Get data from a Form in the beforeSave method of a Model
-
29-06-2021 - |
Question
I already created a register form. I have 3 select-boxes. Day, Month, Year. In my database I have one column called "Birthday" with the format of "date". Now I want to put all three together and insert the result into the database.
public function beforeSave($options = array()){
$this->data['User']['Birthday'] = $this->data['User']['Year'] . '-' . $this->data['User']['Month'] .'-' . $this->data['User']['Day'];
return true;
}
But this is not working :(
None of this fields (Day, Month,Year, Birthday) has validation rules..
How can I do this?
Solution
You can try the following code in your Model:
public function beforeSave($options = array()){
if(!empty($this->data)){
//pr($this->data);die;
$this->data['User']['Birthday'] = date('Y-m-d', strtotime($this->data['User']['Year'] . '-' . $this->data['User']['Month'] .'-' . $this->data['User']['Day']));
unset($this->data['User']['Year']);
unset($this->data['User']['Month']);
unset($this->data['User']['Day']);
}
return true;
}
There must be following form fields should be available into your form:
<?php echo $this->Form->create('User', array('url' => $this->params));
echo $this->Form->input('Year', array('options' => $year_options, 'type' => 'select'));
echo $this->Form->input('Month', array('options' => $month_options, 'type' => 'select'));
echo $this->Form->input('Day', array('options' => $day_options, 'type' => 'select'));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow