Symfony2 dynamic forms mongodb

試著忘記壹切 提交于 2019-12-08 19:23:28

You are getting the non-object error because you are not actually creating the $article variable in your preBind or preSetData functions. It looks like you are mixing up $agent and $article

public function preSetData(FormEvent $event)
{
    //here you have $agent
    $agent = $event->getData();
    //here you have $article
    if (null === $article) {
        return;
    }

    $form = $event->getForm();
    //here you have $article
    $subCategories = $article->getCategory()->getSubCategories();

    $this->customizeForm($form, $subCategories);
}

Change to:

public function preSetData(FormEvent $event)
{
    $article = $event->getData();
    // We can only set subcategories if a category is set
    if (null === $article->getCategory()) {
        return;
    }

    $form = $event->getForm();
    //...

In customise form function you want to add the fields you need like subCategories:

//taken from the article OP referenced
protected function customizeForm($form, $subCatQueryBuilder)
{
    $formOptions = array(
        'class' => 'You\YourBundle\Entity\SubCategory',
        'multiple' => true,
        'expanded' => false,
        'property' => 'THE_FIELD_YOU_WANT_TO_SHOW',
         // I would create a query builder that selects the correct sub cats rather than pass through a collection of objects
        'query_builder' => $subCatQueryBuilder,
    );
    // create the field, this is similar the $builder->add()
    // field name, field type, data, options
    $form->add($this->factory->createNamed('subCategories', 'entity', null, $formOptions));
}

For the query builder:

/**
 * @param event FormEvent
 */
public function preSetData(FormEvent $event)
{
    $agent = $event->getData();

    if (null === $article->getCategory()) {
        return;
    }

    $form = $event->getForm();

   //Something like
   $category = $article->getCategory();
   $subCatQueryBuilder =  $this->dm
      ->getRepository("YourCatBundle:Subcategory")
      ->createQueryBuilder("sc")
      ->join("sc.category", "c")
      ->where("c.id = :category")
      ->setParameter("category", $category->getId());
   $this->customizeForm($form, $subCatQueryBuilder);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!