2016-09-21 77 views
2

我已經修改radio_widget和想給的<label><input>相同ID,這應該是獨特的一對。Symfony/Twig:窗體小部件的內部ID?

目前我使用random(),但我更喜歡內部計數器,如{{loop.index}}Twig: for),以避免衝突。

{% block radio_widget -%} 
    {% set id = random() %} 
    <div class="radio"> 
     <label for="radio_{{ id }}">Label for {{ id }}</label> 
     <input type="radio" id="radio_{{ id }}" {# ...#}/> 
    </div> 
{%- endblock radio_widget %} 

有沒有人知道更好的解決方案?

在此先感謝!

+1

你在談論用於表單渲染的主要無線電部件?如果是這樣,你已經在'form.vars.id'中有一個依賴於窗口小部件的unqiue ID。 – Yoshi

+0

@Yoshi正是我所需要的。發佈它作爲答案,我會接受它。謝謝! –

回答

1

對於每一個表單控件已經有一個預先計算的唯一ID。

參見:\Symfony\Component\Form\Extension\Core\Type\BaseType::buildView

在樹枝這個ID是通過{{ form.vars.id }}訪問。

實質上,id只是嵌套的表單類型名稱的串聯。


注意form.vars一般包含所有有用的東西你需要做的表單定製。當使用FormTypeInterface::buildViewFormTypeInterface::finishView將數據傳輸到表單呈現時,它也是放置自定義值的地方。

1

ProjectTwigExtension.php

class ProjectTwigExtension extends Twig_Extension { 

    public function getFunctions() { 
     return array(
      new Twig_SimpleFunction('get_unique_key', array($this, 'getUniqueKey')),    
     ); 
    } 

    private $keys = array(); 
    /** 
    * Create an unique HTML identifier for a form element 
    * 
    * @param $name String to make unique 
    * 
    * @returns String 
    */ 
    public function getUniqueKey($name) { 
     if (!in_array($name, $this->keys)) { 
      $this->keys[] = $name; 
      return $name; 
     } 
     $i = 0; 
     while(in_array($name.++$i,$this->keys)) {} 
     $this->keys[] = $name.$i; 
     return $name.$i; 
    } 


    public function getName() { 
     return 'ProjectTwigExtension'; 
    }   
} 

的config.php

$twig = new Twig_Environment($loader); 
$twig->addExtension(new ProjectTwigExtension()); 

template.twig

{% block radio_widget -%} 
    {% set id = get_unique_key('radio_') %} 
    <div class="radio"> 
     <label for="{{ id }}">Label for {{ id }}</label> 
     <input type="radio" id="{{ id }}" {# ...#}/> 
    </div> 
{%- endblock radio_widget %} 
+0

一般的好解決方案,但這次我只需要'form.vars.id'。感謝您的回覆! –

1

可能你可以嘗試這樣的事:

{% block radio_widget -%} 
    {% if counter is defined %} {# set desired id #} 
    {% set id = counter %} 
    {% else %} 
    {% set id = random() %} {# default value #} 
    {% endif %} 
    <div class="radio"> 
     <label for="radio_{{ id }}">Label for {{ id }}</label> 
     <input type="radio" id="radio_{{ id }}" {# ...#}/> 
    </div> 
{%- endblock radio_widget %} 

使用示例:

{% for i in 0..10 %} 
    {% set counter = loop.index %} 
    {{- block('radio_widget') }} 
{% endfor %}