Tags

, ,

Tutorial ini memerlukan ekstensi mdmsoft/yii2-widgets dan mdmsoft/yii2-ar-behavior.

Persiapan Database

Untuk contoh, kita gunakan tabel yang sederhana saja. Order dan OrderItem. Buat migration-nya

use yii\db\Migration;

class m160320_191634_order extends Migration
{
    public function up()
    {
        $tableOptions = null;
        if ($this->db->driverName === 'mysql') {
            // http://stackoverflow.com/questions/766809/whats-the-difference-between-utf8-general-ci-and-utf8-unicode-ci
            $tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB';
        }
        $this->createTable('{{%order}}', [
            'id' => $this->primaryKey(),
            'date' => $this->date()->notNull(),
            'keterangan' => $this->string(128),
            ], $tableOptions);

        $this->createTable('{{%order_item}}', [
            'id' => $this->primaryKey(),
            'order_id'=>  $this->integer()->notNull(),
            'product'=>  $this->string(64)->notNull(),
            'qty' => $this->integer()->notNull(),
            'FOREIGN KEY (order_id) REFERENCES {{%order}} (id) ON DELETE CASCADE ON UPDATE CASCADE'
            ], $tableOptions);
    }

    public function down()
    {
        $this->dropTable('{{%order_item}}');
        $this->dropTable('{{%order}}');
    }
}
php yii migrate


Setelah tabelnya terbentuk, selanjutnya adalah membuat AR-nya. Kita gunakan gii. Untuk mudahnya kita isi Table Name dengan *.
Screenshot from 2016-03-20 12:08:52
Lalu kita ubah Active Record sesuai kebutuhan kita. Untuk model Order kita tambahkan trait \mdm\behaviors\ar\RelationTrait dan kita tambahkan method setOrderItems().

class Order extends \yii\db\ActiveRecord
{
    use \mdm\behaviors\ar\RelationTrait;
    ...

    public function getOrderItems()
    {
        return $this->hasMany(OrderItem::className(), ['order_id' => 'id']);
    }

    public function setOrderItems($value)
    {
        $this->loadRelated('orderItems', $value);
    }
}

Sedangkan untuk model OrderItem kita ubah rules()-nya. Kita hapus attribute order_id dari rules lalu kita tambahkan attribute id.

class OrderItem extends \yii\db\ActiveRecord
{
    ...
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['product', 'qty'], 'required'],
            [['order_id', 'qty'], 'integer'],
            [['id'], 'safe'],
            [['product'], 'string', 'max' => 64],
        ];
    }
    ...
}

Selanjutnya kita generate CRUD dengan gii. Jika memakai deesoft/yii2-gii, tampilannya akan seperti ini
Screenshot from 2016-03-20 12:10:46
Setelah CRUD terbentuk, kita ubah sedikit controllernya.

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

    if ($model->load(Yii::$app->request->post())) {
        $transaction = Yii::$app->db->beginTransaction();
        try {
            $model->orderItems = Yii::$app->request->post('OrderItem', []);
            if ($model->save()) {
                $transaction->commit();
                return $this->redirect(['view', 'id' => $model->id]);
            }
            $transaction->rollBack();
        } catch (\Exception $ecx) {
            $transaction->rollBack();
            throw $ecx;
        }
    } else {
        return $this->render('create', [
                'model' => $model,
        ]);
    }
}

public function actionUpdate($id)
{
    $model = $this->findModel($id);

    if ($model->load(Yii::$app->request->post())) {
        $transaction = Yii::$app->db->beginTransaction();
        try {
            $model->orderItems = Yii::$app->request->post('OrderItem', []);
            if ($model->save()) {
                $transaction->commit();
                return $this->redirect(['view', 'id' => $model->id]);
            }
            $transaction->rollBack();
        } catch (\Exception $ecx) {
            $transaction->rollBack();
            throw $ecx;
        }
    } else {
        return $this->render('update', [
                'model' => $model,
        ]);
    }
}

Berikutnya kita ubah viewnya untuk menangani tabular input. Kita ubah file _form.php dan view.php

Ini penampakannya ketika dijalankan
Screenshot from 2016-03-20 14:19:09
Screenshot from 2016-03-20 14:51:26

Demo server gratisan http://goo.gl/NZmGWJ. Source code sila tengok yang ni deesoft/app

Advertisements