【问题标题】:Zend2 Form - set attributes to options in select elementZend2 Form - 将属性设置为选择元素中的选项
【发布时间】:2014-04-09 08:43:47
【问题描述】:

我想知道如何在 Zend 2 中为 select 的选项添加一些属性。我的表单元素如下所示:

$this->add(array(
        'type' => 'Zend\Form\Element\Select',
        'name' => 'brand_name',
        'options' => array(
            'label' => 'Choose brand',
            'value_options' => $this->getBrands(),
        ),
    ));

所以它的填充选择看起来类似于:

<select name="brand_name"><option value="1">aaaa</option></select>

但我想实现这样的目标:

<select name="brand_name"><option value="1" class="test">aaaa</option></select>

并且类应该是不同的,取决于特定的选项。是否可以?我为什么要尝试这个?我需要添加 jquery 插件 - 链接需要选项类。

【问题讨论】:

    标签: php forms zend-framework2


    【解决方案1】:

    我找到了一个解决方案,父选择 value_options 的数组应该是这样的:

    foreach ($data as $item) {
            $models[] = array(
              'label' => $item->model_name, 
              'attributes' => array('class' => $item->id_brand_list), 
              'value' => $item->id);
        }
    

    【讨论】:

      【解决方案2】:

      如果您的数据是您希望从sql 或db 获取的array,您可以编写如下代码:

      public function getOptionsForDataSelect()
      {
          $dbAdapter = $this->_adapter;
          $sql = "SELECT * FROM db_name ORDER BY db_name ASC";
          $statement = $dbAdapter->query($sql);
          $result = $statement->execute();
      
          $selectData = array();
          foreach ($result as $res) {
              $selectData[] = array(
                  'label' => $res['label_data'],
                  'attributes' => array(
                      'data-key' => $res['data_id']
                  ),
                  'value' => $res['value_id']
              );
              // $selectData[$res['id']] = $res['name'];
          }
          return $selectData;
      }
      

      【讨论】:

        猜你喜欢
        • 2017-05-30
        • 1970-01-01
        • 2015-09-12
        • 2011-08-06
        • 1970-01-01
        • 2013-11-26
        • 1970-01-01
        • 2011-11-04
        相关资源
        最近更新 更多