How to populate drop-down list with database values in CakePHP - cakephp

I am very new to CakePHP. Could you please explain me the steps needed to populate a select drop-down with values from the database. Please also suggest me some links to the reference.

Simple, if it's a related model in your controller you pass 'list' into the find(); an cake will make an id => value array for you, and the form helper will know exactly what to do with it.
For example say you want to get the list of categories for a product model, this is in your contoller:
$categories = $this->Product->Categories->find('list');
$this->set(compact('categories'));
Then in your view using the form helper, simply create the select element how you normally would any input:
$form->input('category_id');
The form helper will automatically load the $categories variable we set with $this->set().

You make a find in the db and then set the variable via $this->set(yourvariable) in the controller.
In the view you use the "yourvariable" in the select tag
Fill select 1
Fill select 2
Fill select 3

There is a cakeish way to do it with very less effort
$this->set('arrMain',$this->Post->find('list',
array(
'fields'=>array('id','title')
)));
Will give output as ==>
<select id="UserAge" name="data[User][Age]">
<option value="1">The title</option>
<option value="2">A title once again</option>
<option value="3">Title strikes back</option>

in the controller you do:
$this->loadModel('MyModel'); //if it's not already loaded
$options = $this->MyModel->find('all'); //or whatever conditions you want
$this->set('options',$options);
and in the view
<select...>
<?php foreach ($options as $option): ?>
<option value="<?php echo $option['MyModel']['id']; ?>"><?php echo $option['MyModel']['field']; ?></option>
</select>

Example
in your controller Class
$categories = $this->Articles->find('list')->select(['id', 'title'])->toArray();
$this->set(compact('categories')); // pass result dataset to the view
In Your view file
<?php echo $this->Form->select('articles_categories_id', $categories); ?>
Reading Source
http://book.cakephp.org/3.0/en/orm/retrieving-data-and-resultsets.html

Related

CakePHP Execute query on model and attach it in select

In the model i am executing a custom query and pass it to View as following:
$countries = $connection->execute('Select id,country from c_countries')->fetchAll('assoc');
$this->set('countries',$countries);
And in .ctp file i have the following:
<?= $this->Form->input('Country of residence',array('type'=>'select','options'=>$countries)); ?>
I want as value the Id and the Text as country. Instead the result seems very strange. Any help please ?
You should use the find('list') ORM method as detailed on http://book.cakephp.org/3.0/en/orm/retrieving-data-and-resultsets.html#finding-key-value-pairs

cakephp getLastInsertId not working

Here I have used cakephp js helper to send data,After insert One data I need this last id for farther work.Here I have tried bellow code in Addcontroller
if ($this->Patient->save($this->request->data)) {
$lastid=$this->Patient->getLastInsertId();
$patient=$this->Patient->find('all',array(
'conditions'=>array('Patient.id'=>$lastid ),
'recursive' => -1
));
$this->set('patient', $patient);
}
In add.ctp I have tried bellow code but I haven't get last id here.
<?php foreach ($patient as $patient): ?>
<?php echo h($patient['Patient']['id']); ?>
<?php endforeach; ?>
Method getLastInsertId() return id of just saved records.
If you need this id in your view just after save, you must first set that variable in your controller like $this->set(compact('lastid','patient'); and then use in view <?php echo $lastid; ?>
use
if ($this->Patient->save($this->request->data)) {
$id = $this->Patient->id;
$patient=$this->Patient->find('all',array('conditions'=>array('Patient.id'=>$id),'recursive' => -1));
$this->set->('patient', $patient);
//If you are saving the record with ajax which it looks like you
//might be from your question you will need the following instead
//of $this->set->('patient', $patient); try:
return json_encode($patient);
You will then also need to update your js ajax call, you will have a json array to decode so parse it with jquery and append it back into your view.
Cake will always give you the id of record you have just saved, by simply adding $id = $this->MyModel->id; You can use the id to query for the record.
Try below code:
In controller:
$lastid=$this->Patient->getLastInsertId();
$this->set(compact('lastid','patient');
Then use $lastid in View file.
In controller:
$lastid=$this->Patient->getLastInsertId();
$patient['Patient']['last_id'] = $lastid;
then use $patient['Patient']['last_id'] in your view file.

CakePHP how to change select box to checkbox ?

I have two tables store and users.They have one to one relation.After bake store I get user list in a select box.I want to make all selection to check box because farther I want to select multiple users for one store.Now I just need to convert this select box to check box.
I have tried
<?php
echo $this->Form->input('mad_stores_id');
?>
To
<?php
echo $this->Form->checkbox('mad_stores_id');
?>
But this is giving me only one check box.I need to display all option which have given in selection box.
Here is the controller find methods
$users = $this->UserStoreSelection->Users->find('list',array('fields' => array('id','username')));
How can I show all select option in check box ?
If you're relationship is base on One to One, then you shouldn't allow end users to select multiple users for store. That would be a hasMany relationship.
Anyway, here you go
<?php echo $this->Form->input('mad_stores_id', array(
'multiple' => 'multiple')); ?>
Edit: if its multiple checkboxed yo want, then its the following:
<?php echo $this->Form->input('mad_stores_id', array(
'multiple' => 'checkbox')); ?>

CakePHP - Change the "name" attribute of a form input

I have a helper which generates a custom form input.
Helper (simplifed code)
public function customInput($field, array $options = array()) {
$defaultOptions = array(
'class' => 'custom-input',
'label' => false
);
$options = array_merge($defaultOptions, $options);
return $this->Form->input($field, $options);
}
Now how can I modify the name attribute of the input by prefixing it with another 'model'. For example, the input will by default have the following name attribute:
<input type="text" name="data[MyModel][field]" />
But I want it to be:
<input type="text" name="data[_custom][MyModel][field]" />
Mainly, what seems tricky is that I don't know how to get the model name that will be used by default. Also, I need something that works if the default model hierarchy is more complicated, like:
<input type="text" name="data[MyModel][AssociatedModel][field]" />
Would need to be modified to:
<input type="text" name="data[_custom][MyModel][AssociatedModel][field]" />
You want name
echo $this->Form->input('whatever', array('name' => 'data[_custom][MyModel][field]'));
There is nothing like data[_custom][MyModel][AssociatedModel][field] in cakes form helper. Your options as far as automation go is:
field // normal, use current model
Model.field // used with not default model / relations
Model.$i.field // User hasMany Post would be Post.$i.field
For the input helper, CakePHP uses $this->model() to get the name of the current model.
You can see it inside lib\Cake\view\FormHelper, or directly from the online API:
http://api20.cakephp.org/view_source/form-helper#line-942
$modelKey = $this->model();
Maybe that helps.
well you can do: $this->Form->input('_custom.MyModel.field'); to create an input in the format you require.
It becomes a case of passing the appropriate model name and associated model with it.
I don't know how you could do this automatically as obviously each relation is different/may have multiple associations.
So using your helper: echo $this->YourHelper->CustomInput('_custom.MyModel.MyAssociation.field', $options) might do the trick.

how to store an array in the controller and use in the view file in cakephp

In my Users controller, I find the number of forms that the user has created by querying the 'Forms' table and store it in an array. But how to use the array variables in the view file.
Normally, I would set the variable in the controller using set function and use it in the view file as such. But how to set an array in the controller? I get the values in the controller(did an echo).
My controller code is:
function users(){
$this->set('users',$this->User->find('all'));
$users=$this->User->find('all');
foreach($users as $user):
$id=$user['User']['id'];
$userFormCount[$id]=$this->Form->find('count',array('conditions'=>array('Form.created_by'=>$user['User']['id'])));
$userFormCount[$id]=$this->Form->find('count',array('conditions'=>array('Form.created_by'=>$user['User']['id'])));
echo "users : ".$id." ".$userFormCount[$id];
endforeach;
}
My view file:
<?php foreach($users as $user):?>
<tr>
<td class="people_profile">
<?php echo $user['User']['name'];?>
</td>
<td>
<?php
$id=$user['User']['id'];
echo $userFormCount[$id]." ";?>forms, //need the array value here.
0 reports,
0 badges
</td>
</tr>
<?php endforeach;?>
Since I have stored the value in a varaible $userFormCount in the controller, I do not get the value in the view file. but how to set and get an array value?
First of all you should avoid repeating your function calls.
First two lines of your function can be replaced by:
$users=$this->User->find('all');
$this->set('users', $users);
Next you can alter your object before passing it to view and add the property you are calculating to that object.
function users(){
$users=$this->User->find('all');
// notice the & here
foreach($users as & $user):
// you are repeating the same line here as well, that's not necessary
$user['User']['custom_field'] = $this->Form->find('count',
array('conditions'=>array('Form.created_by'=>$user['User']['id'])));
endforeach;
$this->set('users', $users);
}
and you can then use it in your view like any other field that you get from the database. To improve it even firther you may want to consider moving this code to a afterFind callback in your User model, at least if this custom values are used more then once.
You already know how to set an array value :-)
In this code you are setting the array 'users'
$this->set('users',$this->User->find('all'));
So you can do the same for the other array:
$this->set('userFormCount',$userFormCount);
...and read it in the same way as your users variable.
But please look at RaYell's answer, because it explains how to make your current code better.

Resources