简体   繁体   中英

Symfony 2 add dynamic form; values from database

I would like to create a google categories matching(first field categorie from database and second field a user autocomplete field from google categories) form where i have an entity 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;

In my Controller i tried this

 /**
 * @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()
    ));
}

And my form type : 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'
        ));
    }
  }

I would like to have as many categories rows as row fields(website itecategorie and google categorie)

The result is like that:

在此处输入图片说明

Thank you in advance!

Your loop on $this->categories is uneffective, because the elements you add have the same name each time ( categorySite and categoryGoogle ), so the FormBuilder replaces the form field each time, instead of adding another one.

However, if you want your form to handle a Collection of CategoryConfigs, you need to take a different approach.

1) Create a CategoriesConfigType (as you did), but who is responsible of only a single CategoriesConfig entity

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'
        ));
    }
}

2) Then use CollectionType field to manipulate your form as a whole collection of CategoryConfigTypes:

class YourCollectionType extends AbstractType
{     
    public function buildForm(FormBuilderInterface $builder, array $options)
    {   
        $builder->add('categoriesConfigs', CollectionType::class, array(
            'entry_type'   => CategoriesConfigType::class,
            'entry_options'  => array('required'  => false)
        );
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM