cakephp button add more / less fields - php

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.

Related

How to print value from database

I am trying to add new functionality to Storelocator module. I
have added new checkbox in admin and create new column in database
table. Saving checkbox value to databse is working. Now I want to print "recommended" value, but nothing happens. Why?
Checkbox field /Sparx/Storelocator/Block/Adminhtml/Storelocator/Edit/Tab/Form.php
$fieldset->addField('recommended', 'checkbox', array(
'label' => Mage::helper('storelocator')->__('Recommended'),
'onclick' => 'this.value = this.checked ? 1 : 0;',
'required' => false,
'name' => 'recommended',
'value' => '0',
));
Printing value /Sparx/Storelocator/controllers/IndexController.php
<div class="list-content">
<div class="loc-name">{{name}}</div>
<div>{{recommended}}</div>
<div class="loc-addr">{{address}}</div>
<div class="loc-addr3">{{city}}, {{state}} {{country}} {{postal}}</div>
<div class="loc-phone">{{phone}}</div>
<div class="loc-web">{{web}}</div>
{{#if distance}}<div class="loc-dist">{{distance}} {{length}}</div>
<div class="loc-directions">Directions</div>{{/if}}
{{#if storeid}}<div class="loc-desc">Store Details</div>{{/if}}

jQuery: How to get the input value from an input field made with PHP/CakePHP?

I've tried a couple of things and still can't get the value to be returned correctly. Im using CakePHP 2.0v.
Here is my first input field
echo $this->Form->input('semesterFrom', array(
'options' => $semesterOptions,
'empty' => 'Select',
'label' => false,
'class' => 'form-control',
'name' => 'data[student][semester]'));
Here is my second input/select field
echo $this->Form->year('class_yearFrom', date('Y'), 2030, array(
'empty' => __('Select Year'),
'class' => 'form-control year',
'name' => 'data[student][class_year]'));
Ive tried the following.
var attendanceSemesterValue = app.myGoalForm().find('#StudentSemesterFrom').val(); //also variations of :selected and .text()/.val()
var attendanceYearValue = app.myGoalForm().find('#StudentClassYearFromYear :selected').val();
if (attendanceSemesterValue === "Select" && attendanceYearValue === "Select Year") {
var wantedYearValue;
wantedYearValue = 0;
} else {
wantedYearValue = {
'semesterFrom': app.myGoalForm().find('#StudentSemesterFrom :selected').val(),
'yearFrom': app.myGoalForm().find('#StudentClassYearFromYear :selected').val(),
};
var studentRangeValue = app.myGoalForm().find('#StudentRange').is(':checked');
if (studentRangeValue) {
$.extend(wantedYearValue, {
'semesterTo': app.myGoalForm().find('#StudentSemesterTo :selected').text(),
'yearTo': app.myGoalForm().find('#StudentClassYearToYear :selected').text(),
});
}
}

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?

Allow_Remove doesn't remove the collection

I'm setting a fieldset (collection) in my form, and i want allow add and remove elements.. So, my code is:
$hydrator = new Hydrator($this->getObjectManager(), 'Base\Entity\MyElements');
$fieldset = new MyElements();
$fieldset->setObjectManager($this->getObjectManager())
->setHydrator($hydrator)
->setObject(new \Base\Entity\MyElements())
->init();
$this->add(array(
'type' => 'Zend\Form\Element\Collection',
'name' => 'myElements',
'options' => array(
'label' => 'My Elements',
'count' => 1,
'should_create_template' => true,
'allow_add' => true,
'allow_remove' => true,
'target_element' => $fieldset
)
));
I can add elements, but, the remove button doesn't appear.. I'm doing wrong or forgetting something?
PS: My english is very poor, but i'm trying improve it. Sorry. And thanks
The allow_remove option doesnt add the button directly. Remeber that the allow_add also does not add the button. As you can see in the docs you have to add the button
<button onclick="return add_category()">Add a new category</button>
and the js function to add elements:
<script>
function add_category() {
var currentCount = $('form > fieldset > fieldset').length;
var template = $('form > fieldset > span').data('template');
template = template.replace(/__index__/g, currentCount);
$('form > fieldset').append(template);
return false;
}
</script>
exactly as this, you have to add the remove button
<button onclick="return remove_category()">Remove</button>
and the function:
<script>
function remove_category() {
//write your logic to remove the last, or the current element, for isntance:
$('form > fieldset > fieldset').last().remove();
return false;
}
</script>

jquery.validate not working for select box

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...

Categories