CakePHP Execute query on model and attach it in select - cakephp

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

Related

I want to show some values stored in database in a Joomla article

Hello everyone I want to show some values from the database in a joomla article in the following manner how can I do it ???
I've created the database in the following manner
One way to include php code in your article is to use an extension like
http://extensions.joomla.org/extension/sourcerer
This will allow you to put some php code that will make a query. Doing this in a Joomla way it would look like:
$db = JFactory::getDbo();
$query = $db->getQuery(true)
$query
->select($db->quoteName(array('ques', 'options', 'ans')))
->from($db->quoteName('#__yourtablename'))
->where($db->quoteName('id') . ' = ' . $idOfQuestionYouWantToGrab);
$db->setQuery($query);
$result = $db->loadAssoc();
Now you can show your question:
<?php echo $result['ques']; ?>
then somehow you will need to visualize questions separating them them with some regular expression, since your fields aren't structured well :/
Same with the answers. Then you will need to make some validation with JavaScript to see if answer is the correct one.

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.

Can't populate a Select options with related model info - CakePHP

Puling my hair out with this, I know its something very simple but I've been struggling to resolve it. For the record I'm using cakePHP 2.2.
I'm trying to populate a select input with related model data.
Basically I have users and user_statuses. The user model belongsTo the UserStatus model. Within the user/add() function I want to have a drop down select box populated with the data from the UserStatus model.
Heres the code:
UsersController/Add()
$groups = $this->User->Group->find('list');
$UserStatus = $this->User->UserStatus->find('list');
$this->set(compact('groups', 'UserStatus'));
View/Users/add.ctp
echo $this->Form->input('user_status_id', array('class' => 'span9'));
The field in the users table making the relationship is user_status_id which links to the id in the user_statuses table.
Based on the above the select box will NOT populate with the statuses from the user_statuses table. Interestingly enough, it will if I change the view code to just :
echo $this->Form->input('user_status_id', array('class' => 'span9'));
However, when I do this is will NOT write to the database.
Any help will be gratefully received.
Thanks in advance.
The options param should solve the problems for display and as long as there is a user_status_id in your User table, the below code should save the value in your User model on save.
echo $this->Form->input('User.user_status_id', array('options'=>$UserStatus,'class' => 'span9'));
Should be:
$userStatus = $this->User->UserStatus->find('list');
(note the lowercase 'u')

How to use find('all') in Views - CakePHP

I searched a lot but I couldn't find on How to use the find('all') in Views as used in Rails, but here I'm getting the error "Undefined property: View::$Menu [APP\Lib\Cake\View\View.php, line 804]"
'Menu' is the model which I'm using to fetch data from the menus table.
I'm using the below code in views:
$this->set('test',$this->Menu->find('all'));
print_r($test);
Inside your Menu model create a method, something like getMenu(). In this method do your find() and get the results you want. Modify the results as you need and like to within the getMenu() method and return the data.
If you need that menu on every page in AppController::beforeFilter() or beforeRender() simply do
$this->set('menu', ClassRegistry::init('Menu')->getMenu());
If you do not need it everywhere you might go better with using requestAction getting the data using this method from the Menus controller that will call getMenu() from the model and return the data. Setting it where you need it would be still better, if you use requestAction you also want to cache it very likely.
TRY TO NOT RETRIEVE DATA WITHIN VIEW FILE. VIOLATION OF MVC RULE
try this in view file:
$menu = ClassRegistry::init('Menu');
pr($menu->find('all'));
In AppHelper ,
Make a below function
function getMenu()
{
App::import('Model', 'Menu');
$this->Menu= &new Menu();
$test = array();
$test = $this->Menu->find('all');
return $test;
}
Use above function in view like :
<?php
$menu = $html->getMenu();
print_r($menu);
?>
Cakephp not allow this .
First create the reference(object) of your model using ClassRegistry::init('Model');
And then call find function from using object
$obj = ClassRegistry::init('Menu');
$test = $obj->find('all');
echo ""; print_r($test); `
This will work.

How to populate drop-down list with database values in 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

Resources