在symfony下拉列表中显示名称和保存ID

时间:2014-01-15 11:58:56

标签: symfony

我想将我的部门的“名称”显示为我的用户的下拉列表,当他们选择一个时,将其“id”保存到数据库中。我怎样才能做到这一点?以下是我的代码。 Currentlt显示id和save id。

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('name')
        ->add('adress')
        ->add('city')
        ->add('area')
        ->add('departments', 'entity', array(
        'empty_value' => '',
            'class' => 'YdyaHospitalBundle:Department',
            'query_builder' => function($repository) { return $repository->createQueryBuilder('t')->orderBy('t.id', 'ASC'); },
            'property' => 'id',
            'multiple' =>false,
            'expanded' =>true,
))
        ;
    }

更新

我的控制器操作:

/**
 * Creates a new Hospitals entity.
 *
 * @Route("/", name="hospitals_create")
 * @Method("POST")
 * @Template("YdyaHospitalBundle:Hospitals:new.html.twig")
 */
public function createAction(Request $request)
{
    $entity  = new Hospitals();


    $form = $this->createForm(new HospitalsType(), $entity);
    $form->bind($request);

    if ($form->isValid()) {
        $em = $this->getDoctrine()->getManager();


        $em->persist($entity);
        $em->flush();

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

    return array(
        'entity' => $entity,
        'form'   => $form->createView(),
    );
}

/**
 * Displays a form to create a new Hospitals entity.
 *
 * @Route("/new", name="hospitals_new")
 * @Method("GET")
 * @Template()
 */
public function newAction()
{
    $entity = new Hospitals();

    $form   = $this->createForm(new HospitalsType(), $entity);

    return array(
        'entity' => $entity,
        'form'   => $form->createView(),
    );
}

1 个答案:

答案 0 :(得分:1)

您可以为您的实体实施__toString(),也可以指定要显示的属性:

->add('departments', 'entity', array(
    'empty_value' => '',
    'class' => 'YdyaHospitalBundle:Department',
    'query_builder' => function($repository) { return $repository->createQueryBuilder('t')->orderBy('t.id', 'ASC'); },
    // 'property' => 'id', --> Remove this
    'multiple' => false,
    'expanded' => true,
    'property' => 'name' // Property used to display the entity
))

在您的控制器中,您仍然可以将实体或实体的ID保存到数据库。

请参阅文档:http://symfony.com/doc/current/reference/forms/types/entity.html#property