我在 ZF2 中选择表单元素时遇到问题。我创建了查询原则 2 并具有良好的结果对象列表。
$langs = $this->getEntityManager()->getRepository('ApplicationEntityLangs')->findAll();
并创建简单的表单:
class Coupon extends Form
{
protected $objectManager;
public function __construct($name = null)
{
parent::__construct('coupon');
$this->setAttribute('method', 'post');
$this
->setAttribute('method', 'post')
->setHydrator(new ClassMethodsHydrator(false))
;
$this->add(array(
'name' => 'id',
'attributes' => array(
'type' => 'hidden',
),
));
}
$this->add(array(
'type' => 'ZendFormElementSelect',
'name' => 'language',
'attributes' => array(
'class' => 'form-control',
),
'options' => array(
'label' => 'default.form.message',
'empty_option' => '--- choose formElementName ---',
'value_options' => array(
'0' => 'French',
'1' => 'English',
'2' => 'Japanese',
'3' => 'Chinese',
),
)
));
}
如何将结果 ($langs) 转换为数组以进行value_options - zend 元素选择?我应该为此使用什么?
我解决了它。
我创造
public function getFormElementConfig()
{
return array(
'invokables' => array(
'Coupon' => 'ApplicationFormLangs',
),
'initializers' => array(
'ObjectManagerInitializer' => function ($element, $formElements) {
if ($element instanceof ObjectManagerAwareInterface) {
$services = $formElements->getServiceLocator();
$entityManager = $services->get('DoctrineORMEntityManager');
$element->setObjectManager($entityManager);
}
},
),
);
并在表单中添加初始化:
public function init()
{
parent::init();
$this->add(
array(
'type' => 'DoctrineModuleFormElementObjectSelect',
'name' => 'messages',
'options' => array(
'object_manager' => $this->getObjectManager(),
'target_class' => 'ApplicationEntityLangs',
'property' => 'title',
),
)
);
}
它适用于:)谢谢山姆。