symfony2列表复选框值

时间:2016-05-01 19:06:56

标签: symfony twig

当我尝试在控制器中检查复选框列表

时出现问题

我的控制员:

public function comparaisonAction() {
    $request = $this->get('request');
    $ids=$request->get('assur');
    foreach($_POST['assur'] as $valeur)
    {
        echo "Checkbox $valeur has been checked<br>";
    }

    foreach($ids as $value) {

        $entities=$value;
    }
    var_dump($entities);

    $em=$this->getDoctrine()->getManager();
    //$assur1=$em->getRepository("CMSiteBundle:Offresante")->findOneBy(array('idassurance'=>$idassur));
    //$queryimg1=$em->getRepository("CMSiteBundle:Assurance")->findOneBy(array('id'=>$idassur));
    //$assur2=$em->getRepository("CMSiteBundle:Offresante")->findOneBy(array('idassurance'=>$id2));
    //$queryimg2=$em->getRepository("CMSiteBundle:Assurance")->findOneBy(array('id'=>$id2));
    //$img1=$queryimg1->getImage();
    //$img2=$queryimg2->getImage();

    //return $this->render('CMSiteBundle:Sante:ComparaisonSante.html.twig',array('assurance1'=>$queryimg1,'img1'=>$img1,'id'=>$idassur));
    return $this->render('CMSiteBundle:Sante:ComparaisonSante.html.twig',array('id'=>$entities));
 }

我的观点:

{% for ass in assurance %}
     .....
    <div style="padding-left:40px;padding-bottom:20px" ><input type="checkbox" name="assur[]"   value={{ass.ident}}  /></div>
{% endfor %}

1 个答案:

答案 0 :(得分:0)

您需要将选中的复选框数组传递给视图,并测试当前复选框值是否在传递的数组中:

public function fooAction() {
    //...
    //...
    return $this->render('CMSiteBundle:Sante:ComparaisonSante.html.twig', [
        'chk_foo' => isset($_POST['chk_foo']) ? $_POST['chk_foo'] : [],
    ]);
}

<强> foo.twig

{% for foo in foos %}
   {% set checked = foo.id in chk_foo|default({}) ? ' checked' : '' %}
   <input type="checkbox" name="chk_foo" value="{{ foo.id }}"{{ checked }} />
{% endfor %}