Yii2将隐藏输入设置为当前用户ID

时间:2015-05-04 15:47:14

标签: yii2 yii2-advanced-app

我尝试使用Yii2将表单字段设置为当前登录用户的ID。 这是我的表格:

    <?php $form = ActiveForm::begin();?>

        <?= Html::activeHiddenInput($model, 'id', array('value'=> $model->getId()));?>
        <?= $form->field($model, 'offer_type_id') ?>
        <?= $form->field($model, 'offer_description')->textArea(['rows' => 6])  ?>
        <?= $form->field($model, 'start_date') ?>
        <?= $form->field($model, 'end_date') ?>
        <?= $form->field($model, 'store_id') ?>

        <div class="form-group">
            <?= Html::submitButton('Submit', ['class' => 'btn btn-primary']) ?>
        </div>
    <?php ActiveForm::end(); ?>

这是我的模特:     

use Yii;
use yii\web\IdentityInterface;
/**
* This is the model class for table "tbl_offers".
*
* @property integer $offer_id
* @property integer $id
* @property integer $offer_type_id
* @property string $offer_description
* @property string $start_date
* @property string $end_date
* @property integer $store_id
*/
class TblOffers extends \yii\db\ActiveRecord implements IdentityInterface
{
   public static function findIdentity($id)
  {
     return static::findOne($id);
  }

 public static function findIdentityByAccessToken($token, $type = null)
 {
     return static::findOne(['access_token' => $token]);
 }

 public function getId()
 {
     return $this->id;
 }

 public function getAuthKey()
 {
     return $this->authKey;
 }

 public function validateAuthKey($authKey)
 {
     return $this->authKey === $authKey;
 }

/**
 * @inheritdoc
 */
public static function tableName()
{
    return 'tbl_offers';
}

/**
 * @inheritdoc
 */
public function rules()
{
    return [
        [[ 'id', 'offer_type_id', 'offer_description', 'start_date', 'end_date', 'store_id'], 'required'],
        [[ 'id', 'offer_type_id', 'store_id'], 'integer'],
        [['start_date', 'end_date'], 'safe'],
        [['offer_description'], 'string', 'max' => 8000]
    ];
}

/**
 * @inheritdoc
 */
public function attributeLabels()
{
    return [
        'id' => 'ID',
        'offer_type_id' => 'Offer Type ID',
        'offer_description' => 'Offer Description',
        'start_date' => 'Start Date',
        'end_date' => 'End Date',
        'store_id' => 'Store ID',
    ];
}

    public function getofferId()
{
    return $this->getPrimaryKey();
}

}

关于我哪里出错的任何想法?当我尝试保存表格后,我已经填写了剩下的表格,表单没有提交(我猜这是因为ID字段还没有填写)帮助将不胜感激!!

1 个答案:

答案 0 :(得分:1)

id为空,因为您将其设置为$this->id,但未在任何地方设置。

您可以使用Yii::$app->user->id获取当前登录的用户。因此,不需要隐藏字段或id的规则。您只需使用id手动设置ActiveRecord::beforeSave()

public function beforeSave($insert = true) {
    if ($insert) 
        $this->id = Yii::$app->user->id;
    return parent::beforeSave($insert);
}