yii 2.0中表單小組件介紹

來源:互聯網
上載者:User
這篇文章主要給大家介紹了關於yii 2.0中表單小組件的使用方法,文中介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面來一起看看吧。

前言

本文主要介紹的是關於yii 2.0中表單小組件使用的相關內容,分享出來供大家參考學習,下面來看看詳細的介紹:

使用方法

首先建立model層,因為要使用表單小組件 所以要載入相應的組件,這裡需要的組件有yii\widgets\ActiveForm yii\helpers\Html

接下來在model定義的class裡 寫方法,首先我們要定義需要使用表單小組件的name值

不多說上代碼


<?php/*** Created by PhpStorm.* User: jinlei* Date: 2017/5/10* Time: 9:35*/namespace frontend\models;use yii\base\Model;use yii\widgets\ActiveForm;use yii\helpers\Html;class Form extends Model{public $name;public $pwd;public $sex;public $hobby;public $age;public function rules(){return[];}public function attributeLabels(){return[‘name'=>'使用者名稱',‘pwd'=>'密碼',‘sex'=>'性別',‘hobby'=>'愛好',‘age'=>'年齡'];}static public function dataarr($data){$arr = array();foreach($data as $key=>$value){$arr[$value[‘kid']] = $value[‘kname'];}return $arr;}}

在這個model裡 有將英文表頭轉換中文的方法 attributuLabels

還有 我們處理單選多選還有下拉框值得方式 dataarr

接下來 我 們需要建立controller


<?php/*** Created by PhpStorm.* User: jinlei* Date: 2017/5/10* Time: 9:39*/namespace frontend\controllers;use yii\web\Controller;use yii;use db;use frontend\models\Form;class LoginController extends Controller{public function actionIndex(){$sql = ‘select kid,kname from exam_tiku';$data = yii::$app->db->createCommand($sql)->queryAll();$arr = Form::dataarr($data);//var_dump($arr);die;$model = new Form();return $this->render(‘index',[‘model'=>$model,'data'=>$arr]);}public function actionAdd(){$data = Yii::$app->request->post();echo $name = $data[‘Form'][‘name'];}}

然後就是在我門的view層 展示出來


<?php/*** Created by PhpStorm.* User: jinlei* Date: 2017/5/10* Time: 9:41*/use yii\helpers\Html;use yii\widgets\ActiveForm;$form = ActiveForm::begin([‘id' => ‘login-form',‘options' => [‘class' => ‘form-horizontal'],‘action'=>'?r=login/add',‘method'=>'post',]) ?><?= $form->field($model, ‘name') ?><?= $form->field($model, ‘pwd')->passwordInput() ?><?= $form->field($model, ‘sex')->radioList([‘0'=>'男','1'=>'女']) ?><?= $form->field($model, ‘hobby')->checkboxList([‘basketball'=>'籃球','baseball'=>'棒球','swim'=>'遊泳']) ?><?= $form->field($model, ‘age')->dropDownList($data) ?><p class=”form-group”><p class=”col-lg-offset-1 col-lg-11″><?= Html::submitButton(‘Login', [‘class' => ‘btn btn-primary']) ?></p></p><?php ActiveForm::end() ?>

在這個頁面中 我們展示了 文字框 密碼框 單選多選下拉框 其中下拉框的資料是從db中讀取的

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.