jquery.validate not working for select box - php

I am trying to give a validation rules for my form.. Foe every field it is working fine but for select box it is not coming fine,,
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery('form#EnrollmentAccountHolderInformationForm').validate({
// ignore: function(){
// return $('form#EnrollmentAccountHolderInformationForm input:hidden, form#EnrollmentAccountHolderInformationForm select');
// },
debug: false,
rules: {
"data[Enrollment][personalinfo_source]": {
required:true
},
"data[Enrollment][person_last_name]": {
required:true
}
}
});
this is my select box name ;- data[Enrollment][personalinfo_source]
Here is code for select box:--
<h4 style="line-height:17px;">How did you hear <br/>about us?*</h4>
<?php $options = array(
'Event Sponsorship' => 'Event Sponsorship',
'Internet'=>'Internet',
'Newspaper' => 'Newspaper',
'Outdoor Advertising' =>'Outdoor Advertising',
'Radio' => 'Radio',
'Telemarketing' => 'Telemarketing',
'Television' => 'Television',
'Social Media' =>'Social Media',
'Other'=>'Other');
echo $this->Form->input('personalinfo_source',array('label'=>false,'id'=>'select','class' => "selectbox",'div'=>false,'options'=>$options, 'tabindex' => '16', 'empty' => 'Select','style' => "width:215px;"));
?>
<div style="clear:both"> </div>
Help me out.

Did you check your HTML code? as per your php code ('id'=>'select'). select box id is "select" not "EnrollmentAccountHolderInformationForm", i am not sure...

Related

cakephp button add more / less fields

Hello I am trying to make a button that would allow me to add 2 additional fields to my form: 1 text type fields and 1 multiple choice selector (see image)
fields
I would like to be able to add these 2 fields as many times and save it in the database here is what the code of these 2 fields looks like:
<div class="zone_prestations">
<div class="form-group">
<?php
echo $this->Form->label(
'Prestation.zone',
'Zone',
'col-sm-2 control-label'
);
echo $this->Form->input('Prestation.zone',
array('div' =>
array(
'class' => 'col-sm-10'
),
'class' => 'form-control'
));
?>
</div>
<div class="form-group">
<?php
echo $this->Form->label(
'Prestation.id_contract',
'Préstation',
'col-sm-2 control-label'
);
echo $this->Form->input(
'Prestation.id_prestation',
array(
'type' => 'select',
'options' => $prestations,
'empty' => 'Selectionnez les préstations',
'div' => array('class' => 'col-sm-10'),
'class' => 'form-control search-select',
'multiple' => true,
'value' => $selected,
'id' => 'prestation_selector'
)
);
?>
</div>
</div>
Do you know how I could do this knowing that I have a multiple choice field. Thank you for your help
Update 20/02/21
<script type="text/javascript">
$(document).ready(function() {
$("select").select2({ width: '100%' });
});
$(document).ready(function () {
var maxField = 10;
var addButton = $('#add_button');
var wrapper = $('#prestation_select');
var x = 1;
var fieldHTML = '<div class="form-group">';
fieldHTML += <?php echo $this->Form->label(
'Prestation.' + x + '.zone',
'Zone',
'col-sm-2 control-label'
);
echo $this->Form->input('Prestation.' + x + '.zone',
array('div' =>
array(
'class' => 'col-sm-10'
),
'class' => 'form-control'
));
?>
fieldHTML +='</div>';
$(addButton).click(function () {
if (x < maxField) {
x++;
$(wrapper).append(fieldHTML);
}
$("select").select2({ width: '100%' });
});
$(wrapper).on('click', '.remove_button', function (e) {
e.preventDefault();
$(this).parent('div').remove();
x--;
});
});
Your code for generating fieldHTML is run once when your page loads, with the current version of x. Every time you click your add button, you'll be getting exactly that, always with "1" in it; it's not re-evaluated with the new x. Solution should be simple, just move the calculation of that HTML inside the add function.
On a separate note, don't decrement x when you click the remove button. If you start with field 1, then add 2 and 3 and 4, then remove 2, x decrementing x will mean that adding another field will give you a duplicate of 4. There's no need for them to be sequential, you just need distinct numbers in there.

Yii drop down with ajax

So what I want to do is populate a dropdown in Yii framework with ajax using my database values in drop down. I using Kartik widget in it here is my dropdown code,
<?php $primaryfield = [1 => 'Business Development(Sales)', 2 => 'Graphic Design', 3 => 'Social Media Marketing', 4 => 'Web Development']; ?>
<?= $form->field($model, 'primaryfield')->widget(Select2::classname(), ['data' => $primaryfield,
'options' => ['placeholder' => 'Enter Your Primary Field', 'multiple' => false], 'pluginOptions' => ['tags' => false, 'tokenSeprators' => [',', ' '], 'maximumInputLength' => 20],])->label(false); ?>
I know everything about Ajax in PHP but don't know how to use it in Yii framework using Kartik widget I have all the primary fields value in my database but unfortunately, I am only able to display them in static basis not dynamic basis using ajax
If I get you clear, you want to have a drop-down list in which their items are dynamically generated by your database.
This is the way you can achieve with kartik dropdown widget.
I'll first create active form field which contains predefined categories as follows
<?php $form = ActiveForm::begin();
//Initialize predefined categories
$data = [
'1' => 'Business Development(Sales)',
'2' => 'Graphic Design',
'3' => 'Social Media Marketing',
'4' => 'Web Development',
];
?>
These field will prompt database to retrieve items for particular category via AJAX
<?= $form->field($model, 'primaryfield')->widget(Select2::classname(), [
'data' => $data,
'options' => ['placeholder' => 'Enter your primary field'],
'pluginOptions' => [
//'allowClear' => true
],
'pluginEvents' => [
"change" => "function() {
var id = $(this).val(); //extract the id of selected category
$.ajax({
method : 'GET',
dataType : 'text',
url : '../yourcontroller/populate?id=' + id,
success : function (response) {
var response = JSON.parse(response);
var myDropDownList = document.getElementById(\"model-item\");
$.each(response, function(index, value) {
var option = document.createElement(\"option\");
option.text = value;
option.value = index;
try {
myDropDownList.options.add(option);
}
catch (e) {
alert(e);
}
});
}
});
}",
],
]);
?>
<?= $form->field($model,'item')->dropdownList(
['prompt'=>'Select Item']
);
?>
Now create action in your controller that will query items from your database based on the category selected and return it to the Item field via ajax.
<?php
public function actionPopulate($id)
{
// the id above is the one selected from the category field so you can use
// that Id now to retrieve items from your item-field with ajax
/* in you case */
$results = Category::find()
->select('items')
->where(['id' => $id])
->asArray()
->all();
//these hard-coded values are for the demonstration
$results = [
'1'=>'maziwa',
'2'=>'ugali',
'3'=>'samaki',
'4'=>'kuku',
'5'=>'mtetea',
];
return json_encode($results);
}
?>
Hope this helps!

Trying to create a dependent combobox in yii using ajax

I am trying to create a dependent combobox system in my Yii application.
First combobox is populated with States and the second one is dynamically generated with ajax and renderPartial() method.
Code below:
View
<?php
$this->widget('ext.combobox.EJuiComboBox', array(
'model' => $adMulti,
'attribute' => 'state_id',
// data to populate the select. Must be an array.
'data' => CHtml::listData(State::model()->findAll(), 'id', 'name'),
'assoc' => true,
// options passed to plugin
'options' => array(
// JS code to execute on 'select' event, the selected item is
// available through the 'item' variable.
'onSelect' => 'getCities(item.value);',
// If false, field value must be present in the select.
// Defaults to true.
'allowText' => false,
),
// Options passed to the text input
'htmlOptions' => array(
'style' => 'height: 36px',
),
));
?>
<script type="text/javascript">
function getCities(state) {
$.ajax({
url: '<?php echo $this->createUrl('ad/ajaxCities'); ?>',
data: {state_name: state},
type: 'POST',
success: function (data) {
$('#city_id-carrier').html(data);
}
});
}
</script>
<div id="city_id-carrier" class="textboxes"></div>
AdController
public function actionAjaxCities()
{
$stateName = isset($_POST['state_name']) ? $_POST['state_name'] : FALSE;
if ($stateName) {
$state = State::model()->findByAttributes(array(
'name' => $stateName
));
$stateId = $state->id;
$cities = City::model()->findAllByAttributes(array(
'state_id' => $stateId
));
$this->renderPartial('_cities', array(
'cities' => $cities,
'stateId' => $stateId
), FALSE, TRUE
);
}
}
_cities.php
<?php
$this->widget('ext.combobox.EJuiComboBox', array(
'model' => AdMulti::model(),
'attribute' => 'city_id',
// data to populate the select. Must be an array.
'data' => CHtml::listData($cities, 'id', 'name'),
'assoc' => true,
// options passed to plugin
'options' => array(
// JS code to execute on 'select' event, the selected item is
// available through the 'item' variable.
// 'onSelect' => 'getLocalities(item.value);',
// If false, field value must be present in the select.
// Defaults to true.
'allowText' => false,
),
));
?>
The code is working and creating the combobox for the first time. But when I change the value in state combobox, something weird happens. A new combobox is created, but the values shown are still from the first combobox generated.
I am getting an error "TypeError: this.input is undefined" in Firebug Console.
I tried creating unique id for combobox using uniqid() but it isn't affecting the id of select element of the combobox.
If I change
$('#city_id-carrier').html(data)
to
$('#city_id-carrier').append(data)
it is working well but with multiple combobox generated.
Any ideas/suggestions to make this work?
I've found a solution to get this working. Instead of creating the combobox dynamically, place the combobox once and then populate it dynamically upon each request. Much like dependent dropdown.
A combobox is a combination of a dropdown and textbox. So, note down the id of the hidden dropdown and update it upon ajax update.
Code:
View:
<?php
$this->widget('ext.combobox.EJuiComboBox', array(
'model' => $adMulti,
'attribute' => 'state_id',
// data to populate the select. Must be an array.
'data' => CHtml::listData(State::model()->findAll(), 'id', 'name'),
'assoc' => true,
// options passed to plugin
'options' => array(
// JS code to execute on 'select' event, the selected item is
// available through the 'item' variable.
'onSelect' => 'getCities(item.value);',
// If false, field value must be present in the select.
// Defaults to true.
'allowText' => false,
),
));
?>
<script type="text/javascript">
function getCities(state) {
$.ajax({
url: '<?php echo $this->createUrl('ad/ajaxCities'); ?>',
data: {state_id: state},
type: 'POST',
beforeSend: function() {
$('#AdMulti_city_id_combobox').val(''); // emptying textbox in case a value is previously selected.
},
success: function (data) {
$('#AdMulti_city_id').html(data); // populating the hidden dropdown.
}
});
}
</script>
<?php
$this->widget('ext.combobox.EJuiComboBox', array(
'model' => $adMulti,
'attribute' => 'city_id',
// data to populate the select. Must be an array.
'data' => CHtml::listData(array(''), 'id', 'name'),
'assoc' => true,
// options passed to plugin
'options' => array(
'allowText' => false,
),
));
?>
AdController
public function actionAjaxCities()
{
$stateName = isset($_POST['state_id']) ? $_POST['state_id'] : FALSE;
if ($stateName) {
$state = State::model()->findByAttributes(array(
'name' => $stateName
));
$cities = City::model()->findAllByAttributes(array(
'state_id' => $state->id
));
$data = CHtml::listData($cities, 'id', 'name');
foreach ($data as $id => $name) {
echo CHtml::tag('option', array('value' => $id),
CHtml::encode($name), TRUE);
}
}
}

How to make second dropdown hide/unhide from the choices of first dropdown?

I'm having problem about making the second dropdown hide/unhide if the selected item is the 1st choice of the first dropdown. Since this is more of front-end, I figured I'd use AJAX.
I'm using X-editable widget, here's the code:
<div class="control-group">
<label class="control-label" for="category">大カテゴリ</label>
<div class="controls">
<?php
$criteria = new CDbCriteria;
$criteria -> condition = 'parent_id=:parent_id AND school_id=:school_id AND status=:status';
$criteria -> params = array(':parent_id' => 0, ':school_id' => $school_account_info -> id, ':status' => 'active');
?>
<?php
$this->widget('editable.EditableField', array(
'id' => 'drop', //ADDED THIS LINE SO I COULD GET THE SELECTED VALUE BUT I GUESS I'M WRONG
'type' => 'select',
'model' => $model,
'attribute' => 'category',
'url' => '/school/Materials_Photos/View',
'source' => Editable::source(AssetCategory::model()->findAll($criteria),'id','category'),
'placement' => 'right',
));
?>
</div>
</div>
//SECOND DROPDOWN (SAMPLE ONLY)
<div class="control-group" id="sub_category" style="display: none">
<label class="control-label" for="category">中カテゴリ</label>
<div class="controls">
<?php echo CHtml::dropDownList('sub_category', '', array(), array('prompt' => 'Select')); ?>
</div>
</div>
But then I saw this:
<script>
$(function(){
$('#status').editable({
value: 2,
source: [
{value: 1, text: 'Active'},
{value: 2, text: 'Blocked'},
{value: 3, text: 'Deleted'}
]
});
});
</script>
and I thought this is more practical, I just couldn't figure how to get the source from ActiveRecord through JS.
Check validate callback. May be it will help you. validate will trigger when you click on the OK button.
Read here. http://x-editable.demopage.ru/index.php?r=site/widgets#Options
Try like this
<?php
$this->widget('editable.EditableField', array(
'id' => 'drop', //ADDED THIS LINE SO I COULD GET THE SELECTED VALUE BUT I GUESS I'M WRONG
'type' => 'select',
'model' => $model,
'attribute' => 'category',
'url' => '/school/Materials_Photos/View',
'source' => Editable::source(AssetCategory::model()->findAll($criteria), 'id', 'category'),
'placement' => 'right',
'validate' => 'js: function(value)
{
console.log(value); //The value you are selecting from x-editable dropdown
if($.trim(value) == "Somthing")
{
//Your functionality
}
}'
));
?>
Could you not simply use jQuery for this?
$(document).ready( function() {
var drop1val = $(".drop1").val();
if (drop1val == "first")
{
$(".drop2").hide();
} else {
$(".drop2").show();
}
});
I'm not sure what the x-editable widget is, I'd just assume however in terms of a general html form, my code should work. Something to think about at the very least.
If your code generates a dropdown list, by creating a then would it be possible for you to add a class or id to that tag?

Cakephp form has to be submitted twice to work

I am trying to sort out an issue with a form submit that I have been unable to understand. When I first submit the form, after changing the value of a dropdown, the $this->request->data array is empty. If I submit again I see what I would expect. This happens every time I change either of the dropdowns on the form.
Here is the form:
<?php
echo $this->Form->create('Refine', array('url' => '/ServiceDirectoryResults/refine'));
echo $this->Form->input('state', array(
'type' => 'select',
'label' => 'State',
'options' => $all_states,
'selected' => array('state_selected', $state_selected),
'id' => 'state',
));
echo $this->Form->input('solution', array(
'type' => 'select',
'label' => 'Solution',
'options' => $solutions,
'selected' => array('selected', $solution),
'id' => 'solutions',
));
echo $this->Form->input('region', array(
'before' => '<fieldset id="Region">',
'multiple' => 'checkbox',
'options' => $regions,
'selected' => $reg_selected,
'after' => '</fieldset>'
));
echo $this->Form->input('tags', array(
'before' => '<fieldset id="TagBox">',
'multiple' => 'checkbox',
'options' => $narrow,
'selected' => $tag_selected,
'after' => '</fieldset>'
));
echo $this->Form->end('Refine Search');
?>
The form is rendering fine. If the states or solutions dropdowns are changed and the form is submitted the $this->request->data array is empty. If I submit a second time, without changing anything, the array contains what I would expect to see.
In my Controller I have
if(isset($this->request->data['Refine']['state']))
{
$state = $this->request->data['Refine']['state'];
}
Obviously if the array is empty I get nothing in the state variable the first time the form is submitted.
I would appreciate it if anyone could shed some light on this behaviour. Have I done something wrong in my form creation?
As requested here is the js that is used with this form. The idea is that it just takes care of setting or clearing the checkboxes if the "All" checkbox, which is the first checkbox created for both regions and tags in the controller.
$(document).ready(function(){
$("#RefineRegion0").click(function(){
if ($("#Region #RefineRegion0").is(':checked')) {
$("#Region input[type=checkbox]").each(function (e) {
$(this).prop("checked", true);
});
} else {
$("#Region input[type=checkbox]").each(function (e) {
$(this).prop("checked", false);
});
}
});
$("#RefineTags0").click(function(){
if ($("#TagBox #RefineTags0").is(':checked')) {
$("#TagBox input[type=checkbox]").each(function (e) {
$(this).prop("checked", true);
});
} else {
$("#TagBox input[type=checkbox]").each(function (e) {
$(this).prop("checked", false);
});
}
});
$("#RefineViewForm").submit(function(){
if($('#state').val() == "" || $('#solutions').val() == ""){
alert("Please select a State and Solution before continuing")
}
});
});
Hope that helps
I noticed two things:
1) The form's url: controllers names are lowercase and underscored: service_directory_results. See the cakephp names convetions: http://book.cakephp.org/2.0/en/getting-started/cakephp-conventions.html . But I think its better to use the array for the url so your routes
can be matched:
echo $this->Form->create('Refine', array('url' => array('controller' => 'service_directory_results', 'action' => 'refine')));
2) On your Js if these fields are empty don't send the post adding return false; (also missing a ;)
$("#RefineViewForm").submit(function(){
if($('#state').val() == "" || $('#solutions').val() == ""){
alert("Please select a State and Solution before continuing");
return false;
}
});

Categories