Php 如何向symfony 2表单添加一些额外数据

Php 如何向symfony 2表单添加一些额外数据,php,forms,symfony,entity,Php,Forms,Symfony,Entity,我的实体有一个名为Book的表单,我有一个在视图中显示表单的类型。在这种类型中,我有一些字段映射到实体中的属性 现在我想添加另一个未映射到实体中的字段,并在表单创建期间为该字段提供一些初始数据 我的类型看起来像这样 // BookBundle\Type\Book public function buildForm(FormBuilderInterface $builder, array $options = null) { $builder->add('title'); $

我的实体有一个名为
Book
的表单,我有一个在视图中显示表单的类型。在这种类型中,我有一些字段映射到实体中的属性

现在我想添加另一个未映射到实体中的字段,并在表单创建期间为该字段提供一些初始数据

我的类型看起来像这样

// BookBundle\Type\Book
public function buildForm(FormBuilderInterface $builder, array $options = null)
{
    $builder->add('title');
    $builder->add('another_field', null, array(
        'mapped' => false
    ));
}
$book = $repository->find(1);
$form = $this->createForm(new BookType(), $book);
表单是这样创建的

// BookBundle\Type\Book
public function buildForm(FormBuilderInterface $builder, array $options = null)
{
    $builder->add('title');
    $builder->add('another_field', null, array(
        'mapped' => false
    ));
}
$book = $repository->find(1);
$form = $this->createForm(new BookType(), $book);

在表单创建过程中,如何提供一些初始数据?或者我必须如何更改表单的创建以将初始数据添加到
另一个\u字段
字段?

一个建议可能是在您的BookType上添加一个包含“另一个\u字段”数据的构造函数参数(或setter),并在“添加参数”中设置“数据”参数:

class BookType 
{
    private $anotherFieldValue;

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

    public function buildForm(FormBuilderInterface $builder, array $options = null)
    {
        $builder->add('another_field', 'hidden', array(
            'property_path' => false,
            'data' => $this->anotherFieldValue

        )); 
    }
}
然后构建:

$this->createForm(new BookType('blahblah'), $book);

您可以像这样更改请求参数,以支持包含其他数据的表单:

$type = new BookType();

$data = $this->getRequest()->request->get($type->getName());
$data = array_merge($data, array(
    'additional_field' => 'value'
));

$this->getRequest()->request->set($type->getName(), $data);

这样,表单将在渲染时为字段填写正确的值。如果要提供多个字段,这可能是一个选项。

我还有一个表单,其中的字段大部分与以前定义的实体匹配,但其中一个表单字段已映射为false

要在控制器中解决此问题,您可以非常轻松地为其提供一些初始数据,如下所示:

$product = new Product(); // or load with Doctrine/Propel
$initialData = "John Doe, this field is not actually mapped to Product";
$form = $this->createForm(new ProductType(), $product);
$form->get('nonMappedField')->setData($initialData);
就这么简单。然后,当您处理表单数据准备保存时,您可以通过以下方式访问未映射的数据:

$form->get('nonMappedField')->getData();

您打算如何处理未映射到实体的字段?我想从表单或请求中获取提交的数据,并手动处理数据。谢谢您的回答。我找到了另一种优雅的方法。将在一分钟后发布答案。有用提示:当您要填充的未映射字段本身是子表单时,您必须链接
get()
调用:
$form->get('nonMappedSubForm')->get('subFormField')->setData(…)
。我们正在寻找如何从额外字段检索数据$表单->获取('nonMappedField')->getData();谢谢