duanjuan1103 2015-11-19 16:44
浏览 46
已采纳

使用FormType在Symfony2中“新建”和“编辑”数据

I'm trying to use one form to add and edit data in my "Customer" Entity.

Here is the 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. 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

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

I get a "PHP Fatal error: Allowed memory size..." error..

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;
    }
} 
  • 写回答

1条回答 默认 最新

  • doujiang1001 2015-11-20 07:53
    关注

    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. In this case, the getSingleResult() will throw an error.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目