2012-07-10 48 views
1

在我的symfony 1.4應用程序中,我將生成一個選擇下拉列表作爲表單的一部分。如何動態添加屬性到由sfWidgetFormPropelChoice生成的每個選項標記?

我後來想要應用一些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

並不比幾乎同樣的問題[你的另一個](http://stackoverflow.com/questions/11423854/how-can-i-add -html-選擇框中的選項)? – j0k 2012-07-11 07:30:52

+0

另一個是爲了更通用的情況,儘管我不小心將它標記爲symfony。 – 2012-07-11 15:37:50

+0

你不接受,因爲它不起作用? – j0k 2012-07-19 16:48:33

回答

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', 
), 
); 
相關問題