在我的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>
有关如何实现这一目标的任何建议?也许使用备用或扩展小部件?
答案 0 :(得分: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',
),
);