I want to create a CakePHP Behavior that will handle the data before they are stored in the db.
For example I have Posts add form like:
// Post title
echo $this->Form->input('title',['value'=>'aaa']);
// Post has many Photos (names)
echo $this->Form->input('photos.0.name',['value'=>'zzz']);
echo $this->Form->input('photos.1.name',['value'=>'hhh']);
echo $this->Form->input('photos.2.name',['value'=>'fff']);
PostsController:
public function add()
{
$post = $this->Posts->newEntity();
if ($this->request->is('post')) {
$post = $this->Posts->patchEntity($post, $this->request->data);
if ($this->Posts->save($post)) {
$this->Flash->success(__('The post has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The post could not be saved. Please, try again.'));
}
}
$this->set(compact('post'));
$this->set('_serialize', ['post']);
}
Data from the form is properly stored in a database.
Next, I bake a new behavior (eg, MyBehavoir), and attach it to PhotosTable. I want to retrieve all three "name" field, process them eg. convert via ucfirst method, and send it back to be stored in the database.
public function beforeMarshal(Event $event, ArrayObject $data, ArrayObject $options)
{
$data['name'] = ucfirst($data['name']);
debug($data);
}
// debug return three outputs for every field
object(ArrayObject) {
name => 'Zzz' // Hhh, Fff
}
But only the first result (Zzz) is saved.
What should I do, to save all fields after processing in Behavior?
Also,
public function beforeSave(Event $event, Entity $entity)
{
debug($entity);
return true;
}
debug show only data from first fields
object(App\Model\Entity\Photo) {
'name' => 'Zzz',
'post_id' => (int) 486,
...