我想创建一个谷歌类别匹配(来自数据库的第一个字段类别,第二个字段来自谷歌类别的用户自动完成字段)表单,其中我有一个实体CategoriesConfig:
private $id;
/**
* @var string
*
* @ORM\Column(name="category_site", type="string", length=100)
*/
private $categorySite;
/**
* @var string
*
* @ORM\Column(name="category_google", type="string", length=100)
*/
private $categoryGoogle;
在我的控制器中,我尝试了这个
/**
* @Route("/adminDashboard/categoriesMatching", name="googleShopping_categories")
* @Security("has_role('ROLE_SUPER_ADMIN')")
*/
public function categoriesMatchingAction(Request $request)
{
// create a task and give it some dummy data for this example
$idSite = $this->get('session')->get('_defaultWebSite')->getId();
$categories = $this->getDoctrine()->getRepository('DataSiteBundle:SiteCategory')->findBy(array('IdSite' => $idSite));;
$categories_config = new CategoriesConfig();
//var_dump($categories);exit;
$form = $this->createForm(new CategoriesConfigType($categories), $categories_config);
return $this->render('GoogleShoppingBundle:Default:categoriesMatching.html.twig', array(
'form' => $form->createView()
));
}
我的表单类型:CategoriesConfigType:
class CategoriesConfigType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
private $site_categories;
public function __construct ($site_categories) {
$this->site_categories = $site_categories;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
foreach($this->site_categories as $k => $categorie){
$builder
->add('categorySite')
->add('categoryGoogle');
}
}
/**
* @param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Sp\GoogleShoppingBundle\Entity\CategoriesConfig'
));
}
}
我想将行字段(网站itecategorie和谷歌分类)设置为多个类别行
结果是这样的:
提前谢谢!
答案 0 :(得分:1)
for (j=i-1; j>=0;j--)
上的循环无效,因为您添加的元素每次都具有相同的名称($this->categories
和categorySite
),因此FormBuilder每次都会替换表单字段,而不是添加另一个。
但是,如果您希望表单处理CategoryConfigs的集合,则需要采用不同的方法。
1)创建categoryGoogle
(与您一样),但谁只负责单个CategoriesConfig实体
CategoriesConfigType
2)然后使用CollectionType field将表单作为CategoryConfigTypes的整个集合进行操作:
class CategoriesConfigType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('categorySite')
->add('categoryGoogle');
}
/**
* @param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Sp\GoogleShoppingBundle\Entity\CategoriesConfig'
));
}
}