处理具有多个实体关系的复杂 Symfony2 表单 [英] Handling a complex Symfony2 form with multiple entities relationship

查看:23
本文介绍了处理具有多个实体关系的复杂 Symfony2 表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表单(仍未完成并且缺少许多字段),它作为带有步骤的向导进行处理,其中处理来自多个实体的字段.这是表单本身:

I have a form (still not finished and is missing many fields) that is handled as a wizard with steps, in which fields from multiple entities are handled. This is the form itself:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
            ->add('tipo_tramite', 'entity', array(
                'class' => 'ComunBundle:TipoTramite',
                'property' => 'nombre',
                'required' => TRUE,
                'label' => "Tipo de Trámite",
                'query_builder' => function (EntityRepository $er) {
                    return $er->createQueryBuilder('q')
                            ->where('q.activo = :valorActivo')
                            ->setParameter('valorActivo', TRUE);
                }
            ))
            ->add('oficina_regional', 'entity', array(
                'class' => 'ComunBundle:OficinaRegional',
                'property' => 'nombre',
                'required' => TRUE,
                'label' => "Oficina Regional",
                'query_builder' => function (EntityRepository $er) {
                    return $er->createQueryBuilder('q')
                            ->where('q.activo = :valorActivo')
                            ->setParameter('valorActivo', TRUE);
                }
            ))
            ->add('procedencia_producto', 'entity', array(
                'class' => 'ComunBundle:ProcedenciaProducto',
                'property' => 'nombre',
                'required' => TRUE,
                'label' => "Procedencia del Producto"
            ))
            ->add('finalidad_producto', 'entity', array(
                'class' => 'ComunBundle:FinalidadProducto',
                'property' => 'nombre',
                'required' => TRUE,
                'label' => "Finalidad del Producto"
            ))
            ->add('condicion_producto', 'entity', array(
                'class' => 'ComunBundle:CondicionProducto',
                'property' => 'nombre',
                'required' => TRUE,
                'label' => "Condición del Producto"
            ))
            ->add('lote', 'integer', array(
                'required' => TRUE,
                'label' => "Tamaño del Lote"
            ))
            ->add('observaciones', 'text', array(
                'required' => FALSE,
                'label' => "Observaciones"
    ));

}

我有一个关于在这种情况下如何处理参数 data_class 的问题,所以我不必在控制器中做魔术.当我说魔术时,我的意思是:

I have a question regarding how to handle the parameter data_class in this case so I do not have to do magic in the controller. When I say magic I mean the following:

public function empresaAction()
{
    $entity = new Empresa();
    $form = $this->createForm(new EmpresaFormType(), $entity);
    return array( 'entity' => $entity, 'form' => $form->createView() );

}

public function guardarEmpresaAction(Request $request)
{
    $em = $this->getDoctrine()->getManager();

    /** @var $userManager \FOS\UserBundle\Model\UserManagerInterface */
    $userManager = $this->container->get('fos_user.user_manager');
    /** @var $dispatcher \Symfony\Component\EventDispatcher\EventDispatcherInterface */
    $dispatcher = $this->container->get('event_dispatcher');
    /** @var $mailer FOS\UserBundle\Mailer\MailerInterface */
    $mailer = $this->container->get('fos_user.mailer');

    $request_empresa = $request->get('empresa');
    $request_sucursal = $request->get('sucursal');
    $request_chkRif = $request->get('chkRif');

    $request_estado = $request_empresa[ 'estado' ];
    $request_municipio = $request->get('municipio');
    $request_ciudad = $request->get('ciudad');
    $request_parroquia = $request->get('parroquia');

    $user = $userManager->createUser();

    $event = new GetResponseUserEvent($user, $request);
    $dispatcher->dispatch(FOSUserEvents::REGISTRATION_INITIALIZE, $event);

    if (null !== $event->getResponse())
    {
        return $event->getResponse();
    }

    $entity = new Empresa();
    $form = $this->createForm(new EmpresaFormType(), $entity);
    $form->handleRequest($request);

    $success = $url = $errors = "";

    if ($form->isValid())
    {
        if ($request_sucursal != NULL || $request_sucursal != "")
        {
            $padreEntity = $em->getRepository('UsuarioBundle:Empresa')->findOneBy(array( "padre" => $request_sucursal ));

            if (!$padreEntity)
            {
                $padreEntity = $em->getRepository('UsuarioBundle:Empresa')->findOneBy(array( "id" => $request_sucursal ));
            }

            if ($request_chkRif != NULL || $request_chkRif != "")
            {
                $rifUsuario = $request_empresa[ 'tipo_identificacion' ] . $request_empresa[ 'rif' ];
            }
            else
            {
                $originalRif = $padreEntity->getRif();
                $sliceRif = substr($originalRif, 10, 1);
                $rifUsuario = $originalRif . ($sliceRif === false ? 1 : $sliceRif + 1);
            }

            $entity->setPadre($padreEntity);
        }
        else
        {
            $rifUsuario = $request_empresa[ 'tipo_identificacion' ] . $request_empresa[ 'rif' ];
        }

        $user->setUsername($rifUsuario);
        $user->setRepresentativeName($request_empresa[ 'razon_social' ]);
        $user->setEmail($request_empresa[ 'usuario' ][ 'email' ]);
        $user->setPlainPassword($request_empresa[ 'usuario' ][ 'plainPassword' ][ 'first' ]);

        $pais = $em->getRepository('ComunBundle:Pais')->findOneBy(array( "id" => 23 ));
        $user->setPais($pais);

        $estado_id = $request_estado ? $request_estado : 0;
        $estado = $em->getRepository('ComunBundle:Estado')->findOneBy(array( "id" => $estado_id ));
        $user->setEstado($estado);

        $municipio_id = $request_municipio ? $request_municipio : 0;
        $municipio = $em->getRepository('ComunBundle:Municipio')->findOneBy(array( "id" => $municipio_id ));
        $user->setMunicipio($municipio);

        $ciudad_id = $request_ciudad ? $request_ciudad : 0;
        $ciudad = $em->getRepository('ComunBundle:Ciudad')->findOneBy(array( "id" => $ciudad_id ));
        $user->setCiudad($ciudad);

        $parroquia_id = $request_parroquia ? $request_parroquia : 0;
        $parroquia = $em->getRepository('ComunBundle:Parroquia')->findOneBy(array( "id" => $parroquia_id ));
        $user->setParroquia($parroquia);

        ...
    }
    else
    {
        $errors = $this->getFormErrors($form);
        $success = FALSE;
    }

    return new JsonResponse(array( 'success' => $success, 'errors' => $errors, 'redirect_to' => $url ));

}

由于 'data_classonEmpresaFormType 设置为 UsuarioBundle\Entity\Empresa` 那么我需要处理任何额外的参数,如上例所示,使用 getter/setter复杂/大形式的大量工作.

Since the 'data_classonEmpresaFormTypeis set toUsuarioBundle\Entity\Empresa` then I need to handle any extra parameter as example above show with getter/setter and that's a lot of work for complex/big forms.

在示例表单中,字段 tipo_tramite 将保留在 ComunBundle\Entity\Producto 类中,但字段 oficina_regional 将保留在类 ComunBundle\Entity\Producto 中class ComunBundle\Entity\SolicitudUsuario 和其他甚至没有放置在这里但它们在表单中的人,在许多情况下,总共应该保持为 3 或 4 个实体,包括关系,你如何处理这个?

In the sample form, the fields tipo_tramite will persist in the class ComunBundle\Entity\Producto but the field oficina_regional will persist in the class ComunBundle\Entity\SolicitudUsuario and so with others who are not placed even here but they are in the form, in total should persist as 3 or 4 entities including relationships in many cases, how do you handle this?

我知道有 CraueFormFlowBundle 可能涵盖这个过程/流程,但不确定它是否是解决方案去.

I know there is CraueFormFlowBundle that maybe cover this process/flow but not sure if it is the solution to go.

有什么建议吗?

推荐答案

几天前刚刚使用了多步表单.我认为您需要嵌入式表单.无论如何,可以为您推荐另一个用于创建向导的好包:SyliusFlowBundle.IMO 比 CraueFormFlowBundle 更灵活、更容易理解.

Just worked with multi-step form few days ago. I think you need embedded forms here. Anyway can suggest you another nice bundle for creating wizard: SyliusFlowBundle. IMO it's more flexible and easier to understand than CraueFormFlowBundle.

顺便说一句,你为什么要以一种形式存储所有内容?我们为每个步骤使用了一种形式,我喜欢这种方法.

BTW why do you want to store all in one form? We've used one form for each step, and I liked this approach.

这篇关于处理具有多个实体关系的复杂 Symfony2 表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆