mepihindeveloper
mepihindeveloper

Reputation: 195

How to add own data to POST in YII2?

i've question about adding some data outside form and send it with form data. Look! I have 3 fields ActiveForm:

name (text) email (email) course (hidden)

Ok, but i need to add one more named "status". I do not want to add hidden fields, just want to add inside controller or model.

How?

Controller:

public function actionFree()
{
    $model = new SubscribeForm();

    $this->view->title = "ШКОЛА ПИСАТЕЛЬСКОГО МАСТЕРСТВА: Новичок курс";

    if ($post = $model->load(Yii::$app->request->post())) {
        if ($model->save()) {
            Yii::$app->session->setFlash('success', 'Данные приняты');
            return $this->refresh();
        }
        else {
            Yii::$app->session->setFlash('error', 'Ошибка');
        }
    }
    else {
        // страница отображается первый раз
        return $this->render('free-course', ['model' => $model, 'course_id' => 1]);
    }
}

Model:

class SubscribeForm extends ActiveRecord
{
    public $fio;
    public $email;
    public $course;
    public $status;

    public static function tableName()
    {
        return 'users';
    }

    public function rules()
    {
        return [
            // username and password are both required
            [['fio', 'email'], 'required'],
            [['email'], 'unique'],
            ['email', 'email'],
            ['email', 'safe']
        ];
    }
}

Upvotes: 0

Views: 161

Answers (1)

Jap Mul
Jap Mul

Reputation: 18769

You could just set the value in your controller, like this:

public function actionFree()
{
    $model = new SubscribeForm();
    $model->status = 'your-status-value';
    // ... the rest of your code

Or you could add a default value in your model. This way you can still overrule the value from the controller or a form field, but will get this value when nothing else is supplied.

public function rules()
{
    return [
        ['status', 'default', 'value' => 'your-default-status-value'],
        // .. other rules
    ];
}

Upvotes: 1

Related Questions