【发布时间】:2016-04-02 07:21:48
【问题描述】:
所以我在用户表和用户债权人之间建立了一对多的关联。在编写报告时,用户需要选择要连接到他或她的哪个债权人。我遇到的问题是我只想返回使用 DoctrineSelect 登录的用户债权人,而不是数据库中的每个债权人。我不确定如何将 DoctrineSelect 限制为登录用户的 ID。
这是我目前所做的:
客户 -> 债权人
在我的字段集中,我有以下内容:
$this->add(
[
'type' => 'DoctrineModule\Form\Element\ObjectSelect',
'name' => 'creditor',
'options' => [
'object_manager' => $this->objectManager,
'target_class' => 'Debtor\Entity\Creditor',
'label_generator' => function($targetEntity) {
return $targetEntity->getTitle() . ' - ' . $targetEntity->getFirstName() . ' - ' . $targetEntity->getLastName();
},
'label' => 'Creditor',
'instructions' => 'Attach creditors to this report'
],
'attributes' => [
'multiple' => true,
'required' => 'required',
]
]
);
不幸的是,这会将所有债权人附加到表格中,与属于用户的债权人相对。
为了解决这个问题,我创建了以下类:
<?php
namespace Application\Form;
use Debtor\Service\CreditorService;
use Zend\Form\View\Helper\FormElement as BaseFormElement;
use Zend\Form\ElementInterface;
class FormElement extends BaseFormElement
{
public function __construct(
CreditorService $creditorService
)
{
$this->creditorService = $creditorService;
}
/**
* This function overrides the ZendFormElement method which allows us to set the format of our own elements if required
* @param ElementInterface $element
* @return string
*/
public function render( ElementInterface $element )
{
$attributes = $element->getAttributes();
if ( isset( $attributes['customElement']) )
{
$customElement = $attributes['customElement'];
switch( $customElement ) {
case 'getCreditors':
$creditors = $this->creditorService->findUserCreditors();
$element->setValueOptions( $creditors );
break;
}
}
return parent::render($element);
}
}
在我的字段集中,我现在有了这个:
$this->add(
[
'type' => 'select',
'name' => 'creditor',
'options' => [
'label' => 'Creditor',
'instructions' => 'Attach creditors to this report',
],
'attributes' => [
'multiple' => true,
'required' => 'required',
'class' => 'form-control input-medium select2me',
'customElement' => 'getCreditors', <-*****************
]
]
);
我的班级在哪里查找 customElement,如果找到,它会在我的债权人服务中使用以下代码返回客户债权人:
/**
* @return array
*/
public function findUserCreditors()
{
$creditors = $this->findByUserAuth();
$creditorArray = [];
foreach ($creditors AS $creditorObject)
{
$creditorArray[$creditorObject->getId()] = $creditorObject->getName();
}
return $creditorArray;
}
这可以解决一个小问题。当我编辑报告时,表单未在下拉列表中预先选择先前选择的债权人...
我的问题是:
有没有办法使用 DoctrineSelect 并使用我的 AuthenticationService,获取登录的用户 ID 并返回具体数据?
【问题讨论】:
-
为什么不create a custom select element。您只需要一个在表单元素管理器中注册的服务工厂。该工厂可以填充选项并获取经过身份验证的用户。除非 select 元素很简单,否则我个人觉得没有必要在自定义元素上使用 Doctrine
ObjectSelect。
标签: php doctrine-orm zend-framework2