如何在Symfony 2表单字段中设置默认值? [英] How to set a default value in a Symfony 2 form field?

查看:147
本文介绍了如何在Symfony 2表单字段中设置默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直试图用 Symfony 2 来设置一个表单。

因此,我遵循教程,我创建了一个特殊的类来创建表单并在控制器外部处理验证过程(如文档所示)。

但是现在我需要自动填充字段,我听说我必须在ProductType.php中创建表单(用于我的产品)。



但是我不知道该怎么做,下面是我在ProductType.php中的buildForm函数:

  class QuotesType extends AbstractType 
{
private $ id;

public function __construct($ id){
$ this-> product_id = $ id;

$ b $ public function buildForm(FormBuilder $ builder,array $ options)
{
$ builder
- > add('user_name','文本')
- > add('user_lastname','text')
- > add('user_email','email')
- > add('user_comments', 'textarea')
- > add('user_product_id','hidden',array(
'data'=> $ this-> product_id,
));
;

$ / code>

它显然不起作用,因为我得到一个SQL错误,说我的字段是null。



如何将一个默认值赋给user_product_id?我应该直接向对象做什么?



编辑:



这是我的代码的一部分实体:

 命名空间QN\MainBundle\Entity; 

使用Doctrine \ORM\Mapping作为ORM;
使用Symfony \ Component \Vididator\Constraints作为Assert;
$ b $ ** ** b $ b * QN\MainBundle\Entity\Quotes
*
* @ ORM\Table()
* @ORM \Entity(repositoryClass =QN\MainBundle\Entity\QuotesRepository)
* /
class Quotes
{

public function __construct($ p_id )
{
$ this-> date = new \Datetime('today');
$ b $ **
* @var integer $ id
*
* @ ORM\Column(name =id,type =integer)
* @ ORM \Id
* @ ORM\GeneratedValue(strategy =AUTO)
* /
private $ id;
$ b $ **
* @var整数$ user_product_id
*
* @ ORM\Column(name =user_product_id,type =integer)
* /
private $ user_product_id =1;
$ b $ ** b $ b * @var datetime $ date
*
* @ ORM\Column(name =date,type =datetime)
* /
私人$日期;

以及我的控制器:

  public function requestAction($ id)
{
$ repository = $ this-> getDoctrine()
- > getEntityManager()
- > ; getRepository( 'QNMainBundle:分类');
$ categories = $ repository-> findAll();

$ quote =新行情($ id);
$ form = $ this-> createForm(new QuotesType(),$ quote);

$ formHandler = new QuotesHandler($ form,$ this-> get('request'),$ this-> getDoctrine() - > getEntityManager());

if($ formHandler-> process())
{
return $ this-> redirect($ this-> generateUrl('QNMain_Product',array(' id'=> $ id)));

$ b return $ this-> render('QNMainBundle:Main:requestaform.html.twig',array(
'categories'=> $ categories,
'id'=> $ id,
'form'=> $ form-> createView(),
));


$ / code>

我的处理程序:

  namespace QN\MainBundle\Form; 

使用Symfony \ Component \Form\Form;
使用Symfony \Component\HttpFoundation\Request;
使用Doctrine \ORM \EntityManager;
使用QN\MainBundle\Entity\Quotes;

class QuotesHandler
{
protected $ form;
保护$请求;
保护$ em;

public function __construct(Form $ form,Request $ request,EntityManager $ em)
{
$ this-> form = $ form;
$ this-> request = $ request;
$ this-> em = $ em;

$ b $ public function process()
{
if($ this-> request-> getMethod()=='POST')
{
$ this-> form-> bindRequest($ this-> request);
$ b $ if if($ this-> form-> isValid())
{
$ this-> onSuccess($ this-> form-> getData( ));

返回true;
}
}

return false;
}

public function onSuccess(Quotes $ quote)
{
$ this-> em-> persist($ quote);
$ this-> em-> flush();
}

}

我也把这里 Date 我尝试在实体中设置,在这两种情况下我都可能会做错事,因为我无法让它工作.Date不在 buildForm 函数,我不知道是否应该..

解决方案

在这里要做的就是创建一个安全漏洞:任何人都可以在 user_product_id 字段中注入任何标识,并欺骗你的应用程序。不要提到渲染一个字段并且不显示它是没有用的。



您可以将默认值设置为 user_product_id 在您的实体中:

  / ** 
* @ ORM \Annotations ...
* /
private $ user_product_id = 9000;


I've been trying to set up a form with Symfony 2.

So I followed the tutorial and I've created a special class for creating the form and handling the validation process outside the controller (as shown in the documentation)

But now I need to fill in a field automatically, I've heard that I have to do it in the ProductType.php, where the form (for my product) is created.

But I don't know how to do, here is my buildForm function in ProductType.php :

class QuotesType extends AbstractType
{
    private $id;

    public function __construct($id){
        $this->product_id = $id;
    }

    public function buildForm(FormBuilder $builder, array $options)
    {
        $builder
            ->add('user_name',              'text')
            ->add('user_lastname',          'text')
            ->add('user_email',             'email')
            ->add('user_comments',          'textarea')
            ->add('user_product_id',        'hidden', array(
                'data' => $this->product_id,
            ));
        ;
    }

and it obviously doesnt work since I got a SQL error saying that my field is null.

How can I put a default value to the user_product_id ? should I do it directly to the object ?

EDIT:

Here is a part of the code of my entity :

namespace QN\MainBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * QN\MainBundle\Entity\Quotes
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="QN\MainBundle\Entity\QuotesRepository")
 */
class Quotes
{

    public function __construct($p_id)
    {
        $this->date = new \Datetime('today');
    }
    /**
     * @var integer $id
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var integer $user_product_id
     *
     * @ORM\Column(name="user_product_id", type="integer")
     */
    private $user_product_id = "1";

    /**
     * @var datetime $date
     *
     * @ORM\Column(name="date", type="datetime")
     */
    private $date;

And my controller :

public function requestAction($id)
    {
        $repository = $this->getDoctrine()
                           ->getEntityManager()
                           ->getRepository('QNMainBundle:Categories');
    $categories = $repository->findAll();

    $quote = new Quotes($id);
    $form = $this->createForm(new QuotesType(), $quote);

    $formHandler = new QuotesHandler($form, $this->get('request'), $this->getDoctrine()->getEntityManager());

    if( $formHandler->process() )
    {
        return $this->redirect( $this->generateUrl('QNMain_Product', array('id' => $id)) );
    }

    return $this->render('QNMainBundle:Main:requestaform.html.twig', array(
        'categories' => $categories,
        'id' => $id,
        'form' => $form->createView(),
    ));

}

My Handler :

namespace QN\MainBundle\Form;

use Symfony\Component\Form\Form;
use Symfony\Component\HttpFoundation\Request;
use Doctrine\ORM\EntityManager;
use QN\MainBundle\Entity\Quotes;

class QuotesHandler
{
    protected $form;
    protected $request;
    protected $em;

    public function __construct(Form $form, Request $request, EntityManager $em)
    {
        $this->form    = $form;
        $this->request = $request;
        $this->em      = $em;
    }

    public function process()
    {
        if( $this->request->getMethod() == 'POST' )
        {
            $this->form->bindRequest($this->request);

            if( $this->form->isValid() )
            {
                $this->onSuccess($this->form->getData());

                return true;
            }
        }

        return false;
    }

    public function onSuccess(Quotes $quote)
    {
        $this->em->persist($quote);
        $this->em->flush();
    }

}

I've also put here the Date I try to set up in the entity, I might do something wrong in both case since I can't make it work neither ..Date is not in the buildForm function, I don't know if I should ..

解决方案

What you're trying to do here is creating a security hole: anyone would be able to inject any ID in the user_product_id field and dupe you application. Not mentioning that it's useless to render a field and to not show it.

You can set a default value to user_product_id in your entity:

/**
 * @ORM\Annotations...
 */
private $user_product_id = 9000;

这篇关于如何在Symfony 2表单字段中设置默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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