1

在我的 symfony 1.4 应用程序中,我生成了一个下拉选择作为表单的一部分。

我稍后想对该选择应用一些 jQuery (ddSlick) 以重新设置它的样式。为此,我需要为每个选项标签添加一个属性。

例如,我希望我的选择生成:

<select id="demo-htmlselect">
        <option value="0" data-imagesrc="http://dl.dropbox.com/u/40036711/Images/facebook-icon-32.png"
            data-description="Description with Facebook">Facebook</option>
        <option value="1" data-imagesrc="http://dl.dropbox.com/u/40036711/Images/twitter-icon-32.png"
            data-description="Description with Twitter">Twitter</option>
        <option value="2" selected="selected" data-imagesrc="http://dl.dropbox.com/u/40036711/Images/linkedin-icon-32.png"
            data-description="Description with LinkedIn">LinkedIn</option>
        <option value="3" data-imagesrc="http://dl.dropbox.com/u/40036711/Images/foursquare-icon-32.png"
            data-description="Description with Foursquare">Foursquare</option>

关于如何实现这一目标的任何建议?也许使用备用或扩展小部件?

4

1 回答 1

2

如果要自定义选择渲染,则应扩展默认小部件并制作自己的渲染。

因此,例如创建此文件:/lib/widget/myWidgetFormSelect.class.php使用:

class myWidgetFormSelect extends sfWidgetFormSelect
{
  protected function getOptionsForSelect($value, $choices)
  {
    $mainAttributes = $this->attributes;
    $this->attributes = array();

    if (!is_array($value))
    {
      $value = array($value);
    }

    $value_set = array();
    foreach ($value as $v)
    {
      $value_set[strval($v)] = true;
    }

    $options = array();
    foreach ($choices as $key => $option)
    {
      $attributes = array(
        'value'            => self::escapeOnce($key),
        'data-imagesrc'    => self::escapeOnce($option['imagesrc']),
        'data-description' => self::escapeOnce($option['description'])
      );
      if (isset($value_set[strval($key)]))
      {
        $attributes['selected'] = 'selected';
      }

      $options[] = $this->renderContentTag('option', self::escapeOnce($option['title']), $attributes);
    }

    $this->attributes = $mainAttributes;

    return $options;
  }
}

然后,你应该欺骗你给$choices小部件的方式。在这里,小部件等待这样的数组:

$choices = array(
  0 => array(
    'title'       => 'Facebook',
    'imagesrc'    => 'http://dl.dropbox.com/u/40036711/Images/facebook-icon-32.png',
    'description' => 'Description with Facebook',
  ),
  1 => array(
    'title'       => 'Twitter',
    'imagesrc'    => 'http://dl.dropbox.com/u/40036711/Images/twitter-icon-32.png',
    'description' => 'Description with Twitter',
  ),
);
于 2012-07-11T19:22:50.197 回答