How to echo selected record? - cakephp

i'm still a beginner, and guess it's a simple CakePHP question...
all i want is to echo retrieved data from database (one row is selected).
i have next code:
$cover_page = $this->Publication->find('list', array('conditions' => array('Publication.id' => $id)));
now, how can i echo field title from selected database row?
tnx in adv!!!

From the cookbook:
find('list', $params) returns an indexed array, useful for any use where you would want a list such as for populating input select boxes.
It will give a result as below
Array
(
//[id] => 'displayValue',
[1] => 'displayValue1',
[2] => 'displayValue2',
[4] => 'displayValue4',
[5] => 'displayValue5',
[6] => 'displayValue6',
[3] => 'displayValue3',
)
Since in your code you've specified the id to make the result only one record
,you may not really need to use it, though you can access the title with $cover_page[$id] if you've set the right displayfield.A normal way to do your work would be
$cover_page = $this->Publication->find('first', array('conditions' => array('Publication.id' => $id)));
or
$cover_page = $this->Publication->findById($id);
Both of them can get the title by
$cover_page['Publication']['title']

You access it like this (CakePHP creates an array of the database result):
echo $cover_page['Publication']['title'];
To get it into the view do:
$this->set('cover_page',$cover_page);

Related

How to get only one row from a table using cakephp

I'm trying to retrieve data from one of the rows of a table using cakephp, and I want to get the values from the extracted row.
P.s. I've tried to follow cakephp's find(), but did not get anything, got an error instead.
Error`$login_id = $this->AppAuth->user('id');
$userSettings= $this->loadModel("UserSettings");
$userSetting= $this->$userSettings->find('first', array(
'conditions' => array('UserSettings.user_id' => $login_id)));`
From cakephp siteGot it.
$query = $internSettings->find('all', [
'conditions' => ['InternSettings.intern_id' => $login_id]
]);
$row = $query->first();
Now that I can retrieve a row, how am I suppose to access the values of the row?
$record = $internSettings->find('all', [ 'conditions' => ['InternSettings.intern_id' => $login_id]])->first();
This will returns Entity object in $record, you can access field by
echo $record->field_name;
or you can convert it in array and then you can access
$recordArr=$record->toArray();
echo $recordArr['field_name'];

Settings page and multi edit rows

I would like to make a configuration page like this for my CMS
http://img4.hostingpics.net/pics/72087272ok.png
I want this page (admin/settings/index) gets me the various settings (ID 1 to 21) came to my table and in case of change, I can, in this form, do an update
After 3 days of not especially fruitful research I found something. I put in my SettingsController:
admin_index public function () {
if (!empty($this->data)) {
$this->Setting->saveAll($this->request->data['Setting']);
} else {
$this->request->data['Setting'] = Set::combine($this->Setting->find('all'),
'{n}. Setting.id', '{n}. Setting');
}
}
and my view:
<?php
echo $this->Form->create('Setting', array ('class' => 'form-horizontal'));
foreach($this->request->data['Setting'] as $key => $value) {
echo $this->Form->input('Setting.' . $key . '.pair');
echo $this->Form->input('Setting.' . $key . '.id');
}
echo $this->Form->end(array('class' => 'btn btn-primary', 'label' => 'Save',
'value' => 'Update!', 'div' => array ('class' => 'form-actions')));
?>
he is recovering well all my information, I can even update. The trouble is that I do not really know how I can do to get the same result as my first screenshot. He puts everything in the textarea while in some cases I want the checkbox and / or drop-down.
please help me or explain to me how to make a page that retrieves configuration information from my table and allows me to edit without use an address like admin/settings/edit/ID
My table settings is something like this here
http://img4.hostingpics.net/pics/724403settings.png
If you are asking about how to format the output to produce a "settings" page, you will need to do it manually or add some kind of metadata to your table schema, such as "field_type".
Now Cake will automatically generate a checkbox for a boolean or tiny int, for example, but as you have varchars, ints, texts and so on, this won't work for you (pair is presumably varchar or text to allow for the different possible values.
You cannot really automagically generate the outputs you want without telling Cake.
One option would be to add a field_type to the table, so:
key value field
site_name My Site input
site_online 1 checkbox
meta_desc [some text] textarea
and something like
foreach($settings as $setting) {
echo $this->Form->{$setting['field']}($setting['key'],
array('value' => $setting['value']));
}
might do what you are after.
Or if($key=='site_name') // output a textbox
but this is not exactly ideal.

How do I get data from associated models in CakePHP?

I create a simple blog with cakephp where i have some posts and some comments.
After i bake an application it create a comments folder with the index.ctp and a posts folder with the index.ctp
What i want to do is display them as fallow:
Post1
comment1
comment2
Post2
comment1
comment2
If i place the comments inside the posts/index.ctp i get an error telling me that the $comments is not defined.
How can i do this?
Thanks
edit:
alright, im sorry for the comeback, but it's still a bit unclear. I do have the $hasMany relationship setup, in fact on the page that displays the posts i have a link that points me to the comments. The only thing that i want them to be displayed in the same page as the posts.
i should be able to say <?php echo $comment['Comment']['content']; ?>
Check your controllers.
If you want to display Comment information in a Posts view, you need to be sure that the Posts controller can load the data.
The "CakePHP" way is to define relationships between models. Check your baked models and see if there is something like this:
class Post extends AppModel{
var $hasMany = array( 'Comment' );
}
When the models are associated with each other, your Posts controller will automatically find Post objects and their associated Comment objects.
For instance, this line:
$this->Post->findById( $id );
Will produce something like this:
Array
(
[Post] => Array
(
[id] => 42
[text] => Post1
)
[Comment] => Array
(
[0] => Array
(
[id] => 1
[post_id] => 42
[text] => Comment1
)
[1] => Array
(
[id] => 2
[post_id] => 42
[text] => Comment2
)
)
)
Good documentation at http://book.cakephp.org/
Model Associations
Retreiving Data
EDIT: Adding more info after your comment
As long as the models have the association, CakePHP will pull the data appropriately (unless you set Recursive => false or are using Containable which I assume you aren't).
Check your PostsController controller and see how it's loading the data. I'm guessing it is doing something like the following:
$post = $this->Post->findById( $id );
$this->set( compact( 'post' ) );
or
$this->data = $this->Post->findById( $id );
Check which way it is storing the retrieved data, and then access that variable from the view.
For example, if it is storing the data in a variable named "$post", you would put something like this in your view:
// output the 'text' field of the 'post' object
echo $post[ 'post' ][ 'text' ];
// loop through associated comments
foreach ( $post[ 'comment' ] as $comment ){
//output the 'text' field of a 'comment' object
echo $comment[ 'text' ];
}
By default CakePHP stashes tons of detail in arrays after retrieving data. The trick is to know the hierarchy of the data and fetch it from the array accordingly.

Get threaded results for associated model in CakePHP

I have 2 database-tables which are connected as followed:
ProjectProduct hasMany Bde
Bde belongsTo ParentBde / Bde hasMany ChildBde
The first association is new and shall be added into the application now. Since then I used $this->Bde->find('threaded') to get an threaded array of these records.
Now I need/want to query the ProjectProduct-table and wanted to use the containable-behavior to get all associated Bdes.
Now I'm wondering: Is it possible (in a Cake way) to still get threaded results with a call of find on ProjectProduct?
I tried doing $this->ProjectProduct->find('threaded', array('contain' => 'Bde')) but this will try to get threaded results on ProjectProduct.
I'm expecting an array like this:
Array (
[ProjectProduct] => Array (
[id] => 17,
[Bde] => Array (
[0] => Array (
[id] => 1,
[project_product_id] => 17,
[children] => Array()
)
)
)
)
Since I couldn't find any information how this can be done in one call or the "Cakish" way, I've done it like this:
$project_products = $this->Project->ProjectProduct->find('all');
foreach ($project_products as $key => $project_product) {
$project_products[$key]['Bde'] = $this->Project->Bde->find('threaded', array('conditions' => array('Bde.project_product_id' => $project_product['ProjectProduct']['id'])));
}
If someone has a better way in doing this I really appreciate any other ideas!

CakePHP pre populate select box based on existing selection on related model

I am trying to pre-populate this State select box with the existing selection when editing records.
in a related model.
plan_details/view.ctp
echo $this->Form->input('State',array('empty' => false,'options' => $state));
plan_details_controller view function:
$state = $this->PlanDetail->Plan->State->find('list');
$this->set(compact('state', $state));
debug($state);
Array output in view.ctp (as expected):
Array
(
[1] => Oregon
[2] => Washington
)
My select box above defaults to 1 in the array. I need it to default to the already existing selected value.
For example, when I added a record and a selected Washington(2), then when viewing my edit screen, the pre-selected value should be Washington with value 2.
I'm stuck and cracking at this for a while. Any idea what I am doing wrong?
If you are editing a page you need to set $this->data to auto populate it. Within your edit action
if (empty($this->data)) {
$this->data = $this->PlanDetail->read(null, $id);
}
This should read in the record then ( note the plural )
$states = $this->PlanDetail->Plan->State->find('list');
$this->set(compact('states'));
In your form it should read
echo $this->Form->input('Plan.state_id',array('empty' => false));
I find your approach a bit confusing but the above should work. Is this form for editing a Plan, PlanDetail or both

Resources