Search code examples
phpformsyiimodelyii-cactiverecord

Yii Framework - in a main view I can't add a CActiveForm because it needs a model, when I set the model nothing happens


I put this on my view, and I have to add the <?php $model = new Usuarios; ?> and it works but then actually does not send the info to the database.

I tried on another view (index view) and without this it works: <?php $model = new Usuarios; ?>.

<a class="list-group-item">
    <form role="form">
        <div class="form">
            <?php $model = new Usuarios; ?>
            <?php $form = $this->beginWidget('CActiveForm', array(
                'id' => 'usuarios-form',
                'action' => $this->createUrl("usuarios/create"),
                'enableAjaxValidation' => false,
            )); ?>

            <?php echo $form->errorSummary($model); ?>

            <div style="padding:1px;" class="input-group input-group-sm">
                <span class="input-group-addon">
                    <span class="glyphicon glyphicon-user" style="color:white"></span>
                </span>
                <?php echo $form->textField($model, 'Nombre', array('maxlength' => 128, 'placeholder' => 'Nombre y Apellido')); ?>
                <?php echo $form->error($model, 'Nombre'); ?>
            </div>

            <div class="row buttons" style="padding:4%; color:white ; font-size:1.5vmax; font-family: Signika; border-radius:30px">
                <center>
                    <?php echo CHtml::submitButton($model->isNewRecord ? 'Enviar' : 'Save'); ?>
                </center>
            </div>
            <?php $this->endWidget(); ?>   
        </div>
    </form>
</a>

Solution

  • This is what your controller action should look like:

    public function actionCreate() {
        $model = new Usuarios;
    
        if(isset($_POST['Usuarios'])) {
    
            // Populate the model with values from form
            // These attributes must be set to safe in the model rules() function
            $model->attributes = $_POST['Usuarios'];
    
            // ->save() will validate the model with the validation rules 
            // in the Usuarios.php model. If you do not want validation, use ->update()
            if($model->save()) {
                $this->redirect(array('view', 'id' => $model->primaryKey));
            }
        }
    
        $this->render('create', array(
            'model' => $model, // You pass the model to the view page
        ));
    }
    

    In your model, you need to update the rules() function to accept the fields for saving in the database:

    public function rules() {
        return array(
            array('Nombre', 'safe'),
        );
    }