Code snippets for symfony 1.x


Refine Tags

Snippets tagged "select"

select_range_tag() for admin generator

Sometimes you may want to give the user the possibility to select a certain range of numbers in a numeric field in the admin generator. An example would be a rating between 1 and 5. This is where this snippet comes in handy.

Add the helper code below to one of your helper groups, that preferably is included in your standard_helpers. Then you can use it like in your generator.yml like follows:

      display: [..., percentage, ...]
        percentage: { type: select_range_tag, params: min=0 max=100 step=5 }

Supplying a step is optional, it defaults to 1.

Helper code:

function select_range_tag($name, $selected, $options)
  $options = _parse_attributes($options);
  $select_options = range(_get_option($options, 'min', 1), _get_option($options, 'max', 5), _get_option($options, 'step', 1));
  return select_tag($name, options_for_select(array_combine($select_options, $select_options), $selected));
function object_select_range_tag($object, $method, $options = array(), $default_value = null)
  $options = _parse_attributes($options);
  $value = _get_object_value($object, $method, $default_value);
  return select_range_tag(_convert_method_to_name($method, $options), $value, $options);
by Martin on 2007-05-07, tagged admin  generator  input  range  select  tag 

Navigation Jump Menu Drop Down

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:

  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();
  $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>

Selecting an option from the list will redirect your visitor to the URL stored as the option value.

by scott meves on 2007-04-09, tagged jump  menu  select 

Select with a onChange remote function option

If you need to call a remote function with the parameter of the changed select .

Nota for François : Could be cool to have a better documentation of remote_function.

Here is the editSuccess.php

  <?php echo __('Domains:')  ?>
  <?php echo form_error('domain') ?>
  <?php echo select_tag('domain', objects_for_select(
           $domains, 'getIdDomain', 'getName',
           $list->getDomain(), 'include_custom='.__('Choose a domain')),
               'onchange' =>
                   'update' => 'item_domain',
                   'url' => 'list/subdomain',
                   'with' => "'id=' + this.options[this.selectedIndex].value"
           ) ?>
  <?php echo __('Sub domains:')?>
  <?php echo form_error('sub_domain') ?>
  <div id="item_domain">
  <?php echo select_tag('sub_domain', objects_for_select(
           $list_sub_domains, 'getIdDomain', 'getName',
           'include_custom='.__('Choose a sub domain')
           )) ?>

Here is the subdomainSuccess.php

<?php use_helper('Object') ?>
<?php echo select_tag('sub_domain', objects_for_select(
           $list_sub_domains, 'getIdDomain', 'getName',
           0, 'include_custom='.__('Choose a sub domain')
           )) ?>
by mlier on 2007-03-24, tagged ajax  remote  select 
(1 comment)

Rich select_date_tag

select_date_tag is not available in 'rich' version. Waiting for a real enhancement, this is my workaround.

This is the RichDateHelper.php file:

function rich_select_date_tag($name, $value = null, $options = array(), $html_options = array()) {
    $context = sfContext::getInstance();
  if (isset($options['culture']))
    $culture = $options['culture'];
    $culture = $context->getUser()->getCulture();
    // register our javascripts and stylesheets
  $langFile = '/sf/js/calendar/lang/calendar-'.strtolower(substr($culture, 0, 2));
  $jss = array(
    is_readable(sfConfig::get('sf_symfony_data_dir').'/web/'.$langFile.'.js') ? $langFile : '/sf/js/calendar/lang/calendar-en',
  foreach ($jss as $js)
  $js = '
        function updateSelect(cal) {
            var date =;
            var selectMonth = document.getElementById("'.get_id_from_name($name).'_month");
            selectMonth.selectedIndex = date.getMonth();
            var selectDay = document.getElementById("'.get_id_from_name($name).'_day");
            selectDay.selectedIndex = (date.getDate() - 1);
            var selectYear = document.getElementById("'.get_id_from_name($name).'_year");
            selectYear.selectedIndex = (date.getFullYear() - '.$options['year_start'].');
    document.getElementById("trigger_'.$name.'").disabled = false;
            inputField : "'.$name.'_rich_sel_date",
            ifFormat : "%Y-%m-%d",
            button : "trigger_'.$name.'",
            singleClick : true,
            onUpdate : updateSelect,
            showsTime : false,
            range : ['.$options['year_start'].', '.$options['year_end'].'],
            showOthers : false,
            cache : 1,
            weekNumbers : false,
            firstDay : 1
    $html = select_date_tag($name, $value, $options, $html_options);
  // calendar button
  $calendar_button = '...';
  $calendar_button_type = 'txt';
  if (isset($options['calendar_button_img']))
    $calendar_button = $options['calendar_button_img'];
    $calendar_button_type = 'img';
  else if (isset($options['calendar_button_txt']))
    $calendar_button = $options['calendar_button_txt'];
    $calendar_button_type = 'txt';
  if ($calendar_button_type == 'img')
    $html .= image_tag($calendar_button, array('id' => 'trigger_'.$name, 'style' => 'cursor: pointer'));
    $html .= content_tag('button', $calendar_button, array('type' => 'button', 'disabled' => 'disabled', 'onclick' => 'return false', 'id' => 'trigger_'.$name));
  // add javascript
  $html .= content_tag('script', $js, array('type' => 'text/javascript'));
  $html .= '<div id="'.$name.'_rich_sel_date" style="display: inline;"></div>';
  return $html;
by Jacopo Romei on 2006-07-31, tagged date  forms  helper  rich  select 

Select a database dynamically

In app/lib/ create a file named myDBConnectionFilter.class.php and add:

class myDBConnectionFilter 
  public function initialize($filterChain) 
    $db = sfContext::getInstance()->getDatabaseManager()->getDatabase('myschema');
    $db->setConnectionParameter('username', 'myusername');
    $db->setConnectionParameter('password', 'mypassword');
    $db->setConnectionParameter('hostspec', 'localhost');
    $db->setConnectionParameter('database', 'mydatabase');
    // The below line is optional - Symfony will connect anyway if no connection is present

Then declare this filter to run on every page load by adding this to app/config/filters.yml:

  class: myDBConnectionFilter

Finally, Symfony will fail at the call above


because it does not know what type of database driver 'myschema' requires (MySQL/SQLite/etc.). You must add the following to app/config/databases.yml:

    class:          sfPropelDatabase
      phptype:            mysql

You can now dynamically select databases from the above class.

by Darren Schreiber on 2006-06-22, tagged connection  database  dynamic  multiple  propel  select 
(1 comment)