簡體   English   中英

如何在Zend框架2中向使用Zend / Form生成的標簽添加屬性

[英]How to add attributes to a label generated with Zend/Form in Zend framework 2

我正在使用Zend / Form向我的頁面添加表單。

我通過如下定義元素來添加元素:

    $this->add(array(
            'name' => 'value',
            'attributes' => array(
                    'type'  => 'text',
                    'id' => 'value',
                    'autocomplete' => 'off',
                    'placeholder' => 'Cost',
            ),
            'options' => array(
                    'label' => 'Cost',
            ),
    ));

如您所見,有一個'label'=>'cost'節點,它生成了一個與input元素一起使用的標簽。

如何為該標簽添加類,屬性?

請嘗試一下,我還沒有測試或使用過它,但是從源頭來看,它應該可以正常運行:

$this->add(array(
    'name'       => 'value',
    'attributes' => array(),
    'options'    => array(
        'label_attributes' => array(
            'class'  => 'mycss classes'
        ),
        // more options
    ),        
));

如果這不起作用,請給我評論。 如果它不起作用,則無法使用此方法,因為FormLabel相當有效地限制了validAttributes

protected $validTagAttributes = array(
    'for'  => true,
    'form' => true,
);

這在Zend Framework 2.3中效果很好:

$this->add(array(
  'name' => 'userName',
  'attributes' => array(
      'type'  => 'text',
      'class' => 'form-control',
      'placeholder' =>'Username',
  ),
  'options' => array(
      'label' => 'Username',
      'label_attributes' => array('class' => 'control-label')
  ),

));
$element->setOptions(array('label_class' => array('class' => 'control-label')));

產生如下代碼:

<label class="control-label">
  <input type="radio" name="option1" id="option1" value="1">
  Option 1
</label>
<label class="control-label">
  <input type="radio" name="option2" id="option2" value="2">
  Option 2
</label>

我已經試過了。 它可以在Zend Framework One中使用。

請注意,如果您使用

$ element-> setOptions(array('label_attributes'=> array('class'=>'control-label'))));;

由於某些原因,您會得到不希望的效果

<label attributes="control-label">
  <input type="radio" name="option1" id="option1" value="1">
  Option 1
</label>

對於ZF2 +上的編程方法,請嘗試以下操作:

$element->setOptions(array(
    'label_attributes' => array(
        'style' => 'color:gray;'
    )
));

受到達蒙答案的啟發。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM