2013-03-20 72 views
2

我有一個Image類是這樣的:在我的控制器樹枝和布爾

class Image { 
private $color; 
private $name; 
private $gradient; 
private $colorGradient; 

function __construct() { 
    $this->color = "FFFFFF"; 
    $this->name = "blanc"; 
    $this->gradient = false; 
    $this->colorGradient = ""; 
} 

我有這樣的:

public function indexAction() { 
    $image = new Image(); 

    $form = $this->createFormBuilder($image) 
      ->add('color', 'text') 
      ->add('name', 'text') 
      ->add('gradient', 'checkbox') 
      ->add('colorGradient', 'text') 
      ->getForm(); 

    return $this->render('CramifImageBuilderBundle:Builder:index.html.twig', array('form' => $form->createView())); 
} 

在index.html.twig我有這樣的:

<form action="{{ path('cramif_image_builder_image_new') }}" method="post" {{ form_enctype(form) }}> 
     {{ form_errors(form) }} 

     {{form_row(form.color)}} 
     {{form_row(form.name)}} 

     <div id="gradient"> 
      {{form_row(form.gradient)}} 
     </div> 

     {% if form.gradient == true %} 
      <div id="gradient_color"> 
       {{form_row(form.colorGradient)}} 
      </div> 
     {% endif %} 

     <input id="submit" type='submit' value='Créer' /> 
    </form> 

如果gradient = true,則複選框被選中(好),值='1'

<input id="form_gradient" type="checkbox" checked="checked" value="1" required="required" name="form[gradient]"> 

如果梯度=假的複選框未被選中(好)與值=「1」

<input id="form_gradient" type="checkbox" value="1" required="required" name="form[gradient]"> 

問題是任何梯度的值,它像梯度爲真:所以colorgradient字段是始終顯示

謝謝

+0

什如果在比較中省略「true」,則會發生這種情況,將它寫爲「{%if form.gradient%}」? – raina77ow 2013-03-20 16:19:11

回答

5

我沒有測試過這還,但嘗試

{% if form.gradient.vars.checked %} 
    <div id="gradient_color"> 
     {{ form_row(form.colorGradient) }} 
    </div> 
{% endif %} 
+0

是的,它的工作原理...但你可以告訴什麼時候使用==真? – mlwacosmos 2013-03-20 16:35:58

+0

@mlwacosmos form.gradient應始終評估爲true,因爲它存在。我越看越這個目標越是混淆目標。該模板僅適用於新圖像嗎?還是打算處理現有的圖像? – Lighthart 2013-03-20 16:37:15

+0

在這種情況下,'form.gradient.vars.checked'的值可以設置爲'checked'而不是'true',否則可能根本沒有設置 – 2013-03-20 16:38:20