在ZF2中,我有一个编辑数据库中表的数据的表单。我想添加一个字段从另一个表的形式,我怎么能做到这一点?
表名为UserProfile,实体类如下:
namespace UpvUser'Entity;
use Doctrine'ORM'Mapping as ORM;
use Zend'InputFilter'Factory as InputFactory;
use Zend'InputFilter'InputFilter;
use Zend'InputFilter'InputFilterAwareInterface;
use Zend'InputFilter'InputFilterInterface;
/**
* User Profile
*
* @ORM'Entity
* @ORM'Table(name="userprofile")
* @property int $userId
* @property string $title
* @property string $firstName
* @property string $lastName
and so on...
*/
class UserProfile
{
/**
* @ORM'Id
* @ORM'Column(type="integer");
* @ORM'GeneratedValue(strategy="AUTO")
*/
public $userId;
/**
* @ORM'Column(type="string")
*/
public $title;
/**
* @ORM'Column(type="string")
*/
public $firstName;
/**
* @ORM'Column(type="string")
*/
and so on including getters/setters and input filters...
UserProfileForm类是这样的:
namespace UpvUser'Form;
use Zend'Form'Form;
use Zend'I18n'Translator'Translator;
class UserProfileForm extends Form
{
public function __construct($name = null)
{
parent::__construct('userprofile'); // The name of the form
$this->setAttribute('method', 'post');
$this->add(array(
'name' => 'userId',
'attributes' => array(
'type' => 'hidden',
),
));
$this->add(array(
'name' => 'title',
'attributes' => array(
'type' => 'text',
),
));
$this->add(array(
'name' => 'firstName',
'attributes' => array(
'type' => 'text',
),
));
// and so on...
和在控制器的editAction()我有:
$user = $this->getEntityManager()->find('UpvUser'Entity'UserProfile', $userId);
$form = new UserProfileForm();
$form->bind($user);
$form->get('submit')->setAttribute('value', 'LANG_BTN_EDIT');
$request = $this->getRequest();
if ($request->isPost()) {
$form->setInputFilter($user->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
$this->getEntityManager()->flush();
return $this->redirect()->toRoute('upv-user', array('action' => 'overview')); // Redirect to list of albums
}
}
return array(
'userId' => $userId,
'form' => $form,
);
我猜$form->bind($user)用来自$user对象的数据填充表单,但是我如何添加其他数据,例如用户的电子邮件地址,存储在另一个名为user 的表中(它具有相应的结构和实体类),在列电子邮件中,与userprofile.userid相同的id作为userprofile.userid?我试图从UserProfile实体类中获取另一个表,但实体管理器仅在控制器中可用,而不在实体类中!或者我应该在控制器中这样做,并以某种方式将缺失的数据附加到$user对象(但我想我应该使其在模型中而不是在控制器中)?或者我有来定义两个表之间的外键,即使用户id是相同的(但是我不允许更改 user 表,它也被用作其他表的共享资源)?
Thanks for info
1月您可以使用Fieldsets -只需为第二个实体(注意setObject()调用)创建自己的Fieldset,并确保将名称设置为与实体类(parent::__construct())中定义的名称相同。示例:'user' ->是你的引用/相关实体属性(从你需要'外部'数据的地方)-对不起,我不能更好地解释它。
class UserDataFieldset extends Fieldset {
public function __construct(ObjectManager $objectManager){
parent::__construct('user');
$this->setHydrator(new DoctrineHydrator($objectManager))
->setObject(new UserData());
$this->add(array(
'name' => 'email',
'attributes' => array(
'type' => 'text',
),
));
// etc....
}
}
在你的表单中,你可以像添加一个普通的Form -element:
class UserProfileForm extends Form
{
public function __construct(ObjectManager $objectManager, $name = null)
{
// etc..
$this->add(new UserDataFieldset($objectManager));
}
}