Symfony 1.4和在一个表单上编辑/创建多个模型


Symfony 1.4 and editing/creating multiple models on one form?

我有一个名为Users的模块,它允许我创建用户。然而,我也有一个模型称为配置文件。这是一个不同的表比用户,但每当我创建一个新的用户,我想添加一个新的配置文件。此外,我想在配置文件表中添加两个字段,在用户表单中可用。你们知道在Symfony中怎么做吗?

首先,你必须在forms文件夹中创建一个自定义表单。在此表单中添加创建用户所需的所有字段。然后你必须改变你的processForm方法(或者你可以像Flask建议的那样在显示表单的方法中这样做)

protected function processForm(sfWebRequest $request, sfForm $form){
$form->bind($request->getParameter('registration'));
if ($form->isValid())
{
  $user= new sfGuardUser();
  $user->setUsername($form->getValue('username'));
  $user->setPassword($form->getValue('password'));
  $user->setIsActive(true);
  $user->save();
  $profile= new sfGuardUserProfile();
  $profile->setUserId($user->getId());
  $profile->setName($form->getValue('nombre'));
  $profile->setSurname($form->getValue('apellidos'));
  $profile->setMail($form->getValue('username'));
  $profile->save();
  $this->redirect('@user_home');
}

}

看一下sfdoctrineapply,它们几乎完全是你想要的。

or in detail

#schema for the profile 
sfGuardUserProfile:
  tableName: sf_guard_user_profile
  columns:
    id:
      type: integer(4)
      primary: true
      autoincrement: true
    user_id:
      type: integer(4)
      notnull: true
    email:
      type: string(80)
    fullname:
      type: string(80)
    validate:
      type: string(17)
  # Don't forget this!
  relations:
    User:
      class: sfGuardUser
      foreign: id
      local: user_id
      type: one  
      onDelete: cascade    
      foreignType: one
      foreignAlias: Profile

和在您创建用户的表单中:

public function doSave($con = null)
  {
    $user = new sfGuardUser();
    $user->setUsername($this->getValue('username'));
    $user->setPassword($this->getValue('password'));
    // They must confirm their account first
    $user->setIsActive(false);
    $user->save();
    $this->userId = $user->getId();
    return parent::doSave($con);
  }

必须使用嵌入式表单。
查看这些文档:
http://symfony.com/blog/call-the-expert-customizing-sfdoctrineguardplugin
http://www.prettyscripts.com/framework/symfony/symfony-sfdoctrineguardplugin-and-customizing-user-profile