Создайте новых пользователей с той же группой (группами), что и пользователь, вошедший в систему.

Я пытаюсь добавить новых пользователей в таблицу 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