PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, January 2, 2022

[FIXED] How to get value of attribute in controller from Form in view Yii 2

 January 02, 2022     mysql, php, yii, yii2, yii2-basic-app     No comments   

Issue

I created a table named (users) it has two columns: name and pass. In view I created form like this:

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

<div class="form-group">
  <?= $form->field($model, 'user') ?>
  <?= $form->field($model, 'password') ?>
    <div class="col-lg-offset-1 col-lg-11">
        <?= Html::submitButton('Login', ['class' => 'btn btn-primary']) ?>
    </div>
</div>
<?php ActiveForm::end() ?>

So I need to pass this two attributes to controller to insert into data base.


Solution

In YourController.php
assuing you have an Create action for manage your insert in db and a create view for manage the user input (a view for only display the correct result )

    <?php

    namespace app\controllers;

    use Yii;
    use yii\web\Controller;
    use app\models\EntryForm;

    class YourController extends Controller
    {
        // ...existing code...

        public function actionCreate()
        {
            $model = new User();

            if ($model->load(Yii::$app->request->post()) && $model->validate()) {
                // valid data received in $model

                // 
                if( $model->save()){
                    return $this->render('create', ['model' => $model]);
                } else {
                    // this is just for debug  
                    var_dump('not inserted');
                    die();
                }

            } else {
                // either the page is initially displayed or there is some validation error
                return $this->render('view', ['model' => $model]);
            }


        // render the initial page per allow to the user input 
        return $this->render('create', ['model' => $model]);
       }  

       ....
   }


Answered By - ScaisEdge
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing