CakePHP Form Helper: Select helper is not defaulting certain custom fields - php

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

Related

Default value in ActiveDropDownList

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(

Removing a field from a form generated by YII2 ActiveForm

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"],
]);

CakePHP prepopulate form with data from a link

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

Codeigniter - How to populate form from database?

I have a small site which allows a user to enter values in a form and then either submit it directly or store the field values in a template to later submit it. To submit the form later, he can load the previously saved template. For that there are three buttons Load Template / Save Template / Submit form.
Because i am using the form validation built-in functionality from Codeigniter i run into problems when i want to populate the form with a template, which had been previously stored.
The form fields are all set up like
$name = array(
'name' => 'name',
'id' => 'name',
'value' => set_value('name', $form_field_values['name'])
);
The variable $form_field_values holds the values from either a loaded template in the case when a template has been loaded or the default values when the form is first loaded.
Initially the form is loaded with the default values. When i click on Load Template the values from the template are not chosen by set_value() because there were the default values in there before. What i want is to replace the values of the form fields with the ones from the template.
Do you have any idea how to do that in a clean approach? What i have done is to introduce a variable to skip the call to set_value() completely like:
$name= array(
'name' => 'name',
'id' => 'name',
'value' => $skip_form_validation ? $form_field_values['name'] : set_value('name', $form_field_values['name'])
);
Where $skip_form_validation is a variable set in the controller, based on what button was pressed. Form validation is skipped for saving/loading a template.
Codeigniter's set_value() function is a simple function which finds value in $_POST if value found then return else returns second argument, you can remove set_value() and write your own code for it. you can write $_POST['field_name'] if you want to populate value of POST data or add whatever value you want to add
Just use like this
$name = array(
'name' => 'name',
'id' => 'name',
'value' => $valueFromYourTemplate
);
You don't need to use set_value() function if you don't want to set POST values in the form
Assuming you retrieve the database fields and pass them to a data array in your controller.
$record = $this->data_model->get_record(array('uid' => $user_id), 'users');
if (!is_null($record)) {
$data['uname'] = $record->username;
$data['loc'] = $record->location;
}
where 'users' is the database table, and the uid is the id field of the table users.
In your form, do something like this
Hope it helps!

how to set the selected option in Symfony forms select box

I have a form created with Symfony forms.
and in the template i have this selectbox, displayed on the page with the render method.
<?php echo $form['field']->render() ?>
is it possible to set the selected option of this select box?
Or does this have to be done in the class that creates this form?
There is the creation of the field done:
public function configure() {
$this->widgetSchema['field'] = new sfWidgetFormSelect(
array("choices" =>
array('1' => 'test1','2' => 'test2')
)
);
}
yes, sure — you should have set corresponding form value — either via bind(), either via widget's default option.
For example,
public function configure()
{
$this->widgetSchema['field'] = new sfWidgetFormSelect(array(
"choices" => array('1' => 'test1','2' => 'test2'),
'default' => 2));
}
Hope I've answered your question.

Categories