Repopulate Dynamic Dropdown with "set_select" after Form Validation fails in Codeigniter? - codeigniter

I was wondering if it is possible to repopulate a dynamic dropdown(specifically the option of a select) after form validation fails which is generated by another dropdown at on change event.
My jQuery is working good on populating dynamic option of a select as well as at server-side when fetching the data, my only problem is when the form is submitted and validation fails, so basically the dynamic select option/s will reset.
Can somebody help me with this issue?

You have 2 options here:
1) You manually set the 2x select fields with CI and repopulate/set them. You would construct these based on the POST values that were incorrect.
Assuming that list A populates list B which populates list C you may not want to do that. In which case you could define some hidden variables such as this:
var field1 = '<?php $_POST['field1']; ?>';
var field2 = '<?php $_POST['field2']; ?>';
var field3 = '<?php $_POST['field3']; ?>';
$(document).ready(function(){
$('#field1').val(field1).trigger('change'); // or whatever on() query event you use
$('#field2').val(field1).trigger('change'); // or whatever on() query event you use
$('#field3').val(field1).trigger('change'); // or whatever on() query event you use
})
Might help? You would do the trigger to then load whichever lists/ajax calls populate each select box.

Yes it is possible,
this example works with Codeigniter 4 but I'm quite sure it works also with Codeigniter 3. Here I wanted to do a multiple dropdown field with Select2
<div class="form-group">
<label>Categories</label>
<?php
$parameters = array('class' => 'form-control select2_cat', "multiple" => "multiple");
$options = array();
foreach ($categories as $cat) {
$options[$cat['name']] = $cat['name'];
}
echo form_dropdown(
'categories[]',
$options,
set_value('categories[]') != "" ? set_value('categories[]') : 0,
$parameters
);
?>
</div>
You see from the code, I'm using set_value() . I'm checking also if set_value is empty string.
You could find more info here: https://www.py4u.net/discuss/37330

Related

How to create dynamic Checkboxlist in Yii?

I would like a help to solve this problem. I'm using Yii 1.1 and trying to create a dynamic CheckBox list in which its elements change depending on the value selected in a DropDown element.
I created this DropDown element with the arguments in Ajax to perform the function update in the Controller. The function in the Controller is doing the lookup in the table according to the value passed.
Up to this point, the code is working fine, generating an array with the values that should be displayed. The problem is that I'm not able to configure the return of these data and I can't even display them in the View.
Below is the code data:
View - DropDown element:
echo CHtml::activeDropDownList($model, 'standard',
array(CHtml::listData(standard::model()->findAll(), 'name','name')),
array('empty'=>'',
'ajax'=>array(
'type'=>'POST',
'url'=>CController::createUrl('/getTeam',array('form'=>'Team','field'=>'standard')),
'update'=>'#Audit_team'),
)
);?>
Controller:
public function actionGetTeam($form,$field) {
$post = $_POST;
$standard = $post[$form][$field];
$Lists = TblAuditStandard::model()->findAll("standard = $standard");
foreach ($Lists as $List){
$AuditTeam[] = $List->name." - ".$List->login;
asort($AuditTeam);
foreach ($AuditTeam as $id=>$value )
echo CHtml::tag('option',array('value'=>$id),$value,true);
}
}
View - Checkbox element:
<div class="row">
<?php echo $form->labelEx($model,'team'); ?>
<?php echo CHtml::activeCheckBoxList($model,'team',array()); ?>
<?php echo $form->error($model,'team'); ?>
</div>
I hope someone can help me solve this problem. Thanks.

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.

How do I repopulate fields BEFORE validation is passed?

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.

Populating a dropdown based on the selection of another dropdown using Jquery in Codeigniter

I am using Codeigntier and I have the following dropdown in my view file which populates a list of subjects.
<?php echo form_dropdown('subject1', $dropdown_subjects,'',
'class="required" id="subject1"'); ?>
Now when any one selects any value from the dropdown above, I want to send the value to my controller using jquery and query in the following table( SELECT teacherid from table3 WHERE subjectid=$subjectid) to get the teacherid so that I can populate the teacherid list in another dropdown select. If any user changes his selection from the first dropdown I want to get the values of the second dropdown changed also
Table Name: table3
subjectid teacherid
1 1001
2 1003
So the bottom line is I want to populate a dropdown based on another dropdown. I have found couple of tutorials on this topic but I couldn't really understand those(I know I am stupid).
Would you please kindly show me how my view and controller should look like if I want to achieve this?
Thanks :)
EDit
Hi, this is how my controller and view file looks like :
My Controller
$id= $this->input->post('subject_id'); //receiving the ajax post from view
$this->db->select('teachername,teacherid');
$this->db->from('subject_teacher');
$this->db->join('teacher', 'teacher.teacherid = subject_teacher.teacherid');
$this->db->where('subjectid',$id);
$records = $this->db->get('');
$data=array();
$data[''] = 'Select';
foreach ($records->result() as $row)
{
$data[$row->teacherid] = $row->teachername;
}
return ($data); // I need help here... How to send the data as json?
My view:
<script>
$(function(){
$("#subject").change(function(){
$.ajax({
url: "<?echo base_url();?>mycontroller/function",
data: {subject_id: $(this).val()},
type: "post",
success: function(msg){
$("#teacher").html(); // I need help here...how do I get the value from controller and append to my another dropdown named teacher?
})
})
}); // function ends here
</script>
<?php echo form_dropdown('subject1', $dropdown_subjects,'',
'class="required" id="subject1"'); ?>
<select name="teacher" id="teacher">
<option value="">Select</option>
</select>
Please make the necessary changes in my View and Controller for me.
Thanks in Advance :)
You can do this by using jquery ajax. First you post subject_id to ajax page, ajax page will return the list of teacher in combo box and then the result is populated in the first page.
$("#subject").change(function(){
$.ajax({
url: "your-ajax-page-url",
data: {subject_id: $(this).val()},
type: "post",
success: function(msg){
$("#teacher").html();
})
})
This is the edited controller
$id= $this->input->post('subject_id'); //receiving the ajax post from view
$this->db->select('teachername,teacherid');
$this->db->from('subject_teacher');
$this->db->join('teacher', 'teacher.teacherid = subject_teacher.teacherid');
$this->db->where('subjectid',$id);
$records = $this->db->get('');
$output = null;
foreach ($records->result() as $row)
{
$output .= "<option value='".$row->teacherid."'>".$row->teachername."</option>";
}
echo $output; // HTML example
you may do it like this :
you will have to create a function inside your controller which will populate the data but instead of outputting your view you will have to put it inside a var like this
$outout = $this->load->view('myselect_output',$data,TRUE);
and then in your main view you will have to manipulate the DOM with jquery or any other js library ..

how to pass parameters using auto redirect droplist in codeigniter

Hi guys Im trying to make a drop-down list of countries and when the user select a country that redirect to a specific page created dynamically actually i manage to make the redirection work using javascript, but i need to take more parameters to the method inside the controler like the county "id" with out exposing it on the uri, so is that possible using $_post also i should not use button submit.
this is my code
view page
<?php echo form_open('site/country');
$options = array();
$js = 'id="country" onChange="window.location.href= this.form.CTRY.options[this.form.CTRY.selectedIndex].value"';
$options['#'] = "(please select a country)" ;
foreach ($list as $row):
$value= site_url()."/site/country/".url_title($row->name);
$options[$value] = $row->name ;
endforeach;
echo form_dropdown('CTRY', $options,'',$js);
//$test =array ('number' => 10)
//echo form_hidden($test);
echo form_close();?>
this is my method in controller
function country($data)
{
echo 'this is taking you to county= '.$data;
}
Why don't you do something like #Joseph Silber described.
Use jQuery to perform an ajax request when the drop-down list is changed, also managing the redirect?
Something like;
$('#my-drop-down').change(function() {
$.ajax({
url: '/site/country',
type: 'post',
data: $("#my-form").serialize(),
success: function( response.redirect ) {
window.location.href = response.redirect;
},
error: function( response ) {
alert('Oops');
}
});
});
By using serilaize(), you can post all data from the form, or just add the parameters you want to pass.
E.g data: 'id='+$('#id').val()+'&country='+$('#country').val()

Resources