将FormType用于" new"和"编辑" Symfony2中的数据

时间:2015-11-19 16:44:01

标签: php forms symfony doctrine-orm frameworks

我尝试使用一个表单在我的"客户"中添加和编辑数据。实体。

这是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';
    }
}

这里有新的和编辑的控制器&#34;客户&#34;:

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()));
    }

结束编辑视图,因为&#34; new&#34;一个完美的工作:

{% 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 %}

好吧,我的问题是我无法将实体数据预填充到文本字段中。正如您所看到的,在我的控制器(editCustomerAction)中,我从我的数据库中获取客户信息(我在error_log和Symfony2工具栏中检查了它),然后将该信息传递给视图。 但我不知道为什么它不起作用。我阅读了官方文档,但没有预先填写数据的例子......

提前致谢!

编辑:这是模型。我做了一个&#34; getArrayResult()&#34;在DQL中,因为如果做了一个

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

我得到一个&#34; PHP致命错误:允许的内存大小......&#34;误差..

模型功能:

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;
    }
} 

1 个答案:

答案 0 :(得分:0)

您正在为表单添加数组。这就是为什么不起作用。

在你的模型中,你要返回一个结果:

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

    return $customer;
}

如果客户不存在,您可以使用函数getOneOrNullResult()返回null。在这种情况下,getSingleResult()会抛出错误。