0

I have a problem. I'm building a CMS in Cakephp based on the guide on their official website. Everything is going well but I have a problem. As the article adds, no service is generated. Everything is 100% done as per the tutorial.

Can you guess what it is caused by?

I put this in ArticlesTable, but it doesn't seem to work.

<?php
declare(strict_types=1);

namespace App\Model\Table;

use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;
use Cake\Utility\Text;
use Cake\Event\EventInterface;

class ArticlesTable extends Table
{
    public function beforeSave($event, $entity, $options)
    {
        if ($entity->isNew() && !$entity->slug) {
            $sluggedTitle = Text::slug($entity->title);
            $entity->slug = substr($sluggedTitle, 0, 191);
        }
    }

    /**
     * Initialize method
     *
     * @param array $config The configuration for the Table.
     * @return void
     */
    public function initialize(array $config): void
    {
        parent::initialize($config);

        $this->setTable('articles');
        $this->setDisplayField('title');
        $this->setPrimaryKey('id');

        $this->addBehavior('Timestamp');

        $this->belongsTo('Users', [
            'foreignKey' => 'user_id',
            'joinType' => 'INNER',
        ]);
        $this->belongsTo('Editions', [
            'foreignKey' => 'edition_id',
            'joinType' => 'INNER',
        ]);
        $this->belongsTo('Categories', [
            'foreignKey' => 'category_id',
            'joinType' => 'INNER',
        ]);
        $this->hasMany('ArticlesComments', [
            'foreignKey' => 'article_id',
        ]);
        $this->hasMany('ArticlesGalleries', [
            'foreignKey' => 'article_id',
        ]);

    }

Any ideas ?

l3nox
  • 15
  • 2
  • 8
  • You create slug at wrong place. Read https://book.cakephp.org/4/en/orm/entities.html#Cake\ORM\Entity::set – Salines Jun 22 '20 at 21:00
  • @Salines There's nothing wrong with creating slugs in the `beforeSave` handler, unless you want to validate them using application rules, as they are applied before the event is being triggered. – ndm Jun 22 '20 at 21:46
  • 1
    Usually, one would use behaviors for this, https://github.com/dereuromark/cakephp-tools/blob/master/docs/Behavior/Slugged.md for example. Those help to keep this reoccurring logic out of the main app code, it also is a bit more complicated than just using Text::slug() as you need to account for uniqueness and alike. – mark Jun 23 '20 at 10:15

0 Answers0