select 2 widget validation with j query in yii2? - javascript

so i have written a code for select field and i am using yii2 here is my code
<?= $form->field($model, 'primaryfield')->widget(Select2::classname(), ['data'
=> $listData,
'options' => ['placeholder'=>'Select', 'multiple' =>
false,'required'=>true], 'pluginOptions' => ['tags' => false, 'tokenSeprators'
=> [',', ' '], 'maximumInputLength' => 20], ],])->label(false); ?>
i want to validate it by using jquery validate plugin i have tried so far validation rules
$('form').validate({
errorClass:'help-block help-block-error',
errorPlacement: function(error, element) {
if(element.attr("name") == "TestModel[primaryfield]" )
{
error.insertAfter(".error_message2");
}
else
error.insertAfter(element);
},
rules: {
'TestModel[email]': {
required:true,
email: true
},
'TestModel[name]':
{
required:true,
},
'TestModel[primaryfield]':
{
required:true
}
},
my email and name getting validated but select2 field(primary field is not getting validate ) i want to apply validation rules only if anyone can give me solutions

With Yii2, You just declare rules in Model. Then,
In your template, enable "enableClientValidation" option of AcitveForm as below:
<?php $form = \kartik\form\ActiveForm::begin([
'enableClientValidation' => true,
'options' => [
'id' => 'ajax-contact-form'
]
]); ?>
With Select2 Widget, it's not enough. So I have to using javascript as below:
$(document).ready(function () {
$("select").on("select2:close", function (e) {
if (!$(this).val()) {
var formGroup = $(this).parent().parent();
formGroup.addClass('has-error');
$('.help-block:first', formGroup).html('Please choose one partner!')
}
});
});
Here is the result on form:
My select2 HTML structure:

Related

Yii2 Javascript fail to print

This is my form field.
As can see, there is a div tag with details id right below the form field. I wanted to print the content inside the div tag out whenever I select the contact.
$url2 = yii\helpers\Url::toRoute('op-client/contact');
$this->registerJs($this->render('script2.js'), \yii\web\VIEW::POS_READY);
$form->field($model, 'contact_id')->widget(Select2::classname(), [
'data' => $getcontact,
'language' => 'en',
'options' => ['placeholder' => 'Select'],
'pluginOptions' => [
'allowClear' => true
],
'pluginEvents' =>
[
'change' => 'function()
{
var contactid = $(this).val();
getDetails(contactid);
"'.$url2.'"
}',
],
]).'
<div id="details">
</div>
Script2.js
function getDetails(contactid,url2)
{
var csrfToken = $('meta[name="csrf-token"]').attr("content");
console.log(contactid);
$.ajax({
type:"POST",
cache:false,
url:url2,
data:{contactid:contactid, _crsf:csrfToken},
success:function(data){
$("#details").html(data);
//document.getElementById("details").innerHTML = data;
},
})
}
Controller
public function actionContact()
{
$request = Yii::$app->request;
$contact = $request->post('contactid');
$contacts =OpContact::find()
->where(['id'=>$contact])
->one();
echo $contacts->name;
}
The problem seems like I cant print out the contact name. I can get the correct contact id but I cant print out the name inside the div tag, it just show blank onchange. Is there anything wrong with my calling method? Thanks

Symfony2 cascasing dropdown value change via ajax not accepting on submission

I have two entity dropdowns field in my symfony form. On the front end i change the option list of 2nd drop drown using ajax based on the value of first dropdown selected value. and Upon submitting the form i get the error that,
This value is not valid.
below is the code;
/**
* #ORM\ManyToOne(targetEntity="State")
* #ORM\JoinColumn(name="province_id", referencedColumnName="id")
*/
protected $Province;
/**
* #ORM\ManyToOne(targetEntity="District")
* #ORM\JoinColumn(name="district_id", referencedColumnName="id")
*/
protected $District;
and in the form,
->add('domicileDistrict','entity', [
'label' => ucwords('District'),
'class'=>'GeneralBundle\Entity\District',
'required' => true,
'mapped' => true,
'attr' => ['class' => 'form-control'],
'label_attr' => ['class' => 'control-label'],
])
->add('domicileProvince','entity', [
'label' => ucwords('Province'),
'class'=>'GeneralBundle\Entity\State',
'required' => true,
'attr' => ['class' => 'form-control select2'],
'label_attr' => ['class' => 'control-label'],
])
and on front end,
$("#profile_from_type_domicileProvince").change(function() {
var state = $('option:selected', this).val();
getDistrictByState(state);
});
function getDistrictByState(state){
var dict = {
type: "POST",
url: "{{ url('ajax_district_by_stateId') }}?id=" + state,
success: function(e) {
$("#profile_from_type_domicileDistrict option").remove();
$.each(e, function(e, p) {
$("#profile_from_type_domicileDistrict").append($("<option />", {
value: e,
text: p
}));
});
}
};
$.ajax(dict);
}
UPDATE: Add PRE_SUBMIT Event;
After suggestion form #Alsatian, I update my form and add the event as below, but nothing happens on selecting first dropdown.
$builder->addEventListener(FormEvents::PRE_SUBMIT, [$this, 'preSubmitData']);
public function preSubmitData(FormEvent $event){
$form = $event->getForm();
$data = $event->getData();
if (array_key_exists('Province', $data)) {
$state = $data['Province'];
$event->getForm()
->add('District','entity', [
'label' => ucwords('District'),
'class'=>'GeneralBundle\Entity\District',
'required' => true,
'mapped' => true,
'query_builder' => function(DistrictRepository $repository) use ($state) {
$qb = $repository->createQueryBuilder('d')
->andWhere('d.verified = :verified')
->andWhere('d.active = :active')
->setParameter('verified', true)
->setParameter('active', true);
if ($state instanceof State) {
$qb = $qb->where('d.state = :state')
->setParameter('state', $state);
} elseif (is_numeric($state)) {
$qb = $qb->where('d.state = :state')
->setParameter('state', $state);
} else {
$qb = $qb->where('d.state = 1');
}
return $qb;
},
'attr' => ['class' => 'form-control select2'],
'label_attr' => ['class' => 'control-label'],
]);
}
}
I had the same problem.
I wrote a bundle here to deal with "extensible" choice types (also entity or document) :
https://github.com/Alsatian67/FormBundle/blob/master/Form/Extensions/ExtensibleSubscriber.php
How I do it :
Hooking in the form submission process, we can access to the submitted entity by the PRE_SUBMIT FormEvent.
All submitted entity are loaded and are in $event->getData().
Then we have just to take this submitted choices as new 'choices' option for the field.
Caution :
Doing it so it will only validate that the entity submitted exist !
If only a part of the entities are possible choices you have to add a constraint to validate them.
You can also set the choices in the PRE_SUBMIT event, depending on the value of the first dropdown (instead of using all submitted entities).

php jQuery autocomplete not working fine in laravel

I've been working to add autocomplete to my Location text field, the problem is when I type any word on it, it always display all the result.
This is my javascript:
<script type="text/javascript">
$(function(){
$("#Location").autocomplete({
source: "{{ route('search.autocomplete') }}",
minLength: 3,
select: function(event, ui){
$("#Location").val(ui.item.value);
}
});
});
</script>
This is the route.php
Route::get('search/autocomplete', ['uses' => 'SearchController#autocomplete', 'as' => 'search.autocomplete']);
This is the searchController
public function autocomplete(Request $request){
$term = $request->get('Location');
$provinces = DB::table('provinces')->where('ProvinceName', 'LIKE', '%'. $term .'%')
->orderBy('ProvinceName', 'desc')
->get();
$results = [];
foreach ($provinces as $province) {
$results[] = ['id' => $province->id, 'value' => $province->ProvinceName];
}
return response()->json($results);
}
and this is the search.blade.php
<div class="form-group col-md-4">
Location: {!!Form::text('Location', Request::get('Location'), ['class' => 'form-control', 'placeholder' => 'What is your location?', 'id' => 'Location', 'style' => 'width: 250px;'])!!}
</div>
Okay I solve my problem, I change
route.php
Route::get('search/autocomplete', 'SearchController#autocomplete');
SearchController
if ($request->ajax()) {
$term = Input::get('term');
$results = array();
$queries = DB::table('provinces')
->where('ProvinceName', 'LIKE', '%'.$term.'%')
->take(5)->get();
foreach ($queries as $query)
{
$results[] = [ 'id' => $query->id, 'value' => $query->ProvinceName ];
}
return Response::json($results);
}
and my Javascript
<script type="text/javascript">
$(function()
{
$( "#Location" ).autocomplete({
source: "{{ url('search/autocomplete') }}",
minLength: 3,
select: function(event, ui) {
$('#Location').val(ui.item.value);
}
});
});
</script>
An array of objects with label and value properties: [ { label: "Choice1", value: "value1" }, ... ]
The label property is displayed in the suggestion menu. The value will be inserted into the input element when a user selects an item. If just one property is specified, it will be used for both, e.g., if you provide only value properties, the value will also be used as the label.
Change
$results[] = ['id' => $province->id, 'value' => $province->ProvinceName];
to
$results[] = ['value' => $province->id, 'label' => $province->ProvinceName];
And
$("#Location").val(ui.item.value);
To
$("#Location").val(ui.item.label);
Use id in frontend as
ui.item.value

Yii2 Checkbox Changes Style

I have a GridView displaying employee payslips, and beside each of their names are check boxes. Refer to the picture below:
As you can see, I also have a drop-down list. I set it in my jQuery to select the last child of the list which is my case, the April 10, 2015 - April 16, 2015 option. On page load, I can see this page (photo above) with those check boxes. I had a problem with the check boxes since when I click the header check box, it should select all of the check boxes below it. But it's not. Now, when I tried selecting another option in the drop-down list, here's what I get:
The style of the check boxes changes. And now, when I check the header check box, it's already working, selecting every check boxes below.
Here's how I display the drop-down list:
echo Select2::widget([
'name' => 'period',
'data' => $period,
'options' => [
'placeholder' => 'Select period',
'id' => 'period',
'style' => 'width: 400px; height: 34px;'
],
'pluginOptions' => [
'maximumInputLength' => 10,
],
]);
GridView:
<?php \yii\widgets\Pjax::begin(['id' => 'employee']); ?>
<?php
echo GridView::widget([
'dataProvider' => $dataProvider,
//'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
['class' => 'yii\grid\CheckboxColumn',
'options' => ['class' => 'icheckbox_minimal',]
],
'fname',
'lname',
'totalEarnings',
'totalDeductions',
'netPay',
[
'label' => 'Action',
'content' => function ($model, $key, $index, $column) {
if ($model->netPay != null) {
return Html::a('View Payslip', ['view' , 'id' => $model->payslipID], ['class' => 'btn btn-success']);
}else{
return Html::a('Create Payslip', ['create-new', 'id' => $model->user_id], ['class' => 'btn btn-warning']);
}
}
]
],
]);
?>
<?php \yii\widgets\Pjax::end(); ?>
Script:
<script>
$(document).ready(function(){
$("#period option:last-child").attr('selected', 'selected');
$("#period").change( function()
{
var period = $('#period').val();
if(period != 0){
$.ajax({
url: 'index.php?r=payslip/periods',
dataType: 'json',
method: 'GET',
data: {id: period},
success: function (data, textStatus, jqXHR) {
$.pjax.reload({container:'#employee'});
//alert(data.start);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log('An error occured!');
alert('Error in ajax request');
}
});
}
}
);
})
</script>
My question is, how do I preserve/maintain the style of the check boxes? And why does it change in style? And why are the styled check boxes not working?
Your checkboxes are changed with javascript to look like that.
You have 2 problems:
1) your "check all" function works just fine, you just need to refresh the status of the checkboxes afterwards. It works like this: when you click on the div that replaces the checkbox then the checkbox gets changed under it. Your problem is that you check it with the scripts so you need to trigger the div that sits on top of it to change too.
2) because you use pjax your page DOM gets changed. However because you probably change the checkboxes on "onload" of the page the new checkboxes remain unstyled. You need to run the function that changes them again after the pjax call.

call function on submit form and display sum of two values

i am working on simple custom module for Drupal 7, which take two numeric values and on submit display sum of two values on same page.
I have form ready, NOT completed but struggling as I am want to call calculateFunction() function when user submit form, takes parameter and sum values...
info
name = form_test
description = Small module which demo how to create input form in custom module.
core = 7.x
Module php
<?php
function form_test_menu()
{
$items['formtest'] = array(
'title' => 'Form Test',
'page callback' => 'drupal_get_form',
'page arguments' => array('form_test_form'),
'access callback' => TRUE,
);
return $items;
}
function form_test_form($form,&$form_submit) {
$form['firstname'] = array(
'#title' => t('First Number'),
'#type' => 'textfield',
'#required' => TRUE,
);
$form['lastname'] = array(
'#title' => t('Second Number'),
'#type' => 'textfield',
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Run Function'));
calculateFunction($form);
return $form;
}
function calculateFunction()
{
echo "sum of two numbers.....";
}
?>
Instead of calling calculateFuction() directly you need to set $form['#submit'] to an array containing the name of the functions you want to call when the form is submitted.
$form['submit'] just creates the submit form element. #submit sets which callback function to submit to.
You may also optionally set $form['#validate'] to validate the submitted data.
See the Form API tutorial at Drupal.org
The submit callback could look something like the following:
/**
* FAPI Callback for form_test_form().
*/
function calculateFunction($form, &$form_state) {
$values = $form_state['values'];
$sum = $values['first_name'] + $values['last_name'];
drupal_set_message('The sum is ' . $sum);
}

Categories

Resources