fagyi
fagyi

Reputation: 93

Symfony create slug from entitys title

I have a working blog but I thought a bit late about nice urls.

I dont want to use slugable and so on bundles because I dont have much time to read documentations and implement them.

Is it possible to reach a field of an entity and generate the slug from that before doctrine executes into the db?

I thought of an easy solution in the entity like:

public function __construct() {
        $this->setPostedAt(new \DateTime());
        $this->setSlug();
    }
public function setSlug(){
        $tmpslug = (string)$this->id."-";
        $tmpslug .= $this->slugify($this->title);

        $this->slug = $tmpslug;
    }

However this will not work as the id and title fields are empty when the construct() called.

Is there any fast solution which wouldnt require to implement a new extension?

Thanks!

Upvotes: 4

Views: 4443

Answers (2)

xurshid29
xurshid29

Reputation: 4210

I dont' think Sluggable (from DoctrineExtensions) will take more time than reinventing the ready wheel.. I'd use it, it takes 10 minutes to be ready to use.

  1. add "stof/doctrine-extensions-bundle": "~1.1@dev" to composer.json
  2. add configs to the config.yml:

config:

stof_doctrine_extensions:
    orm:
        default:
            uploadable: false
            sluggable: true
            timestampable: false
            translatable: false
            tree: false
            blameable: false
            loggable: false
            sortable: false
            softdeleteable: false
  1. add slug field and getter/setter to your entity

code:

private $slug;
public function getSlug() {...}
public function setSlug($slug) {...}
  1. add xmlns:gedmo="http://gediminasm.org/schemas/orm/doctrine-extensions-mapping" to doctrine-mapping section in your ENTITY.orm.xml (if you're using xml)
  2. add slug field to your ENTITY.orm.xml (if you're using xml);

code:

<field name="slug" column="slug" type="string">
    <gedmo:slug fields="title(OR_YOUR_DESIRED_FIELD)" unique="true" updatable="true" />
</field>

that's it, you can forget about it, you don't need to set, event listeners will take care about it..

Upvotes: 5

fagyi
fagyi

Reputation: 93

Okey..Just forgot Lifecycle Callbacks function of doctrine. So the answer is not to put the function call inside the constructor rather update the function with the mapping information:

/**
    * @ORM\PrePersist
    * @ORM\PreUpdate
    */
    public function setSlug(){
        $tmpslug = (string)$this->id."-";
        $tmpslug = $this->slugify($this->title);

        $this->slug = $tmpslug;
    }

also not forget to update the entity mapping

/**
 * @ORM\Entity
 * @ORM\HasLifecycleCallbacks()

Upvotes: 0

Related Questions