How do I repopulate fields BEFORE validation is passed? - codeigniter

The fields I am making required to fill out, should repopulate the correctly filled out fields, while NOT submitting the form and posing errors for the incorrectly filled out fields. What is the best way to do that?
Please note that with this code, I am repopulating the fields as they should be upon submitting the form correctly and they are all displaying when page is reloaded.
<div class="dropdown_structure">
<?php
if($user['location'] == "empty")
{
echo country_dropdown('location');
}
else
{
echo country_dropdown('location',$user['location']);
}
?>
</div>
Also please note that I've tried inserting the value in the input fields.
$data = array( 'name' => 'location', 'value' => $this->input->post('location'));
echo relation_dropdown('location');
Thanks in advance

Hi if you are using the following country dropdown helper you can set value validation in following way
Country dropdown helper
country_dropdown('location',array(),set_value('location'))
even in your second dropdown use set_value('field_name') will work. if validation is failed your selected value will be remain.

Related

Clear validation error message when the value is updated or selected

I have form in yii that validates the form field. When I submit the form it shows the errors.
But when the value of the field with the validation error is updated, the error still present.
I want the message to clear. How should i clear the validation error?
Below the form widget code
<?php $form = $this->beginWidget('CActiveForm', array(
'id'=>'user-form',
'enableAjaxValidation'=>true
)); ?>
In my form I echo the validation error like the code below:
<?php echo $form->error($model, 'firstname'); ?>
I tried the solution from this problem
Trigger Yii field validation onchange of another field
$('#user-form').change(function(){
var settings = $(this).data('settings');
$.each(settings.attributes, function () {
this.status = 2; // force ajax validation
});
$(this).data('settings', settings);
// trigger ajax validation
$.fn.yiiactiveform.validate($(this), function (data) {
$.each(settings.attributes, function () {
$.fn.yiiactiveform.updateInput(this, data, $(this));
});
});
});
But the error message is still not cleared. I have confirmed that the ajax request is sent and there are response as its showed on the firebug console.
[EDIT]
It seems those validation errors for "select" fields are the ones that are not updated/cleared only.
[EDIT]
All the validation errors that are printed/echo after the form is submmitted will not disappear even if the value is supplied or change to satisfy the validation rules.
Place this just above the // trigger ajax validation comment:
$('.errorSummary, .errorMessage').hide();
This should reset the errors before they get re-validated.
In my case I added the code below on the page to remove the red highlight on input field on the form.
$('#user-form select, #user-form input').change(function(){
field = $(this).attr('id');
if($('#'+field+'_em').text() == ''){
$(this).removeClass('error');
}
});
I also add the updateInput function on framework/web/js/source/jquery.yiiactiveform.js so it will remove the validation error for certain field.
if(hasError == false){
$error.toggle(hasError);
$el2 = form.find('#' + attribute.id);
$el2.removeClass(attribute.errorCssClass);
}
I am not sure if this the proper solution but it works for me.
With your form widget code, i don't think ajax validation won't work.
To enable Ajax validation on form you should configure your widget as below,
<?php
$form = $this->beginWidget('CActiveForm', array(
'id'=>'user-form',
'enableAjaxValidation' => true,
'clientOptions' => array(
'validateOnSubmit' => true,
),
));
?>
With this configuration, your form will be validated when form field lost the focus(blur).
Try it, It will give the solution for your problem.

Laravel 3 - How to validate checkbox array, for at least 1 checked?

I'm starting to learn Laravel and still on the learning curve. Now I'm starting with Laravel 3 but will most probably switch my project into Laravel 4 once I get something working.
Now the question being, how to validate an array of checkbox, I want to validate that at least 1 inside the group is enable(checked). I read somewhere on Laravel forum that we just validate them using a required, but when I dd(input::all()) I don't see anything else but the inputs field and checkbox are not part of them...
Part of my Blade Create code for the checkbox:
<label class="checkbox">{{ Form::checkbox('changeReasons[]', 'ckbCRCertification', Input::had('ckbCRCertification'), array('id' => 'ckbCRCertification')) }} Certification</label>
<label class="checkbox">{{ Form::checkbox('changeReasons[]', 'ckbCRDesignCorrection', Input::had('ckbCRDesignCorrection'), array('id' => 'ckbCRDesignCorrection')) }} Design Correction</label>
My controller (REST) code is:
public function post_create()
{
print "Inside the post_create()";
// validate input
$rules = array(
'ecoNo' => 'min:4',
'productAffected' => 'required',
'changeReasons' => 'required'
);
$validation = Validator::make(Input::all(), $rules);
if($validation->fails())
{
return Redirect::back()->with_input()->with_errors($validation);
}
$eco = new Eco;
$eco->ecoNo = Input::get('ecoNo');
$eco->productAffected = Input::get('productAffected');
$eco->save();
return Redirect::to('ecos');
}
I also want to know the correct code for getting the checkboxes state after a validation fails, I thought I saw the Input::had(checkBoxName) somewhere but that doesn't seem to work, I'm probably not using it correctly and I'm getting a little confuse on that since all example I see are for inputs and nothing else. I assume the validation is roughly the same in L4, would it be?
Going back on this project and making some more researches, I have found the best way for this problem is the following.
My blade view:
<div class="control-group row-fluid">
<?php $arrChangeReasons = Input::old('changeReasons', array()); // array of enable checkboxes in previous request ?>
<label class="checkbox">{{ Form::checkbox('changeReasons[]', 'certification', in_array('certification', $arrChangeReasons)) }} Certification</label>
<label class="checkbox">{{ Form::checkbox('changeReasons[]', 'designCorrection', in_array('designCorrection', $arrChangeReasons)) }} Design Correction</label>
</div>
The explanation of the blade view is a 2 steps process, after a validation occur, is the following:
Pull the checkbox array (in my case 'changeReasons[]') with Input::old
From that array we can then search for individual checkbox and see if they are in there, if they are then change the checkbox as a checked state. That is the job of the in_array() function, returning a true/false will change the state of the checkbox.
My controller (REST) code is exactly as it was written in my question at the beginning. For more information, defining $rules = array('changeReasons' => 'required'); will make sure that at least 1 of the checkboxes is checked.
Please remember that Checkboxes need a value like .
It the Checkbox is checked Input::get('foo') will return 1, but if it is unchecked it will return nothing, because it is not in the post-array.
I'm using this code:
if(Input::get('foo')){
$bar->is_foo = 1;
}
else{
$bar->is_foo = 0;
}

Yii ClientSide Validation on Render Partial not Working

I have a Yii form which calls a render partial from another model (team has_many team_members). I want to call via ajax a partial view to add members in team/_form. All works (call, show, save) except for ajax validations (server and client side). If i submit form, member's model isn't validating, even in client side, it's not validating the required fields.
Any clue?
//_form
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'team-form',
'enableAjaxValidation'=>true,
'enableClientValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
'validateOnChange'=>true
),
'htmlOptions' => array('enctype' => 'multipart/form-data'),
)); ?>
//Controller
public function actionMember($index)
{
$model = new TeamMember();
$this->renderPartial('_member',array(
'model'=> $model, 'index'=> $index
)
,false,true
);
}
public function actionCreate()
{
$model=new Team;
$members = array();
if(isset($_POST['Team']))
{
$model->attributes=$_POST['Team'];
if(!empty($_POST['TeamMember'])){
foreach($_POST['TeamMember'] as $team_member)
{
$mem = new TeamMember();
$mem->setAttribute($team_member);
if($mem->validate(array('name'))) $members[]=$mem;
}
}
$this->redirect(array('team/create','id'=>$model->id,'#'=>'submit-message'));
}
$members[]=new TeamMember;
$this->performAjaxMemberValidation($members);
$this->render('create',array(
'model'=>$model,'members'=>$members
));
}
//_member
<div class="row-member<?php echo $index; ?>">
<h3>Member <?php echo $index+1; ?></h3>
<div class="row">
<?php echo CHtml::activeLabel($model, "[$index]name",array('class'=>'member')); ?>
<?php echo CHtml::activeTextField($model, "[$index]name",array('class'=>'member')); ?>
<?php echo CHtml::error($model, "[$index]name");?>
</div>
</div>
ProcessOutput was set to true. No dice.
Switch renderPartial() to render(). No dice.
If you will look at the CActiveForm::run:
$cs->registerCoreScript('yiiactiveform');
//...
$cs->registerScript(__CLASS__.'#'.$id,"jQuery('#$id').yiiactiveform($options);");
Then you will understand that you validation will not work, because you render partial and not the whole page. And these scripts show up at the bottom of the page. So you should solve this by execute these scripts.
After you partial is rendered, try to get activeform script which should be stored at the scipts array:
$this->renderPartial('_member',array('model'=> $model, 'index'=> $index));
$script = Yii::app()->clientScript->scripts[CClientScript::POS_READY]['CActiveForm#team-form'];
after, send it with rendered html to page:
echo "<script type='text/javascript'>$script</script>"
Also remember before you will append recieved html on the page you should include jquery.yiiactiveform.js, if you not already did it(by render another form, or registerCoreScript('yiiactiveform')), on the page from calling ajax request. Otherwise javascript error will raised.
Hope this will help.
Edit:
Sorry I'm not understood that you are render part of form and not the whole. But you validation will not work exactly with the same issue. Because jQuery('#$id').yiiactiveform($options); script was not created for the field.
The actual problem is that the ActiveForm saves its attributes to be validated in the "settings" data attribute. I see you are already using indexes so what you need to add the new elements to this settings object in order for the validation to work. After the ajax response this is what must be done:
//Get the settings object from the form
var settings = $("#form").data('settings');
//Get all the newly inserted elements via jquery
$("[name^='YourModel']", data).each(function(k, v) {
//base attribute skeleton
var base = {
model : 'YourModel',
enableAjaxValidation : true,
errorCssClass : 'error',
status : 1,
hideErrorMessage : false,
};
var newRow = $.extend({
id : $(v).attr('id'),
inputID : $(v).attr('id'),
errorID : $(v).attr('id') + '_em_',
name : $(v).attr('name'),
}, base);
//push it to the settings.attribute object
settings.attributes.push(newRow);
});
//update the form
$("#form").data('settings', settings);
```
This way the ActiveForm will be aware of the new fields and will validate them.
Well, setting processOutput to true in renderPartial (in order to make client validation works on newly added fields) will not help in this case since it will only work for CActiveForm form and you don't have any form in your _member view (only input fields).
A simple way to deal with this kind of problem could be to use only ajax validation, and use CActiveForm::validateTabular() in your controller to validate your team members.

Magento - Can't delete mulitple select value in the product admin

I created a new attribute (multiple select) with some values, everything works fine but when I want to delete all the selected values for a product, I get the message "The product attribute has been saved." but the values are still selected.
Notes:
I press Ctrl + Click to unselect the last value before I save.
I set the parameter Value Required of my attribute to No
If I save a product without any value selected yet, then no values get selected
My Indexes are properly refreshed
See below two screens, on the left the parameters of my attribute and on the right my multiple select.
I'm running out of ideas so thanks for your help.
This is a known (annoying) behaviour of the Magento Adminhtml forms.
The problem is that if no value is selected for the multiselect, no value for that attribute is posted when the form is submitted.
On the server side Magento then loads the model, sets all the posted attribute values on the model and saves it.
Because no value was posted the original value that was loaded on the model wasn't updated.
As a solution for attributes with a custom source model I tend to provide an empty option with a special option value (e.g. -1). That value must not be 0 or an empty string.
Then I specify a backend model for that attribute that checks for that special value in the _beforeSave() method. If it is found the backend model unsets the attribute on the model instance.
Here is an example:
Source Model:
class Your_Module_Model_Entity_Attribute_Source_Example
extends Mage_Eav_Model_Entity_Attribute_Source_Abstract
{
const EMPTY = '-1';
public function getAllOptions()
$options = array(
array('value' => 1, 'label' => 'One'),
array('value' => 2, 'label' => 'Two'),
array('value' => 3, 'label' => 'Three')
);
if ($this->getAttribute()->getFrontendInput() === 'multiselect')
{
array_unshift($options, array('value' => self::EMPTY, 'label' => ''));
}
return $options;
}
}
Backend Model:
class Your_Module_Model_Entity_Attribute_Backend_Example
extends Mage_Eav_Model_Entity_Attribute_Backend_Abstract
{
public function beforeSave($object)
{
$code = $this->getAttribute()->getAttributeCode();
$value = $object->getData($code);
if ($value == Your_Module_Model_Entity_Attribute_Source_Example::EMPTY)
{
$object->unsetData($code);
}
return parent::beforeSave($object);
}
}
If you find a better workaround please let me know.
There is a feature called <can_be_empty> you need to go to your system.xml and add this configuration into your file:
<can_be_empty>1</can_be_empty>
then inspect the element and remove the selected="selected" and hit save, now you can save the multi-select without any values.
Yes I found this a big pain in the bum too BUT it is an improvement on the previous bug which caused drop down attribute selections to be wiped if you tried to update attributes for several products at once.
Anyway, here is my what I do if I want to remove an option from products using a drop down attribute:
Go to Manage attributes
Click Manage Label Options
Add a temporary option to the list
Assign this new attribute option to all the products you want to
change
Delete the temporary attribute option
All solved.
Add a non existent option to html via chrome/firefox developer tool, select that option and save.
eg.
<option value="99999999">Click this to unselect option</option>
Just ran into this problem in Magento 1.7.0.2, my solution :
Use Firefox with Firebug
right-click the multiselect list, choose Inspect with Element and you'll see something like this at the bottom in Firebug :
XLarge
Double-click on selected, right-click, cut, no more selected attribute and just save the page.

How to Repopulate a form field without setting rule as required in Codeigniter?

When I try to populate a form field which is not required in form validation doesn't repopulate. Let's say I have a field but I don't want it to be required but I want it to be repopulated. How can I do it ? I think this is a bug for codeigniter.
This piece of code solved my problem. But I have to use helpers for that. At least I have a solution.
function value_field($field, $default='') {
return (isset($_POST[$field])) ? $_POST[$field] : $default;
}
You have to set a validation rule on a field in order for it to repopulate on an invalid submission. Luckily, you can pass regular PHP functions, not just validation rules, to the set_rules() method so you could just set trim or something rather than required.
$this->form_validation->set_rules('your_field', 'Your Label', 'trim');
That will repopulate the field and not make it a required field.
Using the form helper's set_value() works even for non-required fields, I'm not sure where your problem lies...
echo form_input(array('name' => 'username', 'value' => set_value('username'));

Resources