Modal Form not inserting data on database

Hi, I’m trying inserting events to fullcalendar, I already made an modal to access the form, but when I submit, no data goes to database. I’ve seen many topics related to this but I found them very confusing.

PS: When acessing the form itself without the modal, I can insert new data without problems.

Controller action


public function actionCreate()

    {

        $model = new Events();


        if ($model->load(Yii::$app->request->post()) && $model->save()) {


            return $this->redirect(['index']);

        } else {

            return $this->render('create', [

                'model' => $model,

            ]);

        }

    }

index.php




<?php

    Modal::begin([

        'toggleButton' => [

            'label' => '<i class="glyphicon glyphicon-plus"></i> Add',

            'class' => 'btn btn-success'

        ],

        'closeButton' => [

            'label' => 'Close',

            'class' => 'btn btn-danger btn-sm pull-right',

        ],

        'size' => 'modal-lg',


    ]);

    $myModel = new \backend\models\Events;

    echo  \Yii::$app->view->render('@backend/views/events/create', ['model'=> $myModel]);

    Modal::end();

    ?>



_form.php




<?php


use kartik\color\ColorInput;

use kartik\datetime\DateTimePicker;

use yii\helpers\Html;

use yii\widgets\ActiveForm;


/* @var $this yii\web\View */

/* @var $model backend\models\Events */

/* @var $form yii\widgets\ActiveForm */

?>


<div class="events-form">


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


    <?= $form->field($model, 'title')->textInput() ?>


    <?= $form->field($model, 'text')->textInput() ?>


    <?= $form->field($model, 'created_date')->widget(DateTimePicker::classname(), [

        'options' => ['placeholder' => 'Insire a data e hora do evento....'],

        'pluginOptions' => [

            'autoclose' => true

        ]

    ]); ?>


    <?= $form->field($model, 'event_type')->textInput() ?>


    <?= $form->field($model, 'event_type_color')->widget(ColorInput::classname(), [

        'options' => ['placeholder' => 'Selecione a cor do evento...'],

    ]); ?>




    <div class="form-group">

        <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

    </div>


    <?php ActiveForm::end(); ?>


</div>




model Events.php




<?php

namespace backend\models;


use Yii;

/**

 * This is the model class for table "events".

 *

 * @property integer $id

 * @property string  $title

 * @property string  $text

 * @property string  $created_date

 */

class Events extends \yii\db\ActiveRecord

{

    /**

     * @inheritdoc

     */

    public static function tableName()

    {

        return 'events';

    }

    /**

     * @inheritdoc

     */

    public function rules()

    {

        return [

            [ [ 'title', 'text','event_type','event_type_color' ], 'required' ],

            [ [ 'text' ], 'string' ],

            [ [ 'created_date' ], 'safe' ],

        ];

    }

    /**

     * @inheritdoc

     */

    public function attributeLabels()

    {

        return [

            'id'           => 'ID',

            'title'        => 'Título do Evento',

            'text'         => 'Text',

            'created_date' => 'Created Date',

            'event_type' => 'Tipo de Evento',

            'event_type_color' => 'Cor do Evento'

        ];

    }


}



Thanks for your time

Does the page get refreshed?

Yes, I can confirm that the page gets refreshed.

You should never mark attributes as safe that accept user input because they do not get validated! You have to save your form using jQuery ajax or Javascript XMLHttpRequest .

Assuming you’re using jQuery for the AJAX event. You need to make a POST request and serialize the form data.


$.ajax({

   'url': 'http://example.com/controller/create'

   'method': 'POST',

   'data': $('#my_form').serialize()

});

If you’re not using jQuery you will need to serialize the form yourself. It’s as simple as looping through the form elements getting the value and name then sending the form data in the XMLHttpRequest.send() method.


var form = document.querySelector('#my_form');


var data = [];


for(var field of form) {

  data.push(field.name + '=' + field.value)

}


data = '?' + data.join('&');



jQuery’s a little easier. If you’re using that, I’d recommend going with the first option.