Fork me on GitHub

Model Methods

View alone

after_find

To process an object immediately before it is returned from a find() or paginate() call, define after_find(). This can be useful if you want to always add a commonly-needed property to objects that is something other than the values of the model's table columns.

<?php
class Event extends MvcModel {

  public function after_find($object) {
    if (isset($object->speakers)) {
      $speaker_names = array();
      foreach($object->speakers as $speaker) {
        $speaker_names[] = $speaker->name;
      }
      $object->speaker_names = implode(', ', $speaker_names);
      $object->name = $object->speaker_names;
      if (isset($object->venue)) {
        $object->name .= ' at '.$object->venue->name;
      }
    }
  }

}
?>
View alone

after_save

To always process an object immediately after it is saved, define after_save().

<?php
class Venue extends MvcModel {
  public function after_save($object) {
    $this->update_sort_name($object);
  }
  
  // Use "Colosseum, The" instead of "The Colosseum" for the sort_name
  public function update_sort_name($object) {
    $sort_name = $object->name;
    $article = 'The';
    $article_ = $article.' ';
    if (strcasecmp(substr($sort_name, 0, strlen($article_)), $article_) == 0) {
      $sort_name = substr($sort_name, strlen($article_)).', '.$article;
    }
    $this->update($object->__id, array('sort_name' => $sort_name));
  } 
}
?>

If you'd like to use pretty URLs for a model, define to_url() and make it return the URL path that should be used when links to the object are created. See Pretty URLs for details.