Search code examples
phpcakephpinternationalizationcakephp-3.0behavior

How do you make a translation field sluggable in CakePHP 3.x


if you ever encountered a problem, when you cannot issue a sluggable behavior on a translated field, I feel ya.

Whenever you save a translation for an entity, 'slug' property is omitted because it's not dirty in the time of saving the translation entity.

  1. You save an entity.
  2. Translations are being created.
  3. The table for i18n has no sluggable behavior attached, so it does not know, when to issue a sluggable behavior on a translated field like title / name etc.

Solution

  • I think I've found a better solution:

    In my SluggableBehavior class, I've updated the behavior to include translations too:

    public function beforeSave(Event $event, EntityInterface $entity) {
        $this->slug($entity);
        if($entity->get('_translations')) {
            foreach($entity->get('_translations') as $key=>$translation) {
                $this->slug($translation);
            }
        }
    }
    

    Of course, simply as it can be, it does not need a separate table :-) But thanks @ndm.