Reputation: 63
I would like to auto-generate a slug from Doctrine in my Symfony 2.4 application, where the slug is unique based upon the year that the record was created. I am using DoctrineExtensions.
For my blog records i want the route to be /blog/{year}/{slug}
So lets say i have these two records
id: 1
title: My Blog Title
createdAt: 2013-08-14 18:48:21
id: 2
title: My Blog Title
createdAt: 2014-02-01 17:12:10
I want both slugs to be my-blog-title
, as they are unique records based upon createdAt
So my two routes would then be
/blog/2013/my-blog-title
/blog/2014/my-blog-title
However, i don't seem to be able to get this to work:
Here is the relevent part of my orm.yml
fields:
title:
type: text
slug:
type: text
gedmo:
slug:
unique_base: createdAt
fields:
- title
createdAt:
type: datetime
gedmo:
timestampable:
on: create
This works, because createdAt is unique for ALL records as it is almost imossible for any two of my records to have the same created date down to the exact same second.
So if i add a third record:
id: 3
title: My Blog Title
createdAt: 2014-03-02 17:12:10
It lets me use the same slug - my-blog-title
In my orm.yml file i want to be able to do something like
unique_base: createdAt("Y")
So that only the year of my created date is used as the base, so i can have the same slug if the records are in different years, but not the same slugs if the records are in the same year.
I know i can pull the date into the slug itself
2014-my-blog-title
but it needs to look like 2014/my-blog-title
Could someone please help with this?
Thanks very much!!!
Upvotes: 1
Views: 1049
Reputation: 63
I finally figured out a workaround, or maybe it's the right way to do it!?
Since i need unique_base to refer to the year i created a record, and not the full timestamp, i made a new field called slugBase.
slugBase is not unique and is slugabble from the createdAt field with the format "Y". So if a record is created on 2014-03-02 slugBase will automatically set to "2014"
So now, when the title changes, slug will only create a slug by the title, using slugBase as the unique_base
Here is my orm.yml
fields:
title:
type: text
slugBase:
type: text
gedmo:
slug:
unique: false
dateFormat: "Y"
fields:
- createdAt
slug:
type: text
gedmo:
slug:
unique_base: slugBase
fields:
- title
createdAt:
type: datetime
gedmo:
timestampable:
on: create
This works nicely as i don't have to do anything manually each time a record is created/updated.
But obviously, when looking up a record i will have to search by slugBase and slug. So my new route will be /blog/{slugBase}/{slug}
Upvotes: 1