Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 866
fagyi Avatar asked Oct 28 '25 15:10

fagyi


1 Answers

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..

like image 110
xurshid29 Avatar answered Oct 31 '25 07:10

xurshid29



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!