CGridview displays existent rows of the table (using DataProvider)
How to add new records through cgridview ?
Suppose you have Categories and Products (category has many products - see the below related wiki) http://www.yiiframework.com/wiki/681/update-related-models-of-a-model-using-listbox-and-checkboxlist-in-the-form/
we want to display all related products with a specific category and the last cgridview row as editable that we send it as new record, so how to do that ?
In your view Category (_form.php)
<h2>Related Products</h2>
<?php
$rels = new CArrayDataProvider($model->relatedProducts);
$data = CHtml::listData($model->relatedProducts,'id','title');
$listBox = CHtml::dropDownList('newRelProduct', null, $data);
$buttonPlus = CHtml::ajaxLink('add new record', $this->createUrl('addRelProduct'), [
'type' => 'POST',
'data' => array('cid' => $model->id, 'pid' => 'js:$("#newRelProduct").val()'),
'success' => 'function(html){ $.fn.yiiGridView.update("grid-related-products"); }'
]);
$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider' => $rels,
'id' => 'grid-related-products',
'columns' => array(
[
'name' => 'Title',
'header' => 'Product',
'footer' => $listBox,
],
[
'class' => 'CButtonColumn',
'template' => '{delete}',
'buttons' => ['delete' => ['url' => '$this->grid->Controller->createUrl("deleteRelProd",["pid"=>$data->id])']],
'footer' => $buttonPlus,
],
),
));
In your Category controller
public function actionAddRelProduct() {
$cid = Yii::app()->request->getParam('cid');
$pid = Yii::app()->request->getParam('pid');
$p = Products::model()->findByPk($pid);
$c = Category::model()->findByPk($cid);
if ($p && $c) {
$p->category_id = $cid;
if ($p->save())
echo 'ok';
else
echo 'error save';
}
}
public function actionDeleteRelProdt() {
$pid = Yii::app()->request->getParam('pid');
$p = Products::model()->findByPk($pid);
if ($p) {
$p->category_id = null;
if ($p->save())
echo 'ok';
else
echo 'error save';
}
}
If you have any questions, please ask in the forum instead.
Signup or Login in order to comment.