5a: Add a record slug

Posted under » CakePHP on 12 Dec 2018

Continued from add a record article where you will notice the form has the id (hidden) but there is no slug. If we were to save an Article right now, saving would fail as we are not creating a slug attribute, and the column is NOT NULL. Slug values are typically a URL-safe version of an article’s title. We can use the beforeSave() callback of the ORM to populate our slug:

// in src/Model/Table/ArticlesTable.php
namespace App\Model\Table;
use Cake\ORM\Table;
// the Text class
use Cake\Utility\Text;
// Add the following method.
public function beforeSave($event, $entity, $options)
{
     if ($entity->isNew() && !$entity->slug) {
     $sluggedTitle = Text::slug($entity->title);
// trim slug to maximum length defined in schema
     $entity->slug = substr($sluggedTitle, 0, 191);
     }
}

You will see that it uses the php substr. This code doesn’t take into account duplicate slugs. But we’ll fix that later on.

Next we learn how to edit a record.

web security linux ubuntu python django git Raspberry apache mysql php drupal cake javascript css AWS data