我有这种形式,我必须分别获取3个字段(名称和2个日期)的值,对日期进行格式化并将它们放入arrayCollection中。 我只想获取这3个字段,并让表单字段的其余部分像往常一样自动插入。 同时,当我回来编辑表单时,我想知道如何分配这些值以填充表单。
答案 0 :(得分:1)
根据本文档creating-form-classes,解决方案的尝试是执行以下操作:
我们假设您的实体名称为文章。
class ArticleType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('title', TextType::class)
->add('author', TextType::class)
->add('name', TextType::class, [
'mapped' => false
])
->add('date1', DatetimeType::class, [
'mapped' => false
])
->add('date2', DatetimeType::class, [
'mapped' => false
]);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Article::class,
]);
}
}
这里有选项'mapped'=> false ,因为您不想将其与实体Article映射。
/**
* @Route("/articles", methods={"POST", "GET"}, name="app_post_article")
*/
public function postArticle(Request $request, EntityManagerInterface $em)
{
$form = $this->createForm(ArticleType::class);
$form->handleRequest($request);
if ($request->isMethod('POST') && $form->isSubmitted() && $form->isValid()) {
$name = $form->get('name')->getData();
$date1 = $form->get('date1')->getData();
$date2 = $form->get('date2')->getData();
//.... do something
}
//... Do other thing
}
/**
* @Route("/articles/{id}", methods={"POST", "GET"}, name="app_edit_article")
*/
public function editArticle(Request $request, Article $article, EntityManagerInterface $em)
{
$form = $this->createForm(ArticleType::class, $article);
// $prevName, $prevDate1, $prevDate2 must be retreive first...
$form->get('name')->setData($prevName);
$form->get('date1')->setData($prevDate1);
$form->get('date2')->setData($prevDate2);
$form->handleRequest($request);
if ($request->isMethod('POST') && $form->isSubmitted() && $form->isValid()) {
$name = $form->get('name')->getData();
$date1 = $form->get('date1')->getData();
$date2 = $form->get('date2')->getData();
//.... do something
}
//... Do other thing
}
这只是个主意。