Създайте нови потребители със същата група(и) като влезлия потребител

Опитвам се да добавя нови потребители към таблицата на sfDoctrineGuard, като използвам собствената си регистрационна форма. Това е функцията за конфигуриране, която направих:

public function configure() {
    // Remove all widgets we don't want to show
    unset(
            $this['is_super_admin'], $this['updated_at'], $this['groups_list'], $this['permissions_list'], $this['last_login'], $this['created_at'], $this['salt'], $this['algorithm']
    );

    $id_empresa = sfContext::getInstance()->getUser()->getGuardUser()->getSfGuardUserProfile()->getIdempresa();
    $this->setDefault('idempresa', $id_empresa);

    $this->validatorSchema['idempresa'] = new sfValidatorPass();

    $this->widgetSchema['first_name'] = new sfWidgetFormInputText(array(), array('class' => 'input-block-level'));
    $this->widgetSchema['last_name'] = new sfWidgetFormInputText(array(), array('class' => 'input-block-level'));
    $this->widgetSchema['username'] = new sfWidgetFormInputText(array(), array('class' => 'input-block-level'));
    $this->widgetSchema['email_address'] = new sfWidgetFormInputText(array(), array('class' => 'input-block-level'));
    $this->widgetSchema['password'] = new sfWidgetFormInputPassword(array(), array('class' => 'input-block-level'));
    $this->widgetSchema['password_confirmation'] = new sfWidgetFormInputPassword(array(), array('class' => 'input-block-level'));

    // Setup proper password validation with confirmation
    $this->validatorSchema['password']->setOption('required', true);
    $this->validatorSchema['password_confirmation'] = clone $this->validatorSchema['password'];

    $this->widgetSchema->moveField('password_confirmation', 'after', 'password');

    $this->mergePostValidator(new sfValidatorSchemaCompare('password', sfValidatorSchemaCompare::EQUAL, 'password_confirmation', array(), array('invalid' => 'The two passwords must be the same.')));
}

Сега трябва да създам тези нови потребители със същата група(и), в която потребителят е влязъл, но не знам как. Прочетох тази публикация, но не знам дали използването на getGroups() ще свърши работа работата имам предвид настройка groups_list по подразбиране, някакъв съвет? Кой е най-добрият начин да направите това?


person Reynier    schedule 12.06.2013    source източник


Отговори (1)


има няколко начина, по които можете да направите това... Бих препоръчал да добавите групите, след като валидирането за другите полета е извършено и потребителският обект бъде запазен; така че можете да замените функцията save() на формуляра и да ги добавите там:

<?php

class YourUserForm extends PluginsfGuardUserForm
{
  /**
   * A class variable to store the current user
   * @var sfGuardUser
   */
  protected $current_user;

  public function configure()
  {
    // Remove all widgets we don't want to show
    unset(
      $this['is_super_admin'],
      $this['updated_at'],
      $this['groups_list'],
      $this['permissions_list'],
      $this['last_login'],
      $this['created_at'],
      $this['salt'],
      $this['algorithm']
    );

    // save the currrent user for use later in the save function
    $this->current_user = sfContext::getInstance()->getUser()->getGuardUser();

    $id_empresa = $this->current_user->getSfGuardUserProfile()->getIdempresa();;
    $this->setDefault('idempresa', $id_empresa);

    $this->validatorSchema['idempresa'] = new sfValidatorPass();

    $this->widgetSchema['first_name'] = new sfWidgetFormInputText(array(), array('class' => 'input-block-level'));
    $this->widgetSchema['last_name'] = new sfWidgetFormInputText(array(), array('class' => 'input-block-level'));
    $this->widgetSchema['username'] = new sfWidgetFormInputText(array(), array('class' => 'input-block-level'));
    $this->widgetSchema['email_address'] = new sfWidgetFormInputText(array(), array('class' => 'input-block-level'));
    $this->widgetSchema['password'] = new sfWidgetFormInputPassword(array(), array('class' => 'input-block-level'));
    $this->widgetSchema['password_confirmation'] = new sfWidgetFormInputPassword(array(), array('class' => 'input-block-level'));

    // Setup proper password validation with confirmation
    $this->validatorSchema['password']->setOption('required', true);
    $this->validatorSchema['password_confirmation'] = clone $this->validatorSchema['password'];

    $this->widgetSchema->moveField('password_confirmation', 'after', 'password');

    $this->mergePostValidator(new sfValidatorSchemaCompare('password', sfValidatorSchemaCompare::EQUAL, 'password_confirmation', array(), array('invalid' => 'The two passwords must be the same.')));
  }

  public function save($con = null)
  {
    // call the parent function to perform the save and get the new user object
    $new_user = parent::save($con); /* @var $user sfGuardUser */

    // add our groups here by looping the current user's group collection
    foreach($this->current_user->getGroups() as $group) /* @var $group sfGuardGroup */
    {
      // we could use $user->addGroupByName($group->name); here, but it would mean
      // an extra db lookup for each group as it validates the name. we know the
      // group must exist, so can just add directly

      // create and save new user group
      $ug = new sfGuardUserGroup();
      $ug->setsfGuardUser($new_user);
      $ug->setsfGuardGroup($group);

      $ug->save($con);
    }

    // make sure we return the user object
    return $new_user;
  }
}

Можете да видите, че настроих променлива на класа за съхраняване на текущия потребител, това не е необходимо, но спестява необходимостта да продължавате да извиквате sfContext::getInstance()->getUser()->getGuardUser() и е добра практика, тъй като формулярите ви стават по-сложни.

Дано това помогне! :)

person moote    schedule 13.06.2013
comment
добър отговор +1, сега искам да знам, вместо да запазя всички групи, както се казва в основната публикация, само за да запазя, нека кажем групата, наречена Група 1, възможно ли е също? как - person Reynier; 17.06.2013
comment
Благодаря @Reynier! Ако знаете името на групата, просто заменете цикъла foreach с: $new_user->addGroupByName('Your group name'); - person moote; 17.06.2013
comment
отлично, работи. Последен въпрос: имам връзка с таблица sfGuardUserProfile и ми харесва също да задам $id_empresa за новосъздадения потребител, как? мога ли да получа достъп от метод save() до setSfGuardUserProfile() метод, който е в BasesfGuardUser клас? - person Reynier; 18.06.2013