Answer the question
In order to leave comments, you need to log in
How to organize Tabular data entry in YII?
Dear, good day! I posted earlier but still haven't found an answer.
I have a table on my page. it comes from the base. I need to update it once a week. how can, for example, upload it in the admin panel and edit it in a public form (like excel or phpmyadmin). then by the button ok to write down entu to the base. thank you
did so
in the view
<div class="about-infos">
<h2> Укажите цены </h2>
</div>
<div class="form">
<?php echo CHtml::beginForm(); ?>
<table>
<tr><th>Наименование</th><th>Цена мин.</th><th>Цена макс.</th></tr>
<?php foreach($items as $i=>$item): ?>
<tr>
<td width="300px" valign="top"><?php echo CHtml::activeTextField($item,"[$i]name"); ?></td>
<td><?php echo CHtml::activeTextField($item,"[$i]price_min"); ?></td>
<td><?php echo CHtml::activeTextField($item,"[$i]price_max"); ?></td>
<!--<td><?php echo CHtml::activeTextArea($item,"[$i]id"); ?></td>-->
</tr>
<?php endforeach; ?>
</table>
<?php echo CHtml::submitButton('Сохранить'); ?>
<?php echo CHtml::endForm(); ?>
</div><!-- form -->
public function actionTablem()
{
//$model = new monitoring;
$items=$this->getItemsToUpdate(); // очевидно тут формируем массив из объектов по правилам известным вам (что-то из БД, что-то новое)
if(isset($_POST['Item']))
{
$valid=true;
foreach($items as $i=>$item) // перебираем объекты, обновляя их данными из $_POST
{
if(isset($_POST['Item'][$i]))
$item->attributes=$_POST['Item'][$i];
$valid=$item->validate() && $valid;
if($items->getErrors()) {
var_dump($items->getErrors());
die();
}
}
if($valid)
{
foreach($items as $item) {
//$item->attributes=$_POST['item'];
$item->save();
}
//$this->redirect(array());
//monitoring::model()-> update();
}
// если все модели валидны, сейвим их
// ...do something here
}
// displays the view to collect tabular input
$this->render('Tablem',array('items'=>$items));
}
?php
/**
* This is the model class for table "{{monitoring}}".
*
* The followings are the available columns in table '{{monitoring}}':
* @property integer $id
* @property string $name
* @property string $price_min
* @property string $price_max
*/
class Monitoring extends CActiveRecord
{
/**
* @return string the associated database table name
*/
public function tableName()
{
return '{{monitoring}}';
}
/**
* @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('id, name, price_min, price_max', 'required'),
array('id', 'numerical', 'integerOnly'=>true),
array('name, price_min, price_max', 'length', 'max'=>255),
// The following rule is used by search().
// @todo Please remove those attributes that should not be searched.
array('id, name, price_min, price_max', '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',
'name' => 'Name',
'price_min' => 'Price Min',
'price_max' => 'Price Max',
);
}
/**
* 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('name',$this->name,true);
$criteria->compare('price_min',$this->price_min,true);
$criteria->compare('price_max',$this->price_max,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 Monitoring the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
}
Answer the question
In order to leave comments, you need to log in
1. Get the list of models
2. Display the table with fields in the view, as the key items[$modelId]['fieldName'] -> items[12][price_min]
3. In the save action:
3.1. Find all model id's that showed array_keys($_POST['items'])
3.2. Finding all models
3.3. Looping through an array/collection with models
3.4. Using the key, we find the corresponding data for updating $_POST['items'][$model->id]
3.5. Update and save the model
//
the more you show the table, the greater will be the load of n-requests update, where n is the number of items. Perhaps it's easier to put everything on Ajax. But here it is a matter of optimizing everything. Since I don’t know how to update in bulk
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question