Search code examples
symfony1doctrinesymfony-1.4dql

How to create a one-to-one related record in a separate table during processing (save()) of a form?


Here's the schema:

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

Here's what I'm trying to do in the frontend: I'm trying to allow the frontend user to create new user's... which I can do and all goes well.

Where I'm stuck: (1) during the save() process of creating the sf_guard_user, creating the new user's sf_guard_user_profile and setting the column value of 'user_id' to the primary key of the newly-created sf_guard_user (column 'id'). (2) Then also setting the column 'user_type' to 4.

I don't even know where to begin. If someone could point me in the right direction, I'd be would be greatly appreciated.

UPDATE:

This is my actions.class.php file (project/Source Files/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());
    }
}

Solution

  • Looks like you are not understanding right. When you configure correctly the sfGuardPlugin it takes care of the profile creation.

    Let's review the process step by step:

    1) First, configure correctly the sfGuardPlugin, add this to your app.yml

    all:
      sf_guard_plugin:
        profile_class:      yourProfileClass
        profile_field_name: user_id
    

    2) Save your user using the form:

    $form->save();
    

    3) Retrieve the newly created profile, and modify it:

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

    4) And you are done! I use this exact same method on one of my websites. So Me and my users are 100% sure this method works. Remember to set up correctly the sfGuardPlugin, it will create the profile even if you don't use it's admin generator;