如何在处理(save())表单期间在单独的表中创建一对一相关记录?

时间:2011-09-12 19:27:20

标签: symfony1 doctrine symfony-1.4 dql

这是架构:

sf_guard_user
  columns:
    id              { type: integer, primary: true, notnull: true, autoincrement: true, unique: true }
    username            { type: string }
    firstname           { type: string }
    lastname            { type: string }
    password            { type: string }
    salt, algorith, etc...

sf_guard_user_profile
  columns:
    id      { type: integer, primary: true, notnull: true, autoincrement: true, unique: true }
    user_id     { type: integer }
    user_type   { type: integer }
  relations:
    User: { class: sfGuardUser, local: user_id, foreign: id, type: one, foreignType: one, foreignAlias: Profile }
    Type: { local: type_id, foreign

这就是我在前端尝试做的事情:我正在尝试允许前端用户创建新用户......我可以做到这一切并且一切顺利。

我陷入困境:(1)在创建sf_guard_user的save()过程中,创建新用户的sf_guard_user_profile并将'user_id'的列值设置为新创建的sf_guard_user的主键(列' ID')。 (2)然后还将列'user_type'设置为4。

我甚至不知道从哪里开始。如果有人能指出我正确的方向,我将非常感激。

更新:

这是我的actions.class.php文件(项目/源文件/ apps / modules / users / actions):

protected function processForm(sfWebRequest $request, sfForm $form)
  {
    $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
    if ($form->isValid())
    {
      $sf_guard_user = $form->save();      
      $this->redirect('users/edit?id='.$sf_guard_user->getId());
    }
}

2 个答案:

答案 0 :(得分:0)

正确配置后,sfGuardPlugin会自动为您创建配置文件。在你的app.yml中添加这段代码:

all:
  sf_guard_plugin:
    profile_class:      sf_guard_user_profile
    profile_field_name: user_id

这将配置插件,以便在创建新用户时创建新的配置文件(创建新配置文件的操作由对象而不是视图执行。因此,这取决于您是否使用sfGuardPlugin拥有管理员,或者如果您正在使用自己的管理员。)

然后在sf_guard_user_profile类(sf_guard_user_profile.php)中,在save方法中,您可以这样做:

public function save(PropelCon $con = null)
{
  if ($this->isNew())
  {
    $this->setUserType(4);
  }
  parent::save();
}

这会将UserType设置为4,任何新的配置文件。

答案 1 :(得分:0)

看起来你理解不对。正确配置sfGuardPlugin后,它会负责配置文件的创建。

让我们一步一步地审查这个过程:

1)首先,正确配置sfGuardPlugin,将其添加到app.yml

all:
  sf_guard_plugin:
    profile_class:      yourProfileClass
    profile_field_name: user_id

2)使用以下表单保存您的用户:

$form->save();

3)检索新创建的配置文件,并对其进行修改:

$user = $form->getObject();
$profile = $user->getProfile();
$profile->setUserType(4);
$profile->save();

4)你完成了!我在我的一个网站上使用这种完全相同的方法。所以我和我的用户100%确定这种方法有效。请记住正确设置sfGuardPlugin,即使您不使用它的管理生成器,它也会创建配置文件;