Skip to content

model behavior draftable

David Spreekmeester edited this page Dec 2, 2014 · 1 revision

Draftable

Use this if you want to be able to publish records in the future, or mark records as draft. This behaviors works with two database columns:

published: a datetime column. Records with a published date before NOW() will not be shown on the site (they do show up in the CMS) online_status: a boolean column. If 1, the record shows up, if 0, it's considered a draft and won't show up.

Simple! There are some things to keep in mind though.

Cache

If you're using caching in your project, as you should, the published column is going to be a problem. If the cache contains the query SELECT * FROM stuff WHERE published >= NOW(), how is it going to know when NOW() and published line up? We use UNIX' at command for this. When a record is saved with a published date, we automatically add a cache clear command to at. That way the cache is cleared at the exact moment the record should show on the site.

Displaying dates

This one's easy: don't forget to use published instead of created when showing the date to your users. Do something like:

<?php
$theDate = $this->blogpost->published ?: $this->blogpost->created;
?>

This is especially important when Draftable is added later on in the project. Often the records show up with unexpected dates because this gets forgotten.

Sorting

How do you sort on the published column when it might be absent? Easy:

<?php
$blogPostModel->select()->order(new Zend_Db_Expr(
'IF(blogpost.published IS NOT NULL, blogpost.published, blogpost.created) DESC'
));
?>

As you can see, the sorting falls back to the created column when published is null. Again, this change often gets forgotten when Draftable is added halfway through a project, leading to unexpected sorting.

Clone this wiki locally