I've inherited a piece of code from an old developer and currently trying to figure out the method behind how it submits.
I'm currently trying to get a quick fix in place where I hide one of his fields to get the form submitting, the issue I'm having is that I can't seem to set the dropdownlist to a default value, which should be United Kingdom, with the id 826 in the database.
echo CHtml::ActiveDropDownList($address, 'country_id', CHtml::listData(Country::model()->findAll(), 'id', 'name', 'continent'), array(
'class' => 'col-md-5 hidden',
'prompt' => 'Select Country',
'label' => 'something here',
'ajax' => array(
'type' => 'POST',
'url' => CController::createUrl('/user/UpdateRegions'),
'dataType' => 'json',
'data' => array('country_id' => 'js:this.value', 'YII_CSRF_TOKEN' => Yii::app()->request->csrfToken),
'success' => 'function(data) {
$("#Address_country_region_id").html(data.country_id);
$("#Address_country_region_id").removeClass(\'hidden\');
if($("#venue_id").val() === "") {
$("#Address_country_region_id").addClass(\'hidden\');
}
}',
)));
$path = CController::createUrl('/admin/user/UpdateRegions');
$id = $address->id;
// On Load
Yii::app()->clientScript->registerScript('ready', '
$.ajax({
type: \'POST\',
dataType : \'json\',
data: {\'country_id\': $(\'#Address_country_id\').val(), \'update_id\' : "' . $id . '"},
url: "' . $path . '",
success: function(data){
$(\'#Address_country_region_id\').html(data.country_id);
}
})
');
How do I get this dropdownlist pointing towards the country_id of 826 as the page loads so I can hide the field and pass the validation of the form.
regards.
this code you pasted does this:
the first part renders a dropdown which does an ajax request on change to /user/UpdateRegions to fill the dependent dropdown for the regions.
the second part does also an ajax request when the page is "ready". So that the region select is filled when the page is ready.
Your script should output the id 826 if you printout the current set id.
If not the value isn't correctly set to the address model.
echo $address->country_id;
If you want to set the default value you can do this at multiple places. e.g. in the controller 'before' the actual submitted value is set or in the model code itself (depends on your code e.g. if you have an additional form model which is extended from your activerecord model).
The correct line in your controller could be before something like this:
$address->country_id= 826;
before one of these lines in your controller
$address->attributes=Yii::app()->request->getQuery(get_class($address));
or
$address->attributes=Yii::app()->request->getPost(get_class($address));
or
$address->attributes=$_POST['address']; // or $_GET
If you have difficulties to find the correct position post some controller code.
I guess you could find some help also here
Yii 1.1: An Easy Solution for Dependent dropDownList Using AJAX
To set default value for $address model, put
$address->country_id = Yii::app()->request->getParam(get_class($address).'[country_id]', 816);
before
echo CHtml::ActiveDropDownList($address, 'country_id', CHtml::listData(Country::model()->findAll(), 'id', 'name', 'continent'), array(
Related
I have a form generated using YII2 ActiveForm. there are some field I need to be on the if I select certain options , or need to have them removed if I select some other option.
For e.g. I Have a dropdown AccountType, with two options "individual" and "company".
If the user selects "individual" some fields on the form needs to go away say company name, and some other fields need to appear such as First name, last name. Initially when the display the form , only the Account Type field is there.
below is the code I have at the moment
<?php
$form = ActiveForm::begin(['id' => 'account-setup-form']); ?>
echo $form->field($modelAccMain, 'account_type')
->widget(Select2::classname(), [
'data' => $accountTypeArray,
'options' => ['placeholder' => 'Select account type'],
]);
echo $form->field($modelUsers, 'firstname')->textInput()
->hint('')->label('First Name');
echo $form->field($modelUsers, 'lastname')->textInput()
->hint('')->label('Last Name');
<?php ActiveForm::end(); ?>
Any help is greatly appreciated.
You can use scenarios for that, first define them in your model and than you can use a if statement in your view
if ($model->isAttributeActive('attribute_name')) {
But like #nterms wrote, if you want the user to be able to switch on the client side, javascript would be better.
Defining scenarios also helps with the validation (only active attributes will be validated).
p.s. Don't forget to set the scenario in your controller
$model = new MyModel(['scenario'=>'my_scenario']);
The way i would handle it is with jquery hide and show using the change event of the dropdown,
In your javascript
Assuming that the data in the select 2 widget is in the form of array
eg:
[1=>"first-item",2=>"second-item",...]
$(document).ready(function(){
var id= //check the id of the select2
on the inspect element id using chrome;
$("#id").on("change", function(){
if(id.value==1){
//show a div
}else{
//hide a div
}
//for multiple values better use switch
like this
switch(id){
case 1:{
$("#divid").show();
......
}
}
})
})
I hope you get the idea,
For the select 2 id you can set it via
echo $form->field($modelAccMain, 'account_type')
->widget(Select2::classname(), [
'data' => $accountTypeArray,
'options' => ['placeholder' => 'Select account type',"id"=>"mypreffereid"],
]);
I'm using standard Yii dependent dropDownMenu (something similar to this). The logic is that current dropDown will define which element (next dropDown) will be updated with controller action.
echo CHtml::dropDownList('level_1', '', $arrayWithValues, aaray(
'ajax'=>array(
'type'=>'POST',
'url'=>Ccontroller::createUrl('myActionName'),
'update'=>'#level_2'
)));
My question is how can I change the update value after the action is executed? i.e the action find out that we need to populate DropDown Level_3 instead of Level_2.
echo CHtml::dropDownList('level_1', '', $arrayWithValues, aaray(
'ajax'=>array(
'type'=>'POST',
'dataType' => 'json',
'data'=>array('selected'=>'js:this.value'),,
'url'=>Ccontroller::createUrl('myActionName'),
'success'=>'js:function(data){
if (data.update==2){
$("#level_2").empty();
$("#level_2").append(data.items);
}
if (data.update==3){
$("#level_3").empty();
$("#level_3").append(data.items);
}
}'
)));
In your controller you'll have selected value as $_POST['selected'].
public function actionmyaActionName()
{
....
do what you need here
$items.=CHtml::tag('option', array('value'=>$value),CHtml::encode($state),true);
....
echo CJSON::encode(array(
'update'=>$update,
'items'=>$items
));
Yii::app()->end();
}
Form your options, define what to update.
Assume I'm in my items controller.
Ok say I am in my view action (the url would be something like /items/view/10012?date=2013-09-30) which lists a list of items that belongs to a client on a given date.
I want to link to add a new item. I would use the htmlhelper like so:
echo $this->Html('action'=>'add');
In my add action I have a form which has fields like client_id and item_date.
When I'm in my view action I know these values as I am viewing the items for a specific client on a specific date. I want to pass these variables to my add action so it will prefill those fields on the form.
If I add a query string in my link ('?' => array('client_id'=>$client_id)) it breaks the add action as it will give an error if the request is not POST. If I use a form->postLink I get another error as the add action's POST data must only be used for adding the record, not passing data to prefill the form.
I basically want to make my link on the view page pass those 2 variables to the add action in the controller so I can define some variables to prefill the form. Is there a way to do this?
Here is my add controller code. It may differ in content a bit from my question above as I have tried to simplify the question a bit but the concept should still apply.
public function add(){
if ($this->request->is('post')) {
$this->Holding->create();
if ($this->Holding->save($this->request->data)) {
$this->Session->setFlash(__('Holding has been saved.'), 'default', array('class' => 'alert alert-success'));
return $this->redirect(array('action' => 'index'));
}
$this->Session->setFlash(__('Unable to add your holding.'), 'default', array('class' => 'alert alert-danger'));
}
$this->set('accounts', $this->Holding->Account->find('list'));
$sedol_list = $this->Holding->Sedol->find('all', array(
'fields' => array(
'id', 'sedol_description'
),
'recursive' => 0,
'order' => 'description'
)
);
$this->set('sedols', Hash::combine($sedol_list, '{n}.Sedol.id', '{n}.Sedol.sedol_description') );
}
Why not use proper Cake URL parameters?
echo $this->Html->link('Add Item', array(
'action' => 'add',
$client_id,
$item_date
));
This will give you a much nicer URL like:
http://www.example.com/items/add/10012/2013-09-30
And then in your controller, you modify the function to receive those parameters:
public function add($client_id, $item_date) {
// Prefill the form on this page by manually setting the values
// in the request data array. This is what Cake uses to populate
// the form inputs on your page.
if (empty($this->request->data)) {
$this->request->data['Item']['client_id'] = $client_id;
$this->request->data['Item']['item_date'] = $item_date;
} else {
// In here process the form data normally from when the
// user has submitted it themselves...
}
}
I added extra select box (choice type) and mapped=>false see the code below.
However when I submit the form. It returned the error msg "This value is not valid."
$form->add('extraField' ,'choice', array(
'required' => false,
'choices' => $arrayChoices,
'mapped'=>false,
'data' =>$id
));
What did I do wrong here?
Ok, after this doc : http://symfony.com/doc/current/reference/forms/types/choice.html#choices
I don't see 'data' option. Try to remove it please. (and , what is the use of this field [data]? )
Are you sure that $id is valid array key for $arrayChoices?
Also, when you submit the form, the request must contain a valid key inside of $arrayChoices
I am having a problem with the form select helper. On my page I have two forms.
One is a quick search form. This one uses state_id.
Upon searching in URL: state_id:CO
This will auto select the correct value in the drop down.
However, when I search with the advanced form. The Field is trail_state_id and
in URL: trail_state_id:CO
For some reason it will not default it to the correct value. It just resets the form to no selections. The values are searhed properly, just the form helper is not recognizing that a field with the same name in the url is set. Any thoughts?
<?php
class Trail extends AppModel {
public $filterArgs = array(
array('name' => 'state_id','field'=>'Area.state_id', 'type' => 'value'),
array('name'=>'trail_state_id','field'=>'Area.state_id','type'=> 'value'),
);
}
?>
in URL: trail_state_id:CO
<?php
echo '<h4>State*:</h4><div>'.$this->Form->select('trail_state_id', $stateSelectList, null, array('style'=>'width:200px;','escape' => false,'class'=> 'enhanced required','empty'=> false));
?>
Using the 3rd argument in the helper you can set a default. I did it the following way;
echo '<h4>State*:</h4><div>'.$this->Form->select('trail_state_id', $stateSelectList, (empty($this->params['named']['trail_state_id']) ? null: $this->params['named']['trail_state_id']), array('style'=>'width:200px;','escape' => false,'class'=> 'enhanced required','empty'=> false));