![]() |
|
Snippets |
|
If you want to have a quick drop down (select) menu that automatically takes users to a specific page on your site, this method works well and results in clean URLS. This snippet is for content / urls stored in a database.
There may be a better way to do this, so suggestions are welcome!
First, set up a route like this:
show_content: url: content/:title params: { module: content, action: show }
That way we can have urls like "content/about" or "content/news". (Note you will want to make sure your content titles are URL friendly themselves, perhaps using a stripped_title field instead of the title field that is parsed to replace spaces and punctuation.)
In the peer class of the "content" table we want to create a method we can use to populate our jump menu:
public static function getUrlOptions() { $options = array(); $c = new Criteria(); $c->addAscendingOrderByColumn(self::NAME); $contents = ContentPeer::doSelect($c); foreach ($contents as $content) { $url = sfContext::getInstance()->getController()->genUrl('content/show?id='.$content->getId()); $options[$url] = $content->getTitle(); } return $options; }
in the template we rely on those options and create a select menu with a javascript behavior:
Jump to: <?php echo select_tag('title', options_for_select(ContentPeer::getUrlOptions(), $currentContentUrl), array('onchange'=>'window.document.location = this.value')) ?>
And finally, in the action we store the current url so we can have it pre-selected in the jump menu on the subsequent page:
$this->content = ContentPeer::retrieveByTitle($this->getRequestParameter('title')); $this->currentContentUrl = $this->getController()->genUrl(sfRouting::getInstance()->getCurrentInternalUri());
You now end up with a select menu like this:
<select name="category" onchange="..."> <option value="/content/news">News</option> <option value="/content/sports">Sports</option> ... </select>
Selecting an option from the list will redirect your visitor to the URL stored as the option value.