[Yii Framework] Update Data Table/ Grid Form With JQrelCopy

Many people ask about “how to update many data in table form?”. I have posted about how to create (not update ) it here https://sabitlabscode.wordpress.com/2012/06/14/yii-framework-ajax-dependent-dropdownlist-in-multi-value-grid-form/ , here https://sabitlabscode.wordpress.com/2012/05/28/yii-framework-insert-banyak-data-dengan-jappendo/ and here https://sabitlabscode.wordpress.com/2011/08/10/yii-framework-membuat-entry-data-tabel-dinamis-dengan-jappendo/. But some

Okeh, first our form will be like this :

t1

And form update will be like this :

t2

Okey, you can see it in update form it will have the previous value that we have been added before. We can delete previous data too with click in “delete” link in form.

I assume you have been knowed to make create form (see my previous post). Now, we will learn how to make an update form. First, download jqrelcopy extension and insert it in your application (In this post i just post with jqrelcopy extension). Next, we need to display previous data when we want to update. So. insert this code on your form in view :

 <div>

<?php 
// define form
$form=$this->beginWidget('CActiveForm', array(
    'id'=>'name-form',
    'enableAjaxValidation'=>false,
)); ?>

<?php 
     // define jqrelcopy
    $this->widget('ext.jqrelcopy.JQRelcopy',array(
        'id' => 'copylink',
        'removeText' => 'Delete', // delete label
        'removeHtmlOptions' => array('style'=>'color:red'),  // style for delete link
        'options' => array(
            'copyClass'=>'newcopy',
            'clearInputs'=>true,
            'excludeSelector'=>'.skipcopy',  // add some class not to copy when we add 
        )
    ));
?>
        <a id="copylink" href="#" rel=".yangdicopy">Add New</a>

        <table>
            <tr>
                <th>Some Text Here</th>
            </tr>

            <?php 
            if(!$model->isNewRecord){
                //if it in update mode, display all value from previous save
                use findAll (or another metode) to show all data before
                foreach (YourModel::model()->findAllByAttributes(array('field1'=>yourParam)) as $key => $value) { 
           ?>
                    <tr>
                        <?php
                           // show all value
                            echo '<td>'.Chtml::textArea('ques3[]',$value->attribute1,array('rows'=>2, 'cols'=>40)).'</td>';
                            // this code use for delete value, it will execution controller and action that set in ajax call
                            echo "<td class='skipcopy'><a href='#' onclick=\"
                                    $.ajax({
                                            url:'".Yii::app()->createUrl('yourController/yourAction')."',
                                            data: {id:$(this).attr('id')}
                                    });
                                    $(this).parent().parent().remove(); return false;
                                \" 
                                style=\"color:red;\" id='produ".$value->idAttribute."' >Delete</a></td>"; 
                                // produ."$value->idAttribute" use to make unique tag in each jqrel table
                        ?>
                    </tr>   
            <?php }} ?>

            <tr>
                <?php
                    // this is standar form will show to add data
                    echo '<td>'.Chtml::textArea('ques3[]','',array('rows'=>2, 'cols'=>40)).'</td>';
                    echo "<td class='skipcopy'><a href='#' onclick=\"
                            $(this).parent().parent().remove(); return false;
                        \" 
                        style=\"color:red;\" id='produ' >Delete</a></td>";
                ?>
            </tr>
        </table>

    <div>
        <?php echo CHtml::submitButton('Save'); ?>
    </div>

<?php $this->endWidget(); ?>
</div><!-- form -->

After that, we will make a code in controller to save update data. Make this in you controller :

 public function actionUpdate()
{
    if(isset($_POST['ques3']))
    {

            $data=YourModel::model()->findAllByAttributes(array('field1'=>yourParam));
            foreach ($_POST['ques3'] as $q3k => $q3v)
            {
                 // if you find index key from $data, so it will be update the data
                 // if no, so make new data
                if(isset($data[$q3k]))
                {
                    $tabdata=YourModel::model()->findByPk($data[$q3k]->idAttribute);  
                }
                else
                {
                    $tabdata=new YourModel;
                }
                $tabdata->field2=$q3v;
                $tabdata->field1=$model->idAttribute;
                $tabdata->save();
            }
    }

    $this->render('update');
}

And for delete existing data, make this code on your controller :

 public function actionDelete()
    {
        if(isset($_GET['id']))
        {
            $idnya=substr($_GET['id'], 5); // remember we need to catch id from "produ" and the id 
             //is the next value after "produ"
            $model=YourModel::model()->findByPk($idnya); search data
            if($model!==null)  // if we can find data, delete it
                $model->delete();
        }
    }

Finsih… Hope it help…

Happy coding… 😀

7 Responses to [Yii Framework] Update Data Table/ Grid Form With JQrelCopy

  1. Joad.s says:

    Hi,
    Thanks for providing information on Yii framework. I think Yii is a fast, secure, high performance PHP framework for developing web 2.0 applications, and The Yii Development is top class, affordable and offer several features to build unique and quality applications.

  2. wow says:

    gan misal gw mau ambil variabelnya
    data = (txtfield1+txtfield2+..)
    gtu gmna gan
    thx

  3. failed to clone mas..juga ngak ada example actionCreate nya

  4. G mana mau buat validasi nya ya mas? pls urgent

    if(isset($_POST[‘Enddetailnq’]))
    {
    $totalPcs = array_sum($_POST[‘Enddetailnq’][‘HED_PCS’]);
    $recordx = Endheaderpf::model()->findAll(array(‘condition’=>’HEH_ID=:ids’,’params’=> array(‘:ids’ =>$id)));
    $Pcs = 0;
    foreach($recordx as $a){
    $Pcs = $a->HEH_ENDPCS;
    }
    $suis = false;
    $total = count($_POST[‘Enddetailnq’][‘HLI_ID’]);
    $activeTab = 0;
    for ($i = 0; $i HEH_ID = $id;
    $enddetailnq->HLI_ID = $_POST[‘Enddetailnq’][‘HLI_ID’][$i];
    $enddetailnq->HED_RPASS = $_POST[‘Enddetailnq’][‘HED_RPASS’][$i];
    $enddetailnq->HED_LOGSERIAL_CODE = $_POST[‘Enddetailnq’][‘HED_LOGSERIAL_CODE’][$i];
    $enddetailnq->HED_LOGSERIAL_FROM = $_POST[‘Enddetailnq’][‘HED_LOGSERIAL_FROM’][$i];
    $enddetailnq->HED_LOGSERIAL_TO = $_POST[‘Enddetailnq’][‘HED_LOGSERIAL_TO’][$i];
    $enddetailnq->HED_PCS = $_POST[‘Enddetailnq’][‘HED_PCS’][$i];
    $enddetailnq->HED_VOL = $_POST[‘Enddetailnq’][‘HED_VOL’][$i];

    if ($enddetailnq->save()) {
    $suis = true;
    }

    }
    }
    if ($suis == true) {
    Yii::app()->user->setFlash(‘successD’,’Your data have been successfully saved. ‘);
    $this->redirect(Yii::app()->request->urlReferrer);
    }else{
    Yii::app()->user->setFlash(‘errorD’,’Failed to save, Please make sure all required fields are filled out correctly. ‘);
    }
    }

  5. cahya satya says:

    [Ask]
    gan kalo mau buat pagination di dalam foreach gimana ya kodingnya ?
    itu kan ada banyak teksField, nah jika itukan ada 4 text field di depannya dikasih angka 1 ….4.
    Mohon bantuannya gan

Leave a comment