简体   繁体   English

将FormType用于Symfony2中的“新”和“编辑”数据

[英]Use FormType for “new” and “edit” data in Symfony2

I'm trying to use one form to add and edit data in my "Customer" Entity. 我正在尝试使用一种表单在“客户”实体中添加和编辑数据。

Here is the FormType: 这是FormType:

    <?php

namespace Ourentec\CustomersBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class CustomerType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name', 'text', array(
                'label' => 'Nombre *',
                'required' => true,
                'max_length' => 20,
            ))
            ->add('lastname', 'text', array(
                'label' => 'Apellido',
                'required' => false
            ))
            ->add('address', 'textarea', array(
                'label' => 'Dirección',
                'required' => false
            ))
            ->add('phone', 'text', array(
                'label' => 'Teléfono *',
                'required' => true
            ))
            ->add('pass', 'text', array(
                'label' => 'Contraseña *',
                'required' => true
            ))
            ->add('tasks', 'textarea', array(
                'label' => 'Tareas',
                'required' => false
            ))
            ->add('email', 'text', array(
                'label' => 'Email',
                'required' => false
            ))
            ->add('status', 'choice', array(
                'label' => 'Estado',
                'required' => true,
                'choices' => array(
                    '' => 'Selecciona un estado',
                    'Pendiente' => 'Pendiente',
                    'En Curso' => 'En Curso',
                    'Terminado' => 'Terminado'
                )
            ))
            ->add('location', 'choice', array(
                'label' => 'Ubicación',
                'required' => true,
                'choices' => array(
                    '' => 'Selecciona una ubicación',
                    'Taller' => 'Taller',
                    'Tienda' => 'Tienda',
                    'Servicio Técnico Oficial' => 'Servicio Técnico Oficial',
                    'Entregado' => 'Entregado'
                )
            ))
            ->add('save', 'submit', array(
                'label' => 'Añadir'
            ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'ourentec_customersbundle_customer';
    }
}

And here are the controllers for new and edit "customer": 这是新的和编辑“客户”的控制器:

public function newCustomerAction(Request $request)
    {
        $customer = new Customer();

        // invoke form and associate a customer object
        $form = $this->createForm(new CustomerType(), $customer);

        // check if form is submitted
        $form->handleRequest($request);

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

            $this->get('session')->getFlashBag()->add(
                'msg',
                'Ficha creada correctamente!'
            );
            return $this->redirect($this->generateUrl('customers_index'));

        }

        return $this->render('CustomersBundle:Customers:new.html.twig', array('form' => $form->createView()));
    }

    public function editCustomerAction(Request $request)
    {
        $customerModel = $this->get('customer_model');
        $historyModel = $this->get('history_model');

        $customer = $customerModel->getCustomerForAdmin($request->get('id'));

        $histories = $historyModel->getHistory($request->get('id'));

        $form = $this->createForm(new CustomerType(), $customer);


        return $this->render('CustomersBundle:Customers:edit.html.twig', array(
            'customer' => $customer,
            'histories' => $histories,
            'form' => $form->createView()));
    }

And to end, the edit view, because the "new" one works perfectly: 最后,编辑视图,因为“新”视图可以完美工作:

{% block content %}
    {% if customer is defined %}
        {% set customer = customer[0] %}
        <h2>Datos de {{ customer.name }}</h2>
        <a href="{{ path('customers_index') }}" class="btn">Volver</a>
        <p></p>

        {{ form_start(form) }}
        <table class="table">
            <tr>
                <td>ID</td>
                <td>{{ customer.id }}</td>
            </tr>

            <tr>
                <td>Fecha de Alta</td>
                <td>{{ customer.date|date("d-m-Y @ H:m:s") }}</td>
            </tr>

            <tr>
                <td>Nombre</td>
                <td>{{ form_widget(form.name) }}</td>
            </tr>

            <tr>
                <td>Estado Actual</td>
                <td>{{ customer.status }}</td>
            </tr>

            <tr>
                <td>Ubicación Actual</td>
                <td>{{ customer.location }}</td>
            </tr>

            <tr>
                <td>Apellido</td>
                <td>{{ form_widget(form.lastname) }}</td>
            </tr>

            <tr>
                <td>Dirección</td>
                <td>{{ form_widget(form.address) }}</td>
            </tr>

            <tr>
                <td>Teléfono</td>
                <td>{{ form_widget(form.phone) }}</td>
            </tr>

            <tr>
                <td>Contraseña</td>
                <td>{{ form_widget(form.pass) }}</td>
            </tr>

            <tr>
                <td>Tareas</td>
                <td>
                    {{ form_widget(form.tasks) }}
                    <input type="button" class="btn" id="btn_tasks" value="Archivar"/>
                </td>
            </tr>

            <tr>
                <td>Email</td>
                <td>{{ form_widget(form.email) }}</td>
            </tr>

            <tr>
                <td>Estado *</td>
                <td>
                    {{ form_widget(form.status) }}
                </td>
            </tr>

            <tr>
                <td>Ubicación *</td>
                <td>
                    {{ form_widget(form.location) }}
                </td>
            </tr>

            <tr>
                <td colspan="2">
                    <input type="submit" class="btn btn-success" name="edit" value="Guardar"/>
                    <a href="{{ path('customers_index') }}" class="btn">Volver</a>
                </td>
            </tr>
        </table>
        {{ form_end(form) }}

        {% if histories is defined %}
            {% set histories = histories[0] %}
            <h3>Historial de Tareas</h3>
            <table class="table">
                {% for history in histories %}
                    {% if history.tasks is defined %}
                        <tr>
                            <td class="history_text">{{ history.date|date("d-m-Y @ H:m:s") }}</td>
                            <td>{{ history.tasks }}</td>
                            <td>
                                <a href="" class="btn btn-danger"
                                   onclick="return confirm('¿Estás seguro de que deseas borrar esta entrada?')">Borrar</a>
                            </td>
                        </tr>
                    {% endif %}
                {% endfor %}
            </table>
        {% endif %}
    {% endif %}
{% endblock %}

Well, my problem is that I can't pre-fill the Entity data into text fields. 好吧,我的问题是我无法将实体数据预先填充到文本字段中。 As you can see, in my controller (editCustomerAction) I'm getting the customer info from my database (I checked it in my error_log and in the Symfony2 toolbar), and I pass that info to the view. 如您所见,在我的控制器(editCustomerAction)中,我从数据库中获取了客户信息(我在error_log和Symfony2工具栏中对其进行了检查),然后将该信息传递给视图。 But I don't know why it doesn't work. 但是我不知道为什么它不起作用。 I read de official docs but there are no examples to pre-fill data... 我阅读了官方文档,但没有示例可以预先填充数据...

Thanks in advance! 提前致谢!

EDITED: Here is the model. 编辑:这是模型。 I do a "getArrayResult()" in the DQL because if a do a 我在DQL中执行“ getArrayResult()”,因为如果执行

$customer = $this->getDoctrine()->getRepository('CustomersBundle:Customer')->find($request->get('id'));

I get a "PHP Fatal error: Allowed memory size..." error.. 我收到“ PHP致命错误:允许的内存大小...”错误。

Model functions: 模型功能:

class CustomerModel
{
    protected $em;

    public function __construct(\Doctrine\ORM\EntityManager $em)
    {
        $this->em = $em;
    }


    public function getAllCustomersForAdmin($userId)
    {
        $customers = $this->em->createQuery(
            'select c, ctrl.seen, ctrl.date as edited from CustomersBundle:Customer c
            join CustomersBundle:Control ctrl
            where c.id = ctrl.customer and ctrl.user = :id order by ctrl.date desc, c.date desc')
            ->setParameter('id', $userId)
            ->getArrayResult();

        return $customers;
    }

    public function getCustomerForAdmin($customerId)
    {
        $customer = $this->em->createQuery(
            'select c from CustomersBundle:Customer c where c.id = :id')->setParameter('id', $customerId)
            ->getArrayResult();

        return $customer;
    }
} 

You're are giving an array to your form. 您正在为表单提供数组。 That's why that didn't work. 这就是为什么不起作用。

In your model, you've to return a single result : 在模型中,您必须返回一个结果:

public function getCustomerForAdmin($customerId)
{
    $customer = $this->em->createQuery(
        'select c from CustomersBundle:Customer c where c.id = :id')->setParameter('id', $customerId)
        ->getSingleResult();

    return $customer;
}

You can use the function : getOneOrNullResult() to return a null if the customer doesn't exist. 如果客户不存在,则可以使用函数: getOneOrNullResult()返回null。 In this case, the getSingleResult() will throw an error. 在这种情况下, getSingleResult()将引发错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM