I want to send request using just choice type, and without submit button, i tried with javascript but no result
My form code:
$form = $this->createFormBuilder()
->add('language', 'choice', array(
'choices' => array(
'ar' => 'Arabic',
'fr' => 'French',
'es' => 'Espagnol',
'nl' => 'Dutch',
'ja' => 'Japanese',
'en' => 'English',
'ko' => 'Korean',
'it' => 'Italian',
'ru' => 'Russian',
),
'required' => false,
'placeholder' => 'Click to Choose Language..',
'attr' => array(
'id' => 'field',
'class' => 'controls',
'data-rel' => 'chosen'
)
))
->getForm();
My twig is as follows:
<form action="{{ path('test_test') }}" method="POST" {{ form_enctype(form) }}>
{{ form_widget(form.language, { 'attr': {'class': 'select2'} }) }}
</form>
The javascript code that i used is :
<script type="text/javascript">
$('#field').change(function() {
$(this).closest('form').trigger('submit');
});
</script>
You can use Jquery submit function like this:
jQuery(function($) {
$(".select2").change(function() { //put class or id of your select input
$('#id_of_your_form').submit();
});
});
EDIT:
If you are using select2 plugin (you have examples here) :
jQuery(function($) {
$('.select2').select2()
.on("change", function(e) {
$('#id_of_your_form').submit();
})
});
And then you can get POST data sending in your Symfony Controller like this :
public function getDataAction(Request $request)
{
dump($request->request->get('name of your select input');exit;
}
Related
I've created some elements with php in order to made up a form. This is the snippet of PHP code:
$builder->add('path', FileType::class, array('label' => 'Submit', 'attr' => array('class' => 'style-1 btn_upload_pdf_php js-btn_upload_pdf', 'id' => 'pdf')));
$builder->add('title', TextType::class, array('label' => 'Flyer\'s name', 'attr' => array('class' => 'style-1 name_pdf js-name_pdf', 'placeholder' => 'Nome del volantino')));
$builder->add('expirationData', DateType::class, array('label' => 'scadenza', 'attr' => array('class' => 'style-1 deadline_pdf js-deadline_pdf', 'placeholder' => 'Nome del volantino', 'id' => 'deadline_pdf')));
I've tried to set path's ID by twig with the following statement:
{{ form_widget(form1.path, { 'id': 'pdf'}) }}
But when I try to get element ($('#pdf')) via JavaScript, it doesn't work. It seems that the element isn't created.
Thx.
to pass id to twig form, you have to do it like that :
{{ form_widget(form1.path, {'attr': {'id': 'pdf'}}) }}
I'm building custom form with select element using Drupal 7 Form Api. I'm attaching #ajax callback to it, which will fire on change event.
$form['landing']['country'] = array(
'#type' => 'select',
'#options' => array(),
'#attributes' => array('class' => array('landing-country-list')),
'#validated' => TRUE,
'#prefix' => '<div id="landing-countries" class="hide">',
'#suffix' => '</div>',
'#title' => 'Select country',
'#ajax' => array(
'wrapper' => 'landing-cities',
'callback' => 'get_cities',
'event' => 'change',
'effect' => 'none',
'method' => 'replace'
),
);
But the problem is that it prevents custom change function on the same select in js. In this function I want to get selected option value. So this will not fire:
$('body').on('change', 'select.landing-country-list', function() {
optval = $(this).find('option:selected').val();
});
This code is in file, which I include in $form:
$form['#attached']['js'] = array(
'https://code.jquery.com/jquery-2.2.4.min.js',
drupal_get_path('module', 'landing') . '/landing.js',
);
Thanks in advance for your help!
If you want to catch before ajax sending you can use :
$(document).ajaxSend(function(){
var val = $('select.landing-country-list').val();
});
Otherwise if you want to get value after ajaxcallback :
$(document).ajaxComplete(function(event, xhr , options) {
if(typeof options.extraData != 'undefined' && options.extraData['_triggering_element_name'] === 'country'){
// only on ajax event attached to country select
var val = $('select.landing-country-list').val();
}
});
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).
I try use callback. If data success update then i need to display modal window. But its not working! Help please! I dont know, how it works. Write me please.
In View
<?php
$this->widget('editable.EditableField', array(
'type' => 'select',
'params' => array('YII_CSRF_TOKEN' => Yii::app()->request->csrfToken),
'model' => $model,
'attribute' => 'category_id',
'url' => $this->createUrl('course/updateSameInfo'),
'source' => Editable::source(Coursecat::model()->findAll(), 'id', 'name'),
'placement' => 'right',
));
?>
In Controller
public function actionUpdateSameInfo()
{
$es = new EditableSaver('Course'); //'User' is name of model to be updated
$es->update();
}
Use success property. Here is the documentation http://x-editable.demopage.ru/index.php?r=site/widgets#Options
Try this
<?php
$this->widget('editable.EditableField', array(
'type' => 'select',
'params' => array('YII_CSRF_TOKEN' => Yii::app()->request->csrfToken),
'model' => $model,
'attribute' => 'category_id',
'url' => $this->createUrl('course/updateSameInfo'),
'source' => Editable::source(Coursecat::model()->findAll(), 'id', 'name'),
'placement' => 'right',
'success' => 'js: function(response, newValue) {
console.log(response); //Open the browser console to check the data
}'
));
?>
As you probably know, Yii does not perform client-side validation with CHtml::ajaxSubmitButton. So after a long time spending on google and stackoverflow, I found that I should use the following link
a-simple-way-to-get-yii-client-side-form-validation-run-when-submitting-by-ajax
Now, It can perform client-side validation. But, the success or complete ajax functions does not fire after validation.
Any Idea?
To be more familiar with topic, I put my codes here:
Yii::app()->clientScript->registerCoreScript('yii');
Yii::app()->clientScript->registerScript('Yii Fix',";$.yii.fix = {
ajaxSubmit : {
beforeSend : function(form) {
return function(xhr,opt) {
form = $(form);
$._data(form[0], 'events').submit[0].handler();
var he = form.data('hasError');
form.removeData('hasError');
return he===false;
}
},
afterValidate : function(form, data, hasError) {
$(form).data('hasError', hasError);
return true;
}
}
};",CclientScript::POS_HEAD);
My form:
$uniqid = uniqid();
$form = $this->beginWidget('CActiveForm', array(
'id' => 'pagescontents-add-new-contents'.$uniqid,
'htmlOptions' => array(
'class' => 'form-horizontal',
'role' => 'form'
),
'enableClientValidation' => true,
'enableAjaxValidation'=>true,
'clientOptions' => array(
'validateOnSubmit' => true,
'validateOnChange'=>false,
'afterValidate'=>'js:$.yii.fix.ajaxSubmit.afterValidate',
),
));
//The rest of code
...
//Ajax submit button
$button_uniqid = uniqid();
echo CHtml::ajaxSubmitButton(Messages::getMessage('ADD_NEW'), $this->createUrl('pagescontents/addPage/'), array(
'beforeSend' => '$.yii.fix.ajaxSubmit.beforeSend("#pagescontents-add-new-contents'.$uniqid.'")',
'type'=>'POST',
'success' => "js:function(data){
$('#page_modal').html('');
$('.modal-backdrop').remove();
$('#pageContents_list').html(data);
}",
),
array(
'class' => 'btn btn-primary',
// 'data-dismiss' => 'modal',
'id' => 'deletesubmit_' . $button_uniqid
)
);
I try your code and find that if you remove the line "'enableAjaxValidation'=>true," your code will work perfectly please check it and let me know that is work for you too or not.