How to use select box related on another select box?

后端 未结 3 726
清酒与你
清酒与你 2021-01-30 23:16

How to use related select boxes in Symfony ?

Let\'s say, I have a select list containing compagnies and another containing employees of the selected company. How do I d

3条回答
  •  深忆病人
    2021-01-30 23:39

    You can create action, that will be return json array with employees of company. When the list of companies changed you must request this action by ajax and create select list of employees.

    Form controller action:

    /**
     * @Route("/job", name="_demo_job")
     * @Template()
     */
    public function jobAction()
    {
        $form = $this->createForm(new JobType());
    
        $request = $this->getRequest();
        if ($request->getMethod() == 'POST') {
            $form->bindRequest($request);
            $data = $form->getData();
            // some operations with form data
        }
    
        return array(
            'form' => $form->createView(),
        );
    }
    

    Conroller, that return employees by company in json:

    /**
     * Finds all employees by company
     *
     * @Route("/{id}/show", name="employees_by_category")
     */
    public function listByCompanyAction($id)
    {
        $request = $this->getRequest();
    
        if ($request->isXmlHttpRequest() && $request->getMethod() == 'POST') {
            $em = $this->getDoctrine()->getEntityManager();
    
            $company = $em->getRepository('AcmeDemoBundle:Company')->find($id);
    
            // create array for json response
            $empoloyees = array();
            foreach ($company->getEmployees() as $employee) {
                $empoloyees[] = array($employee->getId(), $employee->getName());
            }
    
            $response = new Response(json_encode($empoloyees));
            $response->headers->set('Content-Type', 'application/json');
    
            return $response;
        }
        return new Response();
    }
    

    Form template:

    
    
    {{ form_widget(form) }}

    For more detail example you should describe your problem in more detail.

提交回复
热议问题