Standalone year inputs with CakePHP 2.x FormHelper - cakephp

I am using CakePHP 2.10.20 for a legacy project that requires a field to store a year. So no days or months are needed, just years. I have tried to use the MySQL YEAR field type, as well as an INT(4).
I'm using the FormHelper to create a year input as following ...
echo $this->Form->input('User.test_year', [
'type' => 'date',
'dateFormat' => 'Y',
'minYear' => date('Y'),
'maxYear' => date('Y') + 1
]);
After saving the request data contains an array for the User.test_year field which looks like ...
array(
'User' => array(
'id' => '1',
'test_year' => array(
'year' => '2020'
)
)
)
CakePHP always uses the array format for dates. When I usually debug a full date field (so year + month + day) in the beforeValidate() callback, it is already converted to the proper string format. However, when I try to debug this year-only field in beforeValidate(), it is still formatted as the same array.
Therefore, upon saving, I am confronted with a PHP notice and a MySQL error ...
Array to string conversion [CORE/Cake/Model/Datasource/DboSource.php, line 2220]
Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Array' in 'field list'
SQL Query: UPDATE `my_database`.`users` SET `id` = 1, `test_year` = Array, `modified` = '2020-04-14 23:10:32' WHERE `my_database`.`users`.`id` = '1'
Clearly the year in the array is not being converted into a proper string prior to being inserted into the database. I've also tried to use the FormHelper::year() method instead of the generic FormHelper::input(), but this does not change anything.
Really curious to learn what I'm doing wrong or overlooking, so thumbs up in advance to any CakePHP aficionados willing to point me in the right way.
Stay safe and thanks!

Related

cakephp - order by timestamp DESC not working

I have a table called posts that stores all the posts . It has two columns "Created" and "Modified" .
Below is my query in the model :
$options = [
'conditions' => [
'circle_id' => $my_circle_list,
'team_id' => $this->current_team_id,
'modified BETWEEN ? AND ?' => [$start, $end],
],
'order' => ['modified'=> 'desc'],
'limit' => $limit,
'fields' => ['post_id'],
];
$res = $this->find('list', $options);
Now i want the latest edited posts on top and below is what my mysql dump reads like :
SELECT `Post`.`id` FROM `db`.`posts` AS `Post` WHERE `Post`.`id` IN (125, 124) AND `Post`.`del_flg` = '0' ORDER BY `Post`.`modified` desc LIMIT 20
If i run this query in my database editor ,it gives my the correct output , but in my controller the ordering changes again , this is something i figured after i debugged the array values.
Would be helpful if anyone could tell me if there's any specific reason behind this . The call to this model method from the controller is done in a conventional manner .
When using $this->find() after Cake has queried the database with the generated SQL it calls the afterFind() method on the model where it can manipulate the data. This is the mostly likely place for the ordering to have been modified.

grouping contained models

PresentationView hasMany SlideView
SlideView model has field duration.
The presentation_duration = sum of all SlideView.duration fields from slide views that belong to the presentation.
I want to get list (paged) of presentations with presentation_duration for each presentation.
So far I am trying like this:
$this->paginate['contain'] = array(
'PresentationView' => array(
'SlideView' => array(
'group' => 'SlideView.presentation_view_id',
// 'conditions' => array('group' => 'SlideView.presentation_view_id'),
)
)
);
The commented line is an option that I tried.
Both methods end up with some SQL errors:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'SlideView.group' in 'fieldlist'
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'group' in 'where clause'
It seems that contain doesn not even recognize group key - is it even possible to use grouping like this? If yes how I can do it?
You cannot pass 'group' to your 'contain'. To do what you're hoping to do, you'll need to use JOINs - see CakePHP Joining Tables.

Cakephp + enum support : unable to save or select enum 0 and 1

When I am saving data having two enum fields to manage to manage status of message i.e. read or unread by user. I am using enum ('1','0') to manage status '1' => read and '0'=> unread
following code will save the message but in status column saving empty filed
$data = array(
'message' => 'test message',
'status' => 1
);
$this->Message->save($data);
database structure is as follow
Field Type Collation Null Key Default
------------------ ------------- ----------------- ------ ------ -------
id bigint(20) (NULL) NO PRI (NULL)
message varchar(255) (NULL) NO MUL (NULL)
status enum('0','1') latin1_swedish_ci NO MUL 0
even I have used data array as
$data = array(
'message' => 'test message',
'status' => '1'
);
$data = array(
'message' => 'test message',
'status' => "'".1."'"
);
you are using cakephp - it does (as documented) not support ENUM.
and in your case it is wrong to even use enums in the first place. Enums are used for more than two states and should be emulated as ArrayDatasource or in your model (as I do).
But "read/unread" is a boolean (two definite states!).
and there is an easy way to accomplish this correctly:
tinyint(1) [unsigned] [default 0]
cake will automatically assume this is a boolean and will transform the form field for it into a checkbox.
Right out of the MySql Docs, states the following:
"as explained later in this section—we strongly recommend that you do not use numbers as enumeration values"
http://dev.mysql.com/doc/refman/5.0/en/enum.html

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

Resources