php - Symfony2 - 如何设置 Controller createForm 函数使用的实体管理器?

标签 php mysql symfony

我有一个表单类型,它使用带有实体字段的查询生成器来获取相关选项。但是因为我正在为实体使用自定义实体管理器,所以它似乎无法识别这些选项。我得到了错误:

Entities passed to the choice field must be managed. Maybe persist them in the entity manager? 

Controller Action :

/**
 * @Route("/edit/{keyword_rank_id}/", name="lg.keywordrank.campaign.edit")
 * @Template
 */
public function editAction(Request $request, Company $company, $client_slug, $keyword_rank_id)
{
    $em = $this->getDoctrine()->getManager($company->getEntityManagerName());
    $client = $this->getEntityOrNotFound($em, 'LGClientBundle:Client', 'client_slug', $client_slug);
    $kr = $this->getEntityOrNotFound($em, 'LGKeywordRankBundle:KeywordRank', 'keyword_rank_id', $keyword_rank_id);
    $form = $this->createForm(new KeywordRankForm(), $kr, array('client'=>$client,'em'=>$em));
    ...
}

和表单类型:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('name','text',array(
        'label'=>'Campaign Name'
    ))
    ->add('client_domain', 'entity', array(
        'class' => 'LGClientBundle:ClientDomain',
        'choices'=> $this->getClientDomains($options['em'], $options['client']),
        'property' => 'domain',
        'label' => 'Domain: '
     ));
}

private function getClientDomains($em, $client)
{
    $domains = $em->getRepository('LGClientBundle:ClientDomain')->findBy(array('client'=>$client));
    return $domains;
}


public function setDefaultOptions(OptionsResolverInterface $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => 'LG\KeywordRankBundle\Entity\KeywordRank',
        'client' => null,
        'em' => null
    ));
}

public function getName()
{
    return 'lg_project_keywordrank';
}

谁有类似的问题或者知道如何解决这个问题就太好了

最佳答案

您可以在添加字段时指定要使用的实体管理器:

->add('client_domain', 'entity', array(
    'class' => 'LGClientBundle:ClientDomain',
    'choices'=> $this->getClientDomains($options['em'], $options['client']),
    'em' => $options['em'],
    'property' => 'domain',
    'label' => 'Domain: '
 ));

此选项采用实体管理器名称,而不是选项本身,因此您必须更改

$em = $this->getDoctrine()->getManager($company->getEntityManagerName());

进入

$em = $company->getEntityManagerName();

在这里查看文档:http://symfony.com/doc/current/reference/forms/types/entity.html#em

关于php - Symfony2 - 如何设置 Controller createForm 函数使用的实体管理器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20846936/

相关文章:

如果记录不存在(基于日期时间),Php mysql 获取最近的最新记录

mysql - QueryDSL:比较数组

php - MySQL 列出特定字段上的所有重复项,并且仅当另一个字段日期之间的日期 <= 1 时

MySQL 触发表中的更改

php - Doctrine 批量插入 - 实体管理器清除

php - 在 Symfony2 中使用 buildForm->add() 函数时,可接受的选项有哪些?

php - 需要更改 Wordpress 站点的页面位置

php - SELECT 语句给出 fatal error : Invalid parameter number in

php - 在哪里可以找到将 Twitter 集成到我的站点的代码?

symfony - 如何指定要进行逆向工程的数据库?