How to create a form in Yii?

Member

by jasen , in category: PHP Frameworks , 2 years ago

How to create a form in Yii?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by addison , a year ago

@jasen 

To create a form in Yii, follow these steps:

  1. Create a new action in a controller:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
public function actionCreate()
{
    $model = new MyFormModel;

    if(Yii::$app->request->isPost && $model->load(Yii::$app->request->post()))
    {
        if($model->validate())
        {
            // Do something with the submitted form data
            // Redirect to another page or display a success message
        }
    }

    return $this->render('create', ['model' => $model]);
}


  1. Create a view file for the form:
1
2
3
4
5
6
7
8
9

field($model, 'name') ?>

field($model, 'email') ?>

 'btn btn-primary']) ?>



  1. Add validation rules to the model:
1
2
3
4
5
6
7
public function rules()
{
    return [
        [['name', 'email'], 'required'],
        ['email', 'email']
    ];
}


  1. The form can now be accessed by navigating to the controller action URL, such as http://example.com/my-controller/create.