Yii Framework Forum: How to save multiple jqrelcopy-generated dropdownlists in a database? - Yii Framework Forum

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

How to save multiple jqrelcopy-generated dropdownlists in a database? Rate Topic: -----

#1 User is offline   bins 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 1
  • Joined: 12-November 14

Posted 15 November 2014 - 10:54 PM

I'm stuck in this problem for several days now. I can't seem to figure out how to do it. I am following this sample: <http://www.yiiframework.com/forum/index.php/topic/18155-extension-jqrelcopy> and I even recreated it. It's working but I can't seem to apply it in my project. Please help me. Thanks!

Brief Background: I am making a room reservation system. I am using 2 databases: one for the users and one for the schedule.

Here are my codes:<br>
ScheduleController.php
<?php

   class ScheduleController 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('admin'),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update'   actions
                'actions'=>array('create'),
                'users'=>array('@'),
            ),
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions'=>array('admin','delete', 'update', 'UpdateField'),
                '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()
    {
        $model=new Schedule;
        $modelscheditem = new SchedItems;

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);
        if(isset($_POST['Schedule'], $_POST['SchedItems']))
        {
            $model->attributes=$_POST['Schedule'];
            $modelscheditem->attributes=$_POST['SchedItems'];

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

            if($this->saveSchedItem($_POST['SchedItems']))
                $this->redirect(array('view','id'=>$modelscheditem->id_sched_items));
        }

        //$model=new Schedule;
        //$modelscheditem = new SchedItems;

        $data = array($modelscheditem);

        $this->render('create',array(
            'data'=>$data,
            'model'=>$model,
            'modelscheditem'=>$modelscheditem,

        ));
    }

    protected function saveSchedItem($formData)
    {
        if (empty($formData))
            return;

        $result = array();
        $idx=0;

        foreach($formData['fk_items'] as $fk_items)
        {
            $model = new SchedItem;
            $model->fk_items = $fk_items;

            $model->fk_items = $formData['fk_items'][$idx];

            //no id is submitted for new items
            if(!empty($formData['id_sched_items'][$idx]))
                $modelscheditem->id_sched_items = $formData['id_sched_items'][$idx];

            if(!$model->save())
                return false;

            $idx++;

        }
        return true;
    }



    /**
     * 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)
    {
        $model=$this->loadModel($id);
        $modelscheditem = new SchedItems;

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if(isset($_POST['Schedule'], $_POST['SchedItems']))
        {
            $model->attributes=$_POST['Schedule'];
            $modelscheditem->attributes=$_POST['SchedItems'];

            if($this->saveSchedItem($_POST['SchedItem']))
            {
                $this->redirect(array('view','id'=>$model->id_schedule));
                $this->redirect(array('view','id'=>$modelscheditem->id_sched_items));
            }

            $modelscheditem = new SchedItems;
            $data=$model->findAll();

            $this->render('update', array('data'=>$data,));

        }

        $this->render('update',array(
            'model'=>$model,
            'modelscheditem'=>$modelscheditem,
        ));

        $es = new EditableSaver('S');
        $es->update();
    }

    /**
     * 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('Schedule');
        $this->render('index',array(
            'dataProvider'=>$dataProvider,
        ));
    }

    /**
     * Manages all models.
     */

    public function actionAdmin()
    {
        $model=new Schedule('search');
        $model->unsetAttributes();  // clear any default values
        if(isset($_GET['Schedule']))
            $model->attributes=$_GET['Schedule'];

        $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 Schedule the loaded model
     * @throws CHttpException
     */

    public function loadModel($id)
    {
        $model=Schedule::model()->findByPk($id);
        if($model===null)
            throw new CHttpException(404,'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param Schedule $model the model to be validated
     */

    protected function performAjaxValidation($model)
    {
        if(isset($_POST['ajax']) && $_POST['ajax']==='schedule-form')
        {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

    public function actionAjaxupdate()
    {
        $autoIdAll = $_POST['autoId'];
        if(count($autoIdAll)>0)
        {
            foreach($autoIdAll as $autoId)
            {
                $model=$this->loadModel($autoId);
                if($act=='doActive')
                    $model->isActive = '1';
                if($act=='doInactive')
                    $model->isActive = '0';
                if($model->save())
                    echo 'ok';
                else
                    throw new Exception("Sorry",500);

            }
        }
    }

    /*public function actionUpdateEditable() {
        Yii::import('bootstrap.widgets.TbEditableSaver');
        $es = new TbEditableSaver($_GET['tableName']);  // 'modelName' is classname of model to be updated
        $es->update();
    }*/

    public function actionUpdateField()
    {
        $es = new EditableSaver('Schedule');  //'User' is name of model to be updated
        $es->update();
    }
}


_form.php
<?php
/* @var $this ScheduleController */
/* @var $model Schedule */
/* @var $form CActiveForm */
?>

<div class="form">

    <?php $form=$this->beginWidget('CActiveForm', array(
        'id'=>'schedule-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>-->
    <br>

    <?php echo $form->errorSummary($model); ?>

    <br>

    <!--Users-->
    <div class="row">
        <?php echo "User Name:";?>
        <br>
        <?php echo $form->dropDownList($model,'fk_userid', $model->getUser()); ?>
        <br>
        <?php echo $form->error($model,'fk_userid'); ?>
    </div>

    <!--Date From-->
    <div class="row">
        <?php echo $form->labelEx($model,'date_from'); ?>
        <?php $this->widget('zii.widgets.jui.CJuiDatePicker',array(
            'model'=>Schedule::model(),
            'name'=>'Schedule[date_from]',
            'value'=>$model->date_from,
            'options'=>array(
                'dateFormat' => 'yy-mm-dd',
                'showAnim'=>'clip',//'slide','fold','slideDown','fadeIn','blind','bounce','clip','drop'
                'changeMonth'=>true,
                'changeYear'=>true,
                'yearRange'=>'1900:date(y)',    // 1900 to current year
                //'minDate' => '1900-01-01',      // minimum date
                // maximum date(current date)
                //'showOn'=>'both', // 'focus', 'button', 'both'
                //'buttonText'=>Yii::t('ui',''),
                //'buttonImage'=>Yii::app()->request->baseUrl.'/images/calendar.png',
                //'buttonImageOnly'=>true,
            ),
            'htmlOptions'=>array(),
        ));
        ?>
        <?php echo $form->error($model,'date_from'); ?>
    </div>

    <!--Date To-->
    <div class="row">
        <?php echo $form->labelEx($model,'date_to'); ?>
        <?php $this->widget('zii.widgets.jui.CJuiDatePicker',array(
            'model'=>Schedule::model(),
            'name'=>'Schedule[date_to]',
            'value'=>$model->date_to,
            'options'=>array(
                'dateFormat' => 'yy-mm-dd',
                'showAnim'=>'clip',//'slide','fold','slideDown','fadeIn','blind','bounce','clip','drop'
                'changeMonth'=>true,
                'changeYear'=>true,
                'yearRange'=>'1900:date(y)',    // 1900 to current year
                //'minDate' => '1900-01-01',      // minimum date
                // maximum date(current date)
                //'showOn'=>'both', // 'focus', 'button', 'both'
                //'buttonText'=>Yii::t('ui',''),
                //'buttonImage'=>Yii::app()->request->baseUrl.'/images/calendar.png',
                //'buttonImageOnly'=>true,
            ),
            'htmlOptions'=>array(),
        ));
        ?>
        <?php echo $form->error($model,'date_to'); ?>
    </div>

    <!--Time From-->
    <div class="row">
        <?php echo $form->labelEx($model,'time_from'); ?>
        <?php $this->widget('booster.widgets.TbTimePicker',array(
                'model'=>Schedule::model(),
                'name' =>'Schedule[time_from]',
                'value' =>$model->time_from,
                'noAppend' => true, // mandatory
                'options' => array(
                    'disableFocus' => true, // mandatory
                    'showMeridian' => false // irrelevant
                ),
                'wrapperHtmlOptions' => array('class' => 'col-md-3'),
            )
        );
        ?>
        <?php echo $form->error($model,'time_from'); ?>
    </div>

    <!--Time To-->
    <div class="row">
        <?php echo $form->labelEx($model,'time_to'); ?>
        <?php $this->widget('booster.widgets.TbTimePicker',array(
                'model'=>Schedule::model(),
                'name' =>'Schedule[time_to]',
                'value' =>$model->time_to,
                'noAppend' => true, // mandatory
                'options' => array(
                    'disableFocus' => true, // mandatory
                    'showMeridian' => false // irrelevant
                ),
                'wrapperHtmlOptions' => array('class' => 'col-md-3'),
            )
        );
        ?>
        <?php echo $form->error($model,'time_to'); ?>
    </div>

    <!--Rooms-->
    <div class="row">
        <?php echo "Room Name"; ?>
        <br>
        <?php echo $form->dropDownList($model,'fk_room', $model->getRoom()); ?>
        <br>
        <?php echo $form->error($model,'fk_room'); ?>
    </div>

    <!--Items-->
    <?php echo "Item Name"//$form->labelEx($modelscheditem,'fk_items'); ?><br>
    <?php
    $this->widget('ext.jqrelcopy.JQRelcopy',array(
        'id' => 'copylink',
        'removeText' => 'Remove',
        'removeHtmlOptions' => array('style'=>'color:red'),
        'options' => array(
            'limit'=>5,
            'append'=>CHtml::tag('span',array('class'=>'hint'),'You can remove this line'),
        )
    ))
    ?>

    <?php if (empty($data)): ?>
        <div class="row copy">
            <?php echo CHtml::dropDownList('SchedItems[fk_items]', $modelscheditem, $model->getItem()); ?>
            <?php echo $form->error($modelscheditem,'fk_items'); ?>
        </div>
    <?php else: ?>
        <?php
        $idx = 0;
        $count = count($data);

        foreach($data as $modelscheditem):
            //the last added row is the row to copy
            $copyClass = ($idx == $count-1) ? ' copy' : '';

            ?>
            <div class="row<?php echo $copyClass;  ?>">
                <?php
                //don't allow to edit the id, don't copy the id to new records
                echo CHtml::hiddenField('SchedItems[fk_items]',$modelscheditem->id_sched_items,array('class'=>'nocopy'));
                echo CHtml::tag('span',array('class'=>'nocopy'),$modelscheditem->id_sched_items);
                ?>

                <?php echo CHtml::dropDownList('fk_items', $modelscheditem, $model->getItem()); ?>
                <?php echo $form->error($modelscheditem,'fk_items'); ?>

            </div>
            <?php
            $idx++;
        endforeach;
        ?>
    <?php endif; ?>
    <a id="copylink" href="#" rel=".copy">Add Item</a>


    <!--Current Date-->
    <div class="row">
        <?php echo $form->hiddenField($model,'createddate',array('value'=>date('yy-m-d H:m:s'))); ?>
    </div>

    <!--Approved By-->
    <div class="row">
        <?php echo $form->hiddenField($model,'approvedby',array('value'=>0)); ?>
    </div>


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

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

</div><!-- form -->[/code

create.php
[code]<?php
/* @var $this ScheduleController */
/* @var $model Schedule */



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

<h1>Create Schedule</h1>

<?php //$this->renderPartial('_form', array('data'=>$data, 'model'=>$model, 'modelscheditem'=>$modelscheditem));?>
<?php $this->renderPartial('_form', array(/*'model'=>$model,*/ /*'modelscheditem'=>$modelscheditem,*/ 'data'=>$data));?>
<?php //echo $this->renderPartial('_form', array('data'=>$data)); ?>


Schedule.php (model)
<?php

/**
 * This is the model class for table "schedule".
 *
 * The followings are the available columns in table 'schedule':
 * @property integer $id_schedule
 * @property string $fk_userid
 * @property string $date_from
 * @property string $date_to
 * @property string $time_from
 * @property string $time_to
 * @property integer $fk_room
 * @property string $status
 * @property string $remarks
 * @property integer $approvedby
 * @property string $createddate
 */
class Schedule extends CActiveRecord
{
    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return 'schedule';
    }

    /**
     * @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('fk_room, approvedby', 'numerical', 'integerOnly'=>true),
            array('fk_userid, status, remarks', 'length', 'max'=>45),
            array('date_from, date_to, time_from, time_to, createddate, approvedby', 'safe'),

            // The following rule is used by search().
            // @todo Please remove those attributes that should not be searched.
            array('id_schedule, fk_userid, date_from, date_to, time_from, time_to, fk_room, status, remarks, approvedby, createddate', '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(
            'rooms'=>array(self::BELONGS_TO, "Rooms", "fk_room"),
            'users'=>array(self::BELONGS_TO, "OstUseraccounts", "fk_userid"),
            'scheditems'=>array(self::BELONGS_TO, "SchedItems", "fk_items"),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'id_schedule' => 'Id Schedule',
            'fk_userid' => 'Fk Userid',
            'date_from' => 'Date From',
            'date_to' => 'Date To',
            'time_from' => 'Time From',
            'time_to' => 'Time To',
            'fk_room' => 'Fk Room',
            'status' => 'Status',
            'remarks' => 'Remarks',
            'approvedby' => 'Approvedby',
            'createddate' => 'Createddate',
        );
    }

    /**
     * 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_schedule',$this->id_schedule);
        $criteria->compare('fk_userid',$this->fk_userid,true);
        $criteria->compare('date_from',$this->date_from,true);
        $criteria->compare('date_to',$this->date_to,true);
        $criteria->compare('time_from',$this->time_from,true);
        $criteria->compare('time_to',$this->time_to,true);
        $criteria->compare('fk_room',$this->fk_room);
        $criteria->compare('status',$this->status,true);
        $criteria->compare('remarks',$this->remarks,true);
        $criteria->compare('approvedby',$this->approvedby);
        $criteria->compare('createddate',$this->createddate,true);

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

        ));
    }

    /**
     * @return CDbConnection the database connection used for this class
     */
    public function getDbConnection()
    {
        return Yii::app()->reservation_db;
    }

    /**
     * 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 Schedule the static model class
     */

    public static function model($className=__CLASS__)
    {
        return parent::model($className);
    }

    public function getRoom(){
        $list = Chtml::listData(Rooms::model()->findAll(),'id_rooms','room_name');
        return $list;
    }

    public function getItem(){
        $listItem = Chtml::listData(Items::model()->findAll(),'id_item','item_name');
        return $listItem;
    }

    public function getUser(){
        $listUser = Chtml::listData(OstUseraccounts::model()->findAll(),'userid','username');
        return $listUser;
    }

    public function getCount()
    {
        $model = Schedule::model()->findAll();
        $count = count($model);

        echo $count;
    }

}

0

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users