Cakephp 3 : How to insert data on db from a behavior

57 Views Asked by At

I've created a custom behavior on my CakePHP3 project and I would like to insert data on db from this behavior

Here is an clean exemple of my behavior, the function is well called and save of the form but the ADD Articles request doesn't work...

<?php

namespace App\Model\Behavior;

use Cake\ORM\Table;
use Cake\Event\Event;
use Cake\Core\Configure;
use Cake\I18n\I18n;
use Cake\ORM\Behavior;
use Cake\ORM\Entity;
use Cake\ORM\Query;
use Cake\ORM\TableRegistry;
use Cake\Utility\Inflector;
use App\Controller\AppController;

class HistorizeBehavior extends Behavior
{
    public function beforeSave(Event $event, Entity $entity)
    {
        $this->historize($event, $entity);
    }

    public function historize(Event $event, Entity $entity) {
        $articlesTable = TableRegistry::getTableLocator()->get('Articles');
        $article = $articlesTable->newEntity();

        $article->title = 'A New Article';
        $article->body = 'This is the body of the article';
        $articlesTable->save($article);
    }
}

There is no error, no warning...but the data isn't saved..

Any idea why ? Thanks

0

There are 0 best solutions below