Skip to content
On this page

Working with forms

This example shows how to use a yii\widgets\ActiveForm in a controller which uses a [[/guide/ngrest/model]].


When using the CMS, there is an visual form builder module available as package.

Controller logic

public function actionIndex()
    $model = new ExampleFormModel();

    // Validate model
    if ($model->load(Yii::$app->request->post()) && $model->validate()) {
        // All data submitted is valid
        // Do stuff with the data
        // Save the model
        if ($model->save()) {

            // Now you could redirect to a success page or
            // print a success message in the index view
            // return $this->redirect(['/module/controller/index']);

    return $this->render('index', [
        'model' => $model // pass model to the view to display extra informations

View file

The corresponding view file views/controller/index.php could look like this:

<?php if(Yii::$app->session->getFlash('success')): ?>
    <p>Thank you for your request</p>
<?php else: ?>
    <?php $form = \yii\widgets\ActiveForm::begin(); ?> <!-- start of form -->

    <?= $form->field($model, 'field1'); ?> <!-- example field definition -->
    <?= $form->field($model, 'field2'); ?> <!-- example field definition -->
    <?= $form->field($model, 'field3'); ?> <!-- example field definition -->

    <?= yii\helpers\Html::submitButton('Verify', ['class' => 'button']) ?>

    <?php \yii\widgets\ActiveForm::end(); ?> <!-- end of form -->

<?php endif; ?>

The success variable is used to determine if the model was successfully saved - that's only required if you do not redirect the user to another page.

See Yii 2 ActiveForm for more information.

Image and file uploads

In order to enable image and file upload you can just use the file input:

<?= $activeForm->field($form, 'attachment[]')->fileInput(['multiple' => true, 'accept' => 'file/*']) ?>

Validation inside the model is done by luya\admin\ngrest\validators\StorageUploadValidator. This will not only validate but also save the file in LUYA admin storage [[]]

[['attachment'], StorageUploadValidator::class, 'multiple' => true],

In order to display the data inside the NgRest CRUD system you have to apply the luya\admin\ngrest\plugins\FileArray plugin for the given field name:

 * @inheritdoc
public function ngRestAttributeTypes()
    return [
        // ...
        'attachment' => 'fileArray',