使用symfony2在选项列表中获取所选值

时间:2015-05-09 21:22:44

标签: php symfony symfony-forms

我使用的是Symfony2 2.6版 我想知道如何在选择列表中获取所选值的值。这是我的行动:

Activity

问题在于:

public function indexAction(Request $request)
{
    // On récupère l'EntityManager
    $em = $this->getDoctrine()->getManager();
    // Pour récupérer une annonce unique : on utilise find()
     $rep= $em->getRepository('PFEUserBundle:Employee');
     $employees  = $rep->findAll();

    $form = $this->createFormBuilder($employees)
        ->add('employees', 'entity', array(
            'class' => 'PFEUserBundle:Employee',
            'property'=>'matricule',
            'expanded' => false,
            'multiple' => false,
        ))
        ->add('voir','submit')
        ->getForm();

    if ($form->handleRequest($request)->isValid()) {
        $mat=$request->request->get('employees');
        $employee=$rep->findByMatricule($mat);
        //=====> get the employee
        $session = $request->getSession();
        // stocke un attribut pour une réutilisation lors d'une future requête utilisateur
        $session->set('emp', $employee);


        return $this->redirect($this->generateUrl('pfe_employees_employee_view', array('id' => $employee->getId())));
    }

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

}

选择一个选项并提交后会给我这个错误:

$mat=$request->request->get('employees');
$employee=$rep->findByMatricule($mat);

2 个答案:

答案 0 :(得分:0)

我的猜测是<html> <body> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script> <script type="text/javascript" charset="utf-8" src="js/jquery.tubular.1.0.js"></script> <script type="text/javascript"> $(function() { var options = { videoId : '9JXVUP1hyxA', start : 10 }; $('html').tubular(options); }); </script> </body> </html> 包含ID,而findByMatricule方法只接受对象。所以你应该把它改成:

$request->get("employees")

或者更改find​​ByMatricule方法,使其适用于id,但最好添加一个名为findByMatriculeId的方法

答案 1 :(得分:0)

你在请求中得到的是一个对象的id,它是表单对象,它将数据转换为对象(简短地说)从数据库(如果表单中的字段是实体类型或它是一个实体的集合所以

onRestoreInstanceState

返回一个id,让我们说1,

$request->request->get('employees') 

将返回PFEUserBundle类的对象:Employee

相关问题