Not all fields are fetched from table - cakephp

I'm have a relationship setup between two tables (Contacts and Quotes) and I'm trying to access the information from Contacts Quotes Controller. So in QuoteController.php I have the following code:
$contacts = $this->Quote->Contact->find('list', array('fields' => array(
'Contact.id',
'Contact.name',
'Contact.company',
'Contact.mainAddressLine2',
'Contact.mainAddressTown',
'Contact.mainAddressPostCode',
'Contact.mainAddressCountry'
)));
$this->set(compact('contacts'));
echo '<pre>';
print_r($contacts);
echo '</pre>';
The output from the print_r statement is:
Array
(
[1] => Joe Bloggs
[21] => Jane Doe
)
As you can see I'm only getting the id and name, for some reason the company, mainAddressLine2 etc are coming through in the array.
Ultimately I want the user to be able to select the Contacts name from a drop down list which will then, then details from the Contacts table will be populated in the Quotes view.
Any help appreciated.

$this->Quote->Contact->find('list', will only render a 1d array, change it to all instead of list. You may also want to look into the containable behaviors.
btw pr($contacts); is a built in convenience function of php

If you're looking to get all of the fields listed, why not use a find('all'). The find list, with 2 field params will return array with key->value while adding a 3rd field will group the results. see documentation on find options
$contacts = $this->Quote->Contact->find('all', array('fields' => array(
'Contact.id',
'Contact.name',
'Contact.company',
'Contact.mainAddressLine2',
'Contact.mainAddressTown',
'Contact.mainAddressPostCode',
'Contact.mainAddressCountry'
)));
$this->set(compact('contacts'));
echo '<pre>';
print_r($contacts);
echo '</pre>';

Related

Cakephp insert sql statement

I'd like to insert data into a mysql table using 'the cakephp way'.
I have a multi-stage program that stores data to a session, and toward the end of the program I'd like to write the session data to the database. I could do this using a standard sql insert statement but would like to know how this should be done using cakephp. (Most of the cakephp doc discusses sending data from a webform, and I'd like to manually submit session data.)
Should I manually format the session data in this format and then send this to the model? And if so, is there a helper function for this?
Array
(
[ModelName] => Array
(
[fieldname1] => 'value'
[fieldname2] => 'value'
)
)
Yes, that's the way to do it. There's really no need for a helper function, just use the ones you normally would.
$name = 'Foo';
$city = 'Bar';
$this->ModelName->save(
array(
'name' => $name,
'city' => $city
)
);

CakePHP - Retrieving and working with data from different tables

I'm sorry, I am a newbie in CakePHP and I am a little bit confused in this subject, let me explain:
I have a relationship between two tables. One of the table is Dose and the other is tank. So, one Tank belongs to a Dose. A Dose has many Tanks. The table schema is:
CREATE TABLE `doses` (
`id` INT(10) NOT NULL AUTO_INCREMENT,
`dose` INT(5) NULL DEFAULT NULL,
PRIMARY KEY (`id`)
)
In my Tank view I have the following code:
<?php echo $form->input('dose_id', array('class'=>'input', 'label' => ''));?>
Each 'dose' (field) from Dose table correspond to a value, such as 200, 300, and so forth. I need to use these numbers to calculate others numbers before to insert into my database (table tank). For instance, my code in tanks_controllers:
$t_u = $this->data['Tank']['tipo_uso_id'];
if( $t_u == '1'){
$this->data['Tank']['producao_adubo_diaria'] = $this->data['Tank']['dose_id'] * 0.10;
.
.
.
However, it is bringing to me the ID of the Dose and not the value (dose field). Where can I set up this to bring me the correct data (dose)? I tried to set up this way in my model:
'Dose' => array(
'className' => 'Dose',
'foreignKey' => 'dose_id',
'conditions' => '',
'fields' => 'dose',
'order' => ''
)
It did not work.
I appreciate your time helping me.
Thanks in advance.
it is bringing to me the ID of the Dose and not the value (dose field). Where can I set up this to bring me the correct data (dose)?
You need to get it from the db (model), not from the view. So you need to do a find(). If you are new to Cake, you should read the cookbook first to see how it works.
What does $form->input('dose_id') produce? A dropdown? If so; by default cake will produce a dropdown with the value containing (dose_)id, and the text you see as the value of $displayField(usually name/title).
To do this; if I understand you, you would need to first query doses for all the values and store the result in an array using the dose value as the key AND the value, rather than the id as you normally would. You would then be able to access the actual dose value from $this->data.
$doseArray=array();
$doses = $this->Dose->find('all');
foreach($doses['Dose'] as $k => $v) {
$doseArray[$v] = $v;
}
perhaps. Seems a bit redundant so I might be off.

CakePHP - problem with saving from select field

i have a problem i can't figure out
in my cake app i have a form that saves multiple data..
one of my input fields is a select field so i have in the view:
echo $form->input('Booking.room_id', array(
'type' => 'select',
'options' => $booking_options
));
where $booking_options is an array that outputs:
Array
(
[23] => Room name1
[24] => Room name2
)
so when i save the form...
the values in the Booking table for room_id are not 23 or 24 but instead they save as 13 and 14
where can be the problem?
Not the answer to your problem, but you should try the Cake way of populating Select boxes properly!
In your controller:
function add() {
$this->set('rooms',$this->Booking->Room->find('list'));
}
In your Form
$this->Form->input('room_id');
This will automatically create a select box with the rooms found in the find('list'), this lowers the chance on errors.
(make sure the 'rooms' table uses the fields 'id' and 'name')

whats wrong with this query

I have this in my table model called Table
$test = $this->find('first', array(
'conditions' => array('table.test_id is NULL'),
'order'=> array('table.created ASC'),
)
);
it doesnt work. Tryingt to get the latest row with some criteria
Well, first of all, to get the latest row, you would want to organize by the created field descending, rather than ascending. Also, there are some problems with your syntax, that I have cleaned up below.
$this->find('first', array('conditions'=>array('Table.test_id'=>NULL), 'order'=>array('Table.created'=>'desc')));

How to use OR Condition in Paginate function in Cakephp?

I am facing a problem while fetching values using paginate function in cakephp. In the "to" field of message I have CSV fields of userid. To search messages for a single user. I am using the code below...
$this->set('message', $this->paginate('Message', array(
'or'=> array(
"Message.to LIKE" => "".$this->Session->read('Auth.User.id').",",
"Message.to LIKE" => ",".$this->Session->read('Auth.User.id').","
)
)));
But the query is formed in this manner which is not what I want.. I want to two conditions with OR condition.
SELECT `Message`.`id`, `Message`.`timestamp`, `Message`.`to`, `Message`.`from`,
`Message`.`message`, `Message`.`subject`, `Message`.`urgent`, `Message`.`read`,
`Message`.`tag`, `Message`.`open`, `Message`.`reply_id`, `User`.`id`,
`User`.`fname`, `User`.`lname`, `User`.`user`, `User`.`password`,
`User`.`photo`, `User`.`created`, `User`.`access`, `User`.`login`,
`User`.`status`, `User`.`role`
FROM `messages` AS `Message`
LEFT JOIN `users` AS `User` ON (`Message`.`to` = `User`.`id`)
WHERE `Message`.`to` LIKE ',1,'
ORDER BY `Message`.`timestamp` desc
LIMIT 5
The problem is that your conditions array stumbles across a PHP limitation: an array can not have two keys with the same name.
'or'=> array(
"Message.to LIKE" => "".$this->Session->read('Auth.User.id').",",
"Message.to LIKE" => ",".$this->Session->read('Auth.User.id').","
)
You are using the key "Message.to LIKE" twice, so only the last one gets used.
The workaround looks like this:
'or'=> array(
array("Message.to LIKE" => $this->Session->read('Auth.User.id') . ","),
array("Message.to LIKE" => "," . $this->Session->read('Auth.User.id') . ",")
)
Oh, and you should seriously think about a) database normalization and b) code readability.
I think part of the problem might be that he is using LIKE with only the literal exact match syntax.
If any of the following assumptions are incorrect then ignore this..
But it seems like you are searching for user#domain.tld in the to string and having to attach an 'or' condition to match the case where the recipient is listed as a single email address in a string of comma separated email addresses...
I don't think cake adds the '%' character to LIKE queries automagically so perhaps you could try adding it to the query. This should make it match both cases with a single condition in the find call.
<?php
... snip ...
'conditions' => array(
"Message.to LIKE" => "%" . $this->Session->read( 'Auth.User.id' ) . "%"
),
... snip ...
?>
Just make the condition into an array
$this->set('message', $this->paginate('Message', array(
"Message.to LIKE" => array("".$this->Session->read('Auth.User.id').",",",".$this->Session->read('Auth.User.id').",")
)));

Resources