How to prevent Yii2 generating a new slug when updating a record, if the title or the slug itself is not changed? The generation code itself now looks like this:

 [ 'class' => SluggableBehavior::className(), 'ensureUnique' => true, 'value' => function( $event ) { if( $event->sender->slug ) { $slug = $event->sender->slug; } else { $slug = Inflector::slug( $event->sender->title ); } return $slug . '-test'; }, ] 

The problem is that Yii2 generates slug each time a new one. For example

Adding

nazvanie-test

First update

nazvanie-test-test

Second update

nazvanie-test-test-test

etc.

    2 answers 2

    Under your condition code below. Also note that there is a SluggableBehavior :: immutable property, but it does not fit the condition.

     [ 'class' => SluggableBehavior::className(), 'ensureUnique' => true, 'value' => function( $event ) { if( $event->sender->isAttributeChanged('title') || $event->sender->isAttributeChanged('title')) { return Inflector::slug( $event->sender->title ) . '-test'; } return $event->sender->slug; }, ] 

      I did this:
      When creating a record, we generate a slug.
      When updating - do nothing with the slug.

       public function behaviors() { return [ [ 'class' => SluggableBehavior::className(), 'attribute' => 'title',//поле с которого генерируем слаг 'slugAttribute' => 'surname',//поле которое используется как слаг 'attributes' => [ ActiveRecord::EVENT_BEFORE_INSERT => 'surname',//заполнять при создании //ActiveRecord::EVENT_AFTER_UPDATE => 'surname'//заполнять при обновлении - если надо ], ] ]; }