Symfony2 - 如何将当前用户和日期传递给表单?

时间:2014-03-27 17:49:56

标签: php forms symfony entity

我想构建一个表单来创建项目。 projectobject包含名称,客户等以及应该是当前用户的所有者。因此,在显示表单时,不应该有任何“所有者字段”,因为用户不应该编辑所有者,因为它是heselt并且不需要编辑。所以我只想将当前用户传递给表单,如下所示。与日期相同,因为它不是可编辑的,因为它是当前日期。

编辑:基本上我想做的是:创建一个新的项目对象,通过系统修改一些数据,比如将所有者设置为当前用户,将startdate设置为当前日期,之后我想修改对象通过表格(设置名称,客户,截止日期......取决于用户想要的东西)。然后验证projectobject并将其持久保存到数据库中。

$this->getUser();

所以这是我的方法。

项目:

<?php
// src/Beorganized/BeoBundle/Entity/Project.php
namespace Beorganized\BeoBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
/**
 * @ORM\Entity
 */
class Project{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     * 
     */
    protected $id;
    /**
     * @ORM\Column(type="string", length=255)
     * @Assert\NotBlank()
     */
    protected $name;
    /**
     * @ORM\Column(type="string", length=1024)
     */
    protected $icon;
    /**
     * @ORM\ManyToOne(targetEntity="User")
     * @ORM\JoinColumn(name="owner_id", referencedColumnName="id")
     * @Assert\NotBlank()
     **/
    protected $owner;
    /**
     * @ORM\ManyToMany(targetEntity="User", mappedBy="projects")
     */
    protected $users;
    /**
     * @ORM\Column(type="string", length=255)
     */
    protected $customer;
    /**
     * @ORM\ManyToOne(targetEntity="Category")
     * @ORM\JoinColumn(name="category_id", referencedColumnName="id")
     **/
    protected $category;
    /**
     * @ORM\Column(type="date")
     * @Assert\NotBlank()
     */
    protected $startdate;
    /**
     * @ORM\Column(type="date")
     */
    protected $enddate;
    /**
     * @ORM\Column(type="date")
     */
    protected $deadline;


    public function __construct() {
        $this->users = new \Doctrine\Common\Collections\ArrayCollection();
    }
    /**
     * Get id
     *
     * @return 
…

项目类型:

<?php

// src/Beorganized/BeoBundle/Form/Type/ProjectType.php
namespace Beorganized\BeoBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class ProjectType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('name', 'text');
        $builder->add('customer', 'text');
        $builder->add('deadline', 'date');
        $builder->add('users', 'text');
//        $builder->add('owner', 'hidden');
//        $builder->add('startdate', 'hidden');
        $builder -> add('save', 'submit');
        }
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Beorganized\BeoBundle\Entity\Project'
)); }
    public function getName()
    {
        return 'project';
    }
}

ProjectController:

public function newAction() {
        $em = $this -> getDoctrine() -> getManager();

        $project = new Project();

        $user = $this->getUser();
        $username = $user->getUsername();

        $project = new Project();
        $project->setOwner($user);
        $project->setStartdate(getdate());
        $form = $this -> createForm(new ProjectType(), $project, array('action' => $this -> generateUrl('_beo_create_project'), ));
        return $this -> render('BeorganizedBeoBundle:Project:newproject.html.twig', array('username' => $username, 'form' => $form -> createView()));

    }
public function createAction(Request $request) {



        $em = $this -> getDoctrine() -> getManager();
        $form = $this -> createForm(new ProjectType(), new Project());
        $form -> handleRequest($request);

        if ($form -> isValid()) {
            $project = $form -> getData();

            $em -> persist($project);
            $em -> flush();
            return $this -> redirect($this->generateUrl('_beo_project_created'));
        }
        return $this -> render('BeorganizedBeoBundle:Project:newproject.html.twig', array('username' => 'failed', 'form' => $form -> createView()));

    }

当我提交表格时,我得到两次“这个值不应该是空白的。”这是因为必须添加所有必须传递的数据吗?比如“$ builder-&gt; add('owner','hidden');”。我知道我可以删除Annotations * @Assert \ NotBlank()但是应该有另一种方式,对吗?

当我取消注释行添加('owner'...并添加('startdate ...)时出现以下错误:

The form's view data is expected to be of type scalar, array or an instance of \ArrayAccess, but is an instance of class Beorganized\BeoBundle\Entity\User. You can avoid this error by setting the "data_class" option to "Beorganized\BeoBundle\Entity\User" or by adding a view transformer that transforms an instance of class Beorganized\BeoBundle\Entity\User to scalar, array or an instance of \ArrayAccess.
500 Internal Server Error - LogicException

也许我的方法是完全错误的PorjectType,请不要怪我,这是我的第一个Symfonyproject。可能有人帮助我?

谢谢! : - )

3 个答案:

答案 0 :(得分:1)

如果您只是尝试设置这两个值,只需使用验证组(或删除验证,但我知道您不想这样做)并从表单中删除这两个字段。

并在您的控制器中使用它:

    if ($form -> isValid()) {
        $project = $form -> getData();

        $project->setStartDate(new \DateTime()); // set the startdate
        $user= $this->get('security.context')->getToken()->getUser(); // get the current user
        $project->setOwner($user); // set the current user

        $em -> persist($project);
        $em -> flush();
        return $this -> redirect($this->generateUrl('_beo_project_created'));
    }

这会解决您的问题吗?

答案 1 :(得分:0)

尝试在表单构建器中添加此类所有者: $ builder-&gt; add('owner','hidden');

$builder->add('owner', 'entity', array(
    'class' => 'AcmeHelloBundle:User',
    'property' => 'username',
    'attr'=> array('style'=>'display:none')
));

line'class'=&gt; 'AcmeHelloBundle:用户',可能是错误的。

来源:http://symfony.com/doc/current/reference/forms/types/entity.html

答案 2 :(得分:0)

使用验证组:

http://symfony.com/doc/current/book/validation.html#validation-groups

根据某些约束验证您的实体,但不是全部(您将它们分组,并使用该组进行验证)

修改

实体中的

/**
* @ORM\ManyToOne(targetEntity="User")
* @ORM\JoinColumn(name="owner_id", referencedColumnName="id")
* @Assert\NotBlank(groups={"group1"})
**/
protected $owner;

表格:

$resolver->setDefaults(array(
    'data_class' => 'Beorganized\BeoBundle\Entity\Project',
    //'validation_groups' => array('group1'), // will not be applied
));

在没有所有者字段的情况下提交时,这将最终成为有效表单(也不会更改)