Cakephp form has to be submitted twice to work - php

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;
}
});

Related

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);
}
}
}

Cakephp form has no data on submit

Using cakephp 1.3 I fill out a form, and upon debugging the submit, I notice that
data:$("#submit-478065271").closest("form").serialize()
is empty. Why would something like that happen? I've checked that the form actually has data, which I can serialize manually. Here is the submit code:
echo $this->Js->submit(
'Sign up',
array(
'class' => 'btn btn_submit fr register_submit register_btn_align',
'url' => array('controller' => 'email_guides', 'action' => 'subscribe'),
'before' => '$(".error-message").remove();' . $this->Js->get('#loading')->effect(
'fadeIn',
array('buffer' => false)
),
'complete' => $this->Js->get('#loading')->effect(
'fadeOut',
array('buffer' => false)
) . 'debugger;',
'success' => 'if(data.success) {
$("#CustomUserFirstName").val("");
$("#CustomUserEmail").val("");
$("#EmailGuidesUserStartDate").val("' . date('d/m/Y', strtotime('+1 Weekday')) . '");
$("#EmailGuidesUserTerms").attr("checked", false);
$("#signupModal").hide();
} else {
$("#signupModal").hide();
}
'type' => 'json'
)
);
?>
<?php echo $this->Form->end(); ?>
UPDATE: I've noticed that the form is not a parent of the submit element ... which is very bizarre. This would explain why .closest("form") returns an empty array.

CakePHP 2.4: Unwanted pre-filled form data

I have a form to add a new user. Only an admin who is logged in may access this form. Unfortunately, the username and the password of the admin are filled into the form fields which are expected to be completely clear. And one really strange thing is: The username is printed into the birthday field!
I really cannot explain myself how it works. And I could not found in the WWW any post from a person who has got the same problem - I only found questions and answers about pre-filled form data that is wanted.
This is the View /Users/add.ctp
<h1>Add a new Member</h1>
<?php echo $this->Form->create('User', array('url' => BASE_URL.'/users/add', 'action'=>'post')); ?>
<table class="form">
<tr><td>Username:</td><td><?php echo $this->Form->input('User.username', array('label' => false, 'div' => false, 'value' => ''));?></td></tr>
<tr><td>Name:</td><td><?php echo $this->Form->input('User.name', array('label' => false, 'div' => false, 'value' => ''));?></td></tr>
<tr><td>Lastname:</td><td><?php echo $this->Form->input('User.lastname', array('label' => false, 'div' => false, 'value' => ''));?></td></tr>
<tr><td>E-Mail:</td><td><?php echo $this->Form->input('User.email', array('label' => false, 'div' => false, 'value' => ''));?></td></tr>
<tr><td>Birthday:</td><td><?php echo $this->Form->input('User.birth', array('label' => false, 'div' => false, 'value' => ''));?></td></tr>
<tr><td>Password:</td><td><?php echo $this->Form->input('User.password', array('label' => false, 'div' => false, 'value' => ''));?></td></tr>
</table>
<?php
echo $this->Form->submit('Submit', array('formnovalidate' => true));
echo $this->Form->end();
?>
And here is the Controller /UsersController.php
public function add() {
$this->layout = 'admin';
if ($this->request->is('post')) {
// Saving the data
$this->User->create();
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('Data saved.'));
return $this->redirect(array('action' => 'view'));
}
$this->Session->setFlash(__('Data could not be saved.'));
}
}
By the way: Saving works fine.
Of course, the admin is of Object User, as is the new member to be added. I think, here lies the problem, but I really do not know... I am thinking about this problem the whole day :( Does anybody know what to do?
Thanks in advance.
Is not your browser? (saved username/password when you type for the first time)
So, you can turn of the autocomplete.
<?php echo $this->Form->create('User', array('url' => BASE_URL.'/users/add', 'action'=>'post', 'autocomplete' => 'off')); ?>
This option => 'autocomplete' => 'off'
Check your $this->data.
CakePHP autocompletes forms with data found there because it guesses that is data already submitted by the user.
In you example, if you have some value in $this->data['User']['birth'] it should show that value in the Birthday input.

remove validation zend form element javascript/jquery

I want to disable the validation on one of the zend form element based on the input on another element on the same form. I need to achieve this using javascript/jquery. Something very common but very surprisingly couldn't find it over the internet.
e.g.
In the controller:
$oFormMassEdit = new Account_Form_Returns_Return();
$this->view->form = $oFormMassEdit;
In Account_Form_Returns_Return's constructor:
$oNoteElement = new Zend_Form_Element_Textarea('option', array(
'required' => true,
));
$this->addElemet($oNoteElement)
$oReasonElement = new Zend_Form_Element_Select('note', array(
'multiOptions' => array (
'return' => 'return',
'defect' => 'Kaput',
'other' => 'Anderer Grund'
),
'required' => true,
));
$this->addElement($oReasonElement);
$this->addDisplayGroup(array('note', 'option'), 'main', array('legend' => 'Retouren'));
$this->addElement('button','send', array(
'type' => 'submit',
'label' => 'Methode speichern',
));
and finally in the view,
<?= $this->form; ?>
Javascript can't (not in a sensible way) switch Zend_Form configuration. What you can do is changing the 'required' param for certain form fields on validation. For example; If you want to allow fieldTwo to be empty if fieldOne has 'desiredValue' as value you can achieve this using the following function in your form:
public function isValid($data) {
if('desiredValue' == $data['fieldOne'])) {
$this->getElement('fieldTwo')->setRequired(false);
}
return parent::isValid($data);
}

Yii framework,CGridView Checkbox help

I want an alert that pops when user tries to click "add to favorite"
1) if there's no checkboxes checked.
2) I also want to know how to get the values of the checked boxes here's my current code on backend
<?php $this->widget('zii.widgets.grid.CGridView',array(
'id' => 'wsrecruitcvhead-grid',
'dataProvider' => $model->search(),
#'filter' => $model,
'columns' => array(
array(
'name' =>'',
'value' => 'CHtml::checkBox("rid[]",null,array("value"=>$data->ResumeID,"id"=>"rid_".$data->ResumeID))',
'type'=>'raw',
'htmlOptions' => array('width'=>5),
'visible' => !Yii::app()->user->isGuest,
),
array(
'name' => 'ResumeTitle',
'value' =>$model->ResumeTitle,
),
'ResumeSummaryIntroduction',
'Name',
array(
'class' => 'CButtonColumn',
'viewButtonUrl' => 'Yii::app()->createUrl("wsrecruitcvhead/view",array("id"=>$data["ResumeID"]))',
'template'=>'{view}',
),
),
));
?>
and here's the screen shot http://pastebin.com/sEpJBCiU
I hope this helps you.
Your code works just fine, just tried it. I would implement the functionality you mentioned using jQuery, like this:
<script type="text/javascript">
$("input:checkbox").click(function () {
var thisCheck = $(this);
if (thisCheck.is (':checked')){
// do what you want here, the way to access the text is using the
// $(this) selector. The following code would output pop up message with
// the selected checkbox text
$(this).val());
}
});
</script>
This code selects all those DOM elements of type checkbox, and then checks with the if condition if it is selected or not. Here you can find more information about this jQuery selector. jQuery is such a powerful tool!!
For get all seleccions of a Grid yii provides the follow code
var seleccions = ($.fn.yiiGridView.getSelection('id_my_cgridview'));
this return an array with the values of checkboxes selected

Categories