Ben*_*aap 9 php forms entity symfony
我为我的实体调用了一个表单,我Book有一个类型可以在我的视图中显示一个表单.在这种类型中,我有一些字段映射到我的实体中的属性.
现在我想添加另一个未映射到我的实体中的字段,并在表单创建期间为该字段提供一些初始数据.
我的类型看起来像这样
// BookBundle\Type\Book
public function buildForm(FormBuilderInterface $builder, array $options = null)
{
$builder->add('title');
$builder->add('another_field', null, array(
'mapped' => false
));
}
Run Code Online (Sandbox Code Playgroud)
表单就是这样创建的
$book = $repository->find(1);
$form = $this->createForm(new BookType(), $book);
Run Code Online (Sandbox Code Playgroud)
如何在表单创建过程中提供一些初始数据?或者我如何更改表单的创建以将初始数据添加到another_field字段?
tar*_*ion 29
我还有一个表单,其中的字段大多与先前定义的实体匹配,但其中一个表单字段已将映射设置为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);
Run Code Online (Sandbox Code Playgroud)
就那么简单.然后,当您处理表单数据以准备保存它时,您可以使用以下命令访问非映射数据:
$form->get('nonMappedField')->getData();
Run Code Online (Sandbox Code Playgroud)
一个建议可能是在BookType上添加一个包含"another_field"数据的构造函数参数(或setter),并在add参数中设置'data'参数:
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
));
}
}
Run Code Online (Sandbox Code Playgroud)
然后构造:
$this->createForm(new BookType('blahblah'), $book);
Run Code Online (Sandbox Code Playgroud)