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

BeHangat.Net - 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 _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 -->
  7. 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
    )); ?>
  8. 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);
    }
    }
  9. 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,
    )); ?>
  10. selesai
silahkan download source code tutorial ini beserta yiiframework di Sini

Itulah artikel tentang [Tutorial Yii 1] Membuat 1 form untuk data 2 tabel, Jika kalian masih ada yang kurang mengerti silahkan bertanya di kolom komentar yang sudah tersedia di bawah artikel ini dan jangan lupa untuk share artikel ini agar semakin banyak orang orang yang mengetahui dan membaca karena dengan membaca kita jadi tahu.

Jika ada kesalahan kata BaHangat.Net minta maaf, dan semoga artikel ini berguna, bermanfaat. Terimakasih sudah membaca dan sudah mampir di BeHangat.net sampai jumpa di pertemuan berikutnya.

Jika Kamu Punya Artikel, Puisi, Sesuatu Yang Ingin Kamu Upload, Maka Kamu Bisa Kirim Ke Alamat Email Di Bawah Ini:
Email : puisibehangat@gmail.com
Sertakan Judul Beserta Foto/Gambar

Reaksi:

You Might Also Like:

Use parse tool to easy get the text style on disqus comments:
Show Parser Hide Parser