Jumat, 09 Desember 2016

Widgets

[Tutorial Yii 1] Membuat 1 form untuk data 2 tabel

[Tutorial Yii 1] Membuat 1 form untuk data 2 tabel
Semua Ada - Tutorial kali ini untuk membuat 1 lembar form tapi nanti datanya masuk ke 2 tabel, kira2 gambarnya seperti dibawah ini ektension

tambahan yg dibutuhkan multimodelform, download dan lihat tutorial di http://www.yiiframework.com/extension/multimodelform/
langkahnya adalah:
  1. instal yii versi 1.1.15
  2. kopi folder multimodelform yg didapat dari download ke folder protected/extensions
  3. untuk tes silahkan buat database dan masukkan kode SQL ini
    CREATE TABLE IF NOT EXISTS 'group' (

    'id' int ( 11 ) NOT NULL AUTO_INCREMENT ,

    'title' varchar ( 100 ) NOT NULL ,

    PRIMARY KEY ( 'id' )

    ) ENGINE = InnoDB DEFAULT CHARSET = latin1 AUTO_INCREMENT = 4 ;



    CREATE TABLE IF NOT EXISTS 'member' (

    'id' int ( 11 ) NOT NULL AUTO_INCREMENT ,

    'groupid' int ( 11 ) NOT NULL ,

    'firstname' varchar ( 20 ) NOT NULL ,

    'lastname' varchar ( 200 ) NOT NULL ,

    'membersince' varchar ( 10 ) NOT NULL ,

    PRIMARY KEY ( 'id' )

    ) ENGINE = InnoDB DEFAULT CHARSET = latin1 AUTO_INCREMENT = 6 ;

  4. pakai gii generate model group dan member, generate juga crud group, crud member tidak usah, cukup modelnya aja
  5. edit file model Group.php yg ada di folder model menjadi spt ini
    <?php

    /**
    * This is the model class for table group .
    *
    * The followings are the available columns in table 'group':
    * @property integer $id
    * @property string $title
    */
    class Group extends CActiveRecord
    {
    /**
    * @return string the associated database table name
    */
    public function tableName()
    {
    return 'group';
    }

    /**
    * @return array validation rules for model attributes.
    */
    public function rules()
    {
    // NOTE: you should only define rules for those attributes that
    // will receive user inputs.
    return array(
    array('title', 'required'),
    array('title', 'length', 'max'=>100),
    // The following rule is used by search().
    // @todo Please remove those attributes that should not be searched.
    array('id, title', 'safe', 'on'=>'search'),
    );
    }

    /**
    * @return array relational rules.
    */
    public function relations()
    {
    // NOTE: you may need to adjust the relation name and the related
    // class name for the relations automatically generated below.
    return array(
    );
    }

    /**
    * @return array customized attribute labels (name=>label)
    */
    public function attributeLabels()
    {
    return array(
    'id' => 'ID',
    'title' => 'Title',
    );
    }

    /**
    * Retrieves a list of models based on the current search/filter conditions.
    *
    * Typical usecase:
    * - Initialize the model fields with values from filter form.
    * - Execute this method to get CActiveDataProvider instance which will filter
    * models according to data in model fields.
    * - Pass data provider to CGridView, CListView or any similar widget.
    *
    * @return CActiveDataProvider the data provider that can return the models
    * based on the search/filter conditions.
    */
    public function search()
    {
    // @todo Please modify the following code to remove attributes that should not be searched.

    $criteria=new CDbCriteria;

    $criteria->compare('id',$this->id);
    $criteria->compare('title',$this->title,true);

    return new CActiveDataProvider($this, array(
    'criteria'=>$criteria,
    ));
    }

    /**
    * Returns the static model of the specified AR class.
    * Please note that you should have this exact method in all your CActiveRecord descendants!
    * @param string $className active record class name.
    * @return Group the static model class
    */
    public static function model($className=__CLASS__)
    {
    return parent::model($className);
    }
    }
    ?>
  6. edit file GroupController.php di folder controllers
    <?php

    class GroupController extends Controller
    {
    /**
    * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
    * using two-column layout. See 'protected/views/layouts/column2.php'.
    */
    public $layout='//layouts/column2';

    /**
    * @return array action filters
    */
    public function filters()
    {
    return array(
    'accessControl', // perform access control for CRUD operations
    'postOnly + delete', // we only allow deletion via POST request
    );
    }

    /**
    * Specifies the access control rules.
    * This method is used by the 'accessControl' filter.
    * @return array access control rules
    */
    public function accessRules()
    {
    return array(
    array('allow', // allow all users to perform 'index' and 'view' actions
    'actions'=>array('index','view'),
    'users'=>array('*'),
    ),
    array('allow', // allow authenticated user to perform 'create' and 'update' actions
    'actions'=>array('create','update'),
    'users'=>array('@'),
    ),
    array('allow', // allow admin user to perform 'admin' and 'delete' actions
    'actions'=>array('admin','delete'),
    'users'=>array('admin'),
    ),
    array('deny', // deny all users
    'users'=>array('*'),
    ),
    );
    }

    /**
    * Displays a particular model.
    * @param integer $id the ID of the model to be displayed
    */
    public function actionView($id)
    {
    $this->render('view',array(
    'model'=>$this->loadModel($id),
    ));
    }

    /**
    * Creates a new model.
    * If creation is successful, the browser will be redirected to the 'view' page.
    */
    public function actionCreate()
    {
    Yii::import('ext.multimodelform.MultiModelForm');
    $model=new Group;
    $member = new Member;
    // Uncomment the following line if AJAX validation is needed
    // $this->performAjaxValidation($model);
    $validatedMembers = array(); //ensure an empty array
    if(isset($_POST['Group']))
    {
    $model->attributes=$_POST['Group'];

    if( //validate detail before saving the master
    MultiModelForm::validate($member,$validatedMembers,$deleteItems) &&
    $model->save()
    )
    {
    //the value for the foreign key 'groupid'
    $masterValues = array ('groupid'=>$model->id);
    if (MultiModelForm::save($member,$validatedMembers,$deleteMembers,$masterValues))
    $this->redirect(array('view','id'=>$model->id));
    }

    }

    $this->render('create',array(
    'model'=>$model,
    'member'=>$member,
    'validatedMembers' => $validatedMembers,
    ));
    }

    /**
    * Updates a particular model.
    * If update is successful, the browser will be redirected to the 'view' page.
    * @param integer $id the ID of the model to be updated
    */
    public function actionUpdate($id)
    {
    Yii::import('ext.multimodelform.MultiModelForm');
    $model=$this->loadModel($id);

    // Uncomment the following line if AJAX validation is needed
    // $this->performAjaxValidation($model);
    $member = new Member;
    $validatedMembers = array(); //ensure an empty array

    if(isset($_POST['Group']))
    {
    $model->attributes=$_POST['Group'];
    $masterValues = array ('groupid'=>$model->id);
    if( //Save the master model after saving valid members
    MultiModelForm::save($member,$validatedMembers,$deleteMembers,$masterValues) && $model->save()
    )
    $this->redirect(array('view','id'=>$model->id));


    //if($model->save())
    // $this->redirect(array('view','id'=>$model->id));
    }

    $this->render('update',array(
    'model'=>$model,
    'member'=>$member,
    'validatedMembers' => $validatedMembers,
    ));
    }

    /**
    * Deletes a particular model.
    * If deletion is successful, the browser will be redirected to the 'admin' page.
    * @param integer $id the ID of the model to be deleted
    */
    public function actionDelete($id)
    {
    $this->loadModel($id)->delete();

    // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
    if(!isset($_GET['ajax']))
    $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
    }

    /**
    * Lists all models.
    */
    public function actionIndex()
    {
    $dataProvider=new CActiveDataProvider('Group');
    $this->render('index',array(
    'dataProvider'=>$dataProvider,
    ));
    }

    /**
    * Manages all models.
    */
    public function actionAdmin()
    {
    $model=new Group('search');
    $model->unsetAttributes(); // clear any default values
    if(isset($_GET['Group']))
    $model->attributes=$_GET['Group'];

    $this->render('admin',array(
    'model'=>$model,
    ));
    }

    /**
    * Returns the data model based on the primary key given in the GET variable.
    * If the data model is not found, an HTTP exception will be raised.
    * @param integer $id the ID of the model to be loaded
    * @return Group the loaded model
    * @throws CHttpException
    */
    public function loadModel($id)
    {
    $model=Group::model()->findByPk($id);
    if($model===null)
    throw new CHttpException(404,'The requested page does not exist.');
    return $model;
    }

    /**
    * Performs the AJAX validation.
    * @param Group $model the model to be validated
    */
    protected function performAjaxValidation($model)
    {
    if(isset($_POST['ajax']) && $_POST['ajax']==='group-form')
    {
    echo CActiveForm::validate($model);
    Yii::app()->end();
    }
    }
    }
    ?>
  7. edit file _form.php di folder view/group
    <?php
    /* @var $this GroupController */
    /* @var $model Group */
    /* @var $form CActiveForm */
    ?>

    <div class="form wide">
    <?php $form=$this->beginWidget('CActiveForm', array(
    'id'=>'group-form',
    // Please note: When you enable ajax validation, make sure the corresponding
    // controller action is handling ajax validation correctly.
    // There is a call to performAjaxValidation() commented in generated controller code.
    // See class documentation of CActiveForm for details on this.
    'enableAjaxValidation'=>false,
    )); ?>

    <p class="note">Fields with <span class="required">*</span> are required.</p>

    <?php //echo $form->errorSummary($model);
    echo $form->errorSummary(array_merge(array($model),$validatedMembers));
    ?>

    <div class="row">
    <?php echo $form->labelEx($model,'title'); ?>
    <?php echo $form->textField($model,'title',array('size'=>60,'maxlength'=>100)); ?>
    <?php echo $form->error($model,'title'); ?>
    </div>


    <?php

    // see http://www.yiiframework.com/doc/guide/1.1/en/form.table
    // Note: Can be a route to a config file too,
    // or create a method 'getMultiModelForm()' in the member model

    $memberFormConfig = array(
    'elements'=>array(
    'firstname'=>array(
    'type'=>'text',
    'maxlength'=>40,
    ),
    'lastname'=>array(
    'type'=>'text',
    'maxlength'=>40,
    ),
    'membersince'=>array(
    'type'=>'dropdownlist',
    //it is important to add an empty item because of new records
    'items'=>array(''=>'-',2009=>2009,2010=>2010,2011=>2011,),
    ),



    ));

    $this->widget('ext.multimodelform.MultiModelForm',array(
    'id' => 'id_member', //the unique widget id
    'formConfig' => $memberFormConfig, //the form configuration array
    'model' => $member, //instance of the form model

    //if submitted not empty from the controller,
    //the form will be rendered with validation errors
    'validatedItems' => $validatedMembers,

    //array of member instances loaded from db
    'data' => $member->findAll('groupid=:groupId', array(':groupId'=>$model->id)),
    ));
    ?>



    <div class="row buttons">
    <?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
    </div>

    <?php $this->endWidget(); ?>

    </div><!-- form -->
  8. edit file create.php di view/group menjadi
    <?php
    /* @var $this GroupController */
    /* @var $model Group */

    $this->breadcrumbs=array(
    'Groups'=>array('index'),
    'Create',
    );

    $this->menu=array(
    array('label'=>'List Group', 'url'=>array('index')),
    array('label'=>'Manage Group', 'url'=>array('admin')),
    );
    ?>

    <h1>Create Group</h1>

    <?php $this->renderPartial('_form', array(
    'model'=>$model,
    'member'=>$member,
    'validatedMembers'=>$validatedMembers
    )); ?>
  9. edit file Member.php di folder model menjadi
    <?php

    /**
    * This is the model class for table "member".
    *
    * The followings are the available columns in table 'member':
    * @property integer $id
    * @property integer $groupid
    * @property string $firstname
    * @property string $lastname
    * @property string $membersince
    */
    class Member extends CActiveRecord
    {
    /**
    * @return string the associated database table name
    */
    public function tableName()
    {
    return 'member';
    }

    /**
    * @return array validation rules for model attributes.
    */
    public function rules()
    {
    // NOTE: you should only define rules for those attributes that
    // will receive user inputs.
    return array(
    array('firstname, lastname, membersince', 'required'),

    array('firstname', 'length', 'max'=>20),
    array('lastname', 'length', 'max'=>200),
    // The following rule is used by search().
    // @todo Please remove those attributes that should not be searched.
    array('id, groupid, firstname, lastname, membersince', 'safe', 'on'=>'search'),
    );
    }

    /**
    * @return array relational rules.
    */
    public function relations()
    {
    // NOTE: you may need to adjust the relation name and the related
    // class name for the relations automatically generated below.
    return array(
    );
    }

    /**
    * @return array customized attribute labels (name=>label)
    */
    public function attributeLabels()
    {
    return array(
    'id' => 'ID',
    'groupid' => 'Groupid',
    'firstname' => 'Firstname',
    'lastname' => 'Lastname',
    'membersince' => 'Membersince',
    );
    }

    /**
    * Retrieves a list of models based on the current search/filter conditions.
    *
    * Typical usecase:
    * - Initialize the model fields with values from filter form.
    * - Execute this method to get CActiveDataProvider instance which will filter
    * models according to data in model fields.
    * - Pass data provider to CGridView, CListView or any similar widget.
    *
    * @return CActiveDataProvider the data provider that can return the models
    * based on the search/filter conditions.
    */
    public function search()
    {
    // @todo Please modify the following code to remove attributes that should not be searched.

    $criteria=new CDbCriteria;

    $criteria->compare('id',$this->id);
    $criteria->compare('groupid',$this->groupid);
    $criteria->compare('firstname',$this->firstname,true);
    $criteria->compare('lastname',$this->lastname,true);
    $criteria->compare('membersince',$this->membersince,true);

    return new CActiveDataProvider($this, array(
    'criteria'=>$criteria,
    ));
    }

    /**
    * Returns the static model of the specified AR class.
    * Please note that you should have this exact method in all your CActiveRecord descendants!
    * @param string $className active record class name.
    * @return Member the static model class
    */
    public static function model($className=__CLASS__)
    {
    return parent::model($className);
    }
    }
  10. edit file update.php di folder view/group menjadi
    <?php
    /* @var $this GroupController */
    /* @var $model Group */

    $this->breadcrumbs=array(
    'Groups'=>array('index'),
    $model->title=>array('view','id'=>$model->id),
    'Update',
    );

    $this->menu=array(
    array('label'=>'List Group', 'url'=>array('index')),
    array('label'=>'Create Group', 'url'=>array('create')),
    array('label'=>'View Group', 'url'=>array('view', 'id'=>$model->id)),
    array('label'=>'Manage Group', 'url'=>array('admin')),
    );
    ?>

    <h1>Update Group <?php echo $model->id; ?></h1>

    <?php $this->renderPartial('_form', array('model'=>$model,
    'member'=>$member,
    'validatedMembers' => $validatedMembers,
    )); ?>
  11. selesai
silahkan download source code tutorial ini beserta yiiframework di Sini

SHARE THIS

Author:

3 komentar: