简体   繁体   中英

ZF2 Doctrine: Use data from another entity in a form

in ZF2 I've got a form which edits the data of a table in the database. I'd like to add a field from another table to the form, how can I do it?

The table is called UserProfile , the entity Class goes like this:

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...

The UserProfileForm class goes like this:

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...

and in the editAction() of the controller I have:

$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,
 );

I guess the $form->bind($user) populates the form with the data from $user object, but how can I append other data, eg user's e-mail address, which is stored in another table called User (which has the corresponding structure and Entity class as well), in a column e-mail , with the same id as the userprofile.userid ? I tried to make a getter to another table from UserProfile entity class, but the Entity manager is only available in the controller and not in Entity classes! Or should I do it in the controller and somehow append the missing data to the $user object (but I guess I should make it in the model and not in the controller)? Or do I have to define a foreign key between the two tables, even if the user id is the same (but I'm not allowed to change the User table, it's used as a shared resource for the other ones as well)?

Thanks a lot for info

Jan

you can do that with Fieldsets - just make an own Fieldset for the second Entity (note the setObject() call) and be sure to set the name the same as it is defined in your entity class (parent::__construct()). Example: 'user' -> is your referencing/relating entity property (from where you need the 'external' data) - sorry I can't explain it better.

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....
    }
}

In your Form you can add it like a normal form-element:

class UserProfileForm extends Form
{
    public function __construct(ObjectManager $objectManager, $name = null)
    {
        // etc..

        $this->add(new UserDataFieldset($objectManager));
    }
}

that should be enough.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM