Karate_Dog
Karate_Dog

Reputation: 1277

Yii 2.0 Passing data from Form to Controller

So recently, I migrate from CodeIgniter to Yii2.0 .

I have a view form that users can view and update the data my form looks like this :

<form role="form" name="damnedForm" action="">
   <div class="form-group">
        <label>SKU Code</label>
        <input class="form-control" name="pSku" value="<?= $model->sku ?>">
   </div>

   <div class="form-group">
         <label>Name</label>
         <input class="form-control" name="pName" value="<?= $model->name ?>">
   </div>

   <div>
         <button type="submit" class="btn btn-danger">Submit me</button>
   </div>
</form>

I have a controller named ProductsController, with method :

    function actionUpdate($id) {
      // bla bla bla // 
    }

My question is :

How do I pass all the data from the form to my controller? Do I have to make a manual post/get method and catch it on the controller? Or can I use the ActiveForm class ?

Upvotes: 0

Views: 2653

Answers (2)

chapskev
chapskev

Reputation: 982

// Your view for the form should be something like this exerpt

<div class="row">
    <div class="col-sm-6">
        <div class="the-box">
            <h4 class="small-title">Create New Department</h4>
            <?php
            $form = $this->beginWidget('CActiveForm', array(
                'id' => 'department-Department-form',
                'enableClientValidation' => true,
                'enableAjaxValidation' => false,
            ));
            ?>

            <!--<form role="form">-->
            <div class="form-group">
                <?php echo $form->labelEx($modelDepartment, 'dept_name'); ?>
                <?php
                echo $form->textField($modelDepartment, 'dept_name', array(
                    'id' => 'dept_name',
                    'class' => 'form-control',
                ));
                ?>
                <small style="color: #e9573f;"><?php echo $form->error($modelDepartment, 'dept_name'); ?>
                </small>

            </div>
            <div class="form-group">
                <?php echo $form->labelEx($modelDepartment, 'dept_contact'); ?>
                <?php
                echo $form->textField($modelDepartment, 'dept_contact', array(
                    'id' => 'dept_contact',
                    'class' => 'form-control',
//                        'placeholder' => 'ID Number',
                ));
                ?>
                <small style="color: #e9573f;"><?php echo $form->error($modelDepartment, 'dept_contact'); ?>
                </small>
            </div>




            <div class="form-group">
                <?php echo $form->labelEx($modelDepartment, 'dept_hod'); ?>
                <?php
                echo $form->dropDownList($modelDepartment, 'dept_hod', $employeeList, $htmlOptions = array(
                    'class' => 'form-control chosen-select'
                ));
                ?>

                <small style="color: #e9573f;"><?php echo $form->error($modelDepartment, 'dept_hod'); ?>
                </small>
            </div>
            <div class="form-group">
                <?php echo $form->labelEx($modelDepartment, 'dept_email'); ?>
                <?php
                echo $form->textField($modelDepartment, 'dept_email', array(
                    'id' => 'dept_email',
                    'class' => 'form-control',
//                        'placeholder' => 'ID Number',
                ));
                ?>
                <small style="color: #e9573f;"><?php echo $form->error($modelDepartment, 'dept_email'); ?>
                </small>
            </div>

            <button type="submit" class="btn btn-success"><i class="fa fa-sign-in"></i> Create</button>
            <?php $this->endWidget(); ?>
            <!--</form>-->
        </div><!-- /.the-box -->
    </div>
    <div class="col-sm-6">
        <div class="the-box">
            <?php
            echo '<pre>';
            print_r($dtData);
            ?>
        </div>
    </div>
</div>
//Your Model should be something like this format
class DepartmentForm extends CFormModel {

    public $dept_name;
    public $dept_contact;
    public $dept_hod;
    public $dept_email;

    public function rules() {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('dept_name, dept_contact, dept_hod, dept_email', 'required'),
            array('dept_hod', 'numerical', 'integerOnly' => true),
            array('dept_name, dept_contact', 'length', 'max' => 255),
            array('dept_email', 'length', 'max' => 150),
            // The following rule is used by search().
            // @todo Please remove those attributes that should not be searched.
            array('dept_id, dept_name, dept_contact, dept_hod, dept_email', 'safe', 'on' => 'search'),
        );
    }

    public function attributeLabels() {
        return array(
            'dept_id' => 'Dept',
            'dept_name' => 'Department Name',
            'dept_contact' => 'Department Contact',
            'dept_hod' => 'Department HOD',
            'dept_email' => 'Department Email',
        );
    }

}
//Your Controller should be something like this
public function actionManageDepartments() {

        $modelDept = new DepartmentForm(); //Initialize the model above
        $sql = new TSqlResource();


        //Handles the Work Profile
        if (Yii::app()->request->getPost('DepartmentForm')) {
            $modelDept->attributes = Yii::app()->request->getPost('DepartmentForm');
            if ($modelDept->validate()) {
                $data = array(
//                    dept_name, dept_contact, dept_hod, dept_email
                    'dept_name' => $modelDept->attributes ['dept_name'],
                    'dept_contact' => $modelDept->attributes ['dept_contact'],
                    'dept_hod' => $modelDept->attributes ['dept_hod'],
                    'dept_email' => $modelDept->attributes ['dept_email'],
                    'created_by' => Yii::app()->session['user']['profile_id'],
                );
                //insert into database
                $dataSql = $sql->postDepartment($data);

                if ($dataSql == true) {
                    YII::app()->user->setFlash('alert alert-success', ' Successfully Created <strong>' . $data['dept_name'] . '</strong>  Department. ');
                } else {
                    YII::app()->user->setFlash('alert alert-danger', 'Sorry  an Error Occured while adding <strong>' . $data['dept_name'] . '</strong> Department. Contact Admin for assistance ');
                }
            }
        }
//        #end work profile post
        $this->render('manageDepartments', array(
            'modelDepartment' => $modelDept,
            'dtData' => $dtData,
                )
        );
    }

Upvotes: 2

J&#248;rgen
J&#248;rgen

Reputation: 3567

If you don't already know, Yii2 comes with a fantastic gode-generator tool called Gii. You can access it with index.php?r=gii as long as you are in dev environment.

If you use this tool to create a CRUD for your model, you can look in the code how the forms are written and collected in the views and controller.

I recommend this approach, as its the "yii-way" of doing forms.

Welcome to Yii!

Upvotes: 1

Related Questions