[英]How to add some extra data to a symfony 2 form
我有一個名為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);
如何在表單創建過程中提供一些初始數據? 或者我如何更改表單的創建以將初始數據添加到another_field
字段?
我還有一個表單,其中的字段大多與先前定義的實體匹配,但其中一個表單字段已將映射設置為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();
一個建議可能是在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
));
}
}
然后構造:
$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);
這樣,您的表單將在渲染時為您的字段填充正確的值。 如果您想提供許多字段,這可能是一個選項。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.