Search code examples
yiiwidgetwhere-clausecgridviewdataprovider

Yii Widgets CGridView show data


I have 2 tables in my DB: t_product and t_user.

t_user

'***************************************************************************'

'* cod_arm * descrição * username * password * salt * tipo *'

'***************************************************************************'

'* 000 * 000 - ADMIN * admin * 123 * asdfgh * A *'

'* 001 * 001 - MEDICINA 1 * P01 * 123 * asdf * U *'

'* 021 * 021 - UROLOGIA * P21 * 123 * asdfg * U *'

****************************************************************************'

t_product

'*********************************************************************************************'

'* id_prod * cod_art * designacao * unidade * data_validade * cod_loc *'

'*********************************************************************************************'

'* 1 * 210110300 * ADESIVO COMUM (...) * ROL * 2014-11-30 * P010101 *'

'* 2 * 210110320 * ADESIVO COMUM (...) * ROL * NULL * P01 *'

'* 3 * 210110302 * ADESIVO COMUM (...) * ROL * 2016-12-30 * P210110 *'

'* 4 * 210110301 * ADESIVO COMUM (...) * ROL * 2014-11-30 * P010101 *'

'* 1 * 210110300 * ADESIVO COMUM (...) * ROL * 2014-11-30 * P01EXT *'

'* 1 * 210110300 * ADESIVO COMUM (...) * ROL * 2014-11-30 * P210101 *'

'***********************************************************************************************'

I want, when user click in "Manage Product". Table show all products where cod_loc like 'username%'.

exemp: In this case the user is "P01". In this page-"Manage Produtos" I want show all products where cod_loc beginning with "P01".

I try whith dataProvider. In model->Product .. But i cannot show what i want! I can show all products where cod_loc are exactly match with username (ex."P01") and I can show all products where cod_loc have "P","0" and "1", and this case are almost all produts.


Well, in my model Product i have that code:

<?php

/**
 * This is the model class for table "produto".
 *
 * The followings are the available columns in table 'produto':
 * @property integer $idProduto
 * @property integer $cod_art
 * @property string $designacao
 * @property string $unidades
 * @property string $data_validade
 * @property string $cod_loc
 * @property string $username
 *
 * The followings are the available model relations:
 * @property User $username0
 */
class Produto extends CActiveRecord
{
	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'produto';
	}

	/**
	 * @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('cod_art, designacao, unidades, cod_loc', 'required'),
			array('cod_art', 'numerical', 'integerOnly'=>true),
			array('designacao', 'length', 'max'=>128),
			array('unidades', 'length', 'max'=>6),
			array('cod_loc', 'length', 'max'=>12),
			array('username', 'length', 'max'=>3),
			array('data_validade', 'safe'),
			// The following rule is used by search().
			// @todo Please remove those attributes that should not be searched.
			array('idProduto, cod_art, designacao, unidades, data_validade, cod_loc, username', '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(
			'username0' => array(self::BELONGS_TO, 'User', 'username'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			//'idProduto' => 'Id Produto',
			'cod_art' => 'Cod Art',
			'designacao' => 'Designacao',
			'unidades' => 'Unidades',
			'data_validade' => 'Data Validade',
			'cod_loc' => 'Cod Loc',
			//'username' => 'Username',
		);
	}

	/**
	 * 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('cod_arm',$this->cod_arm);
		$criteria->compare('descricao',$this->descricao,true);
		$criteria->compare('username',$this->username,true);
		$criteria->compare('password',$this->password,true);
		$criteria->compare('salt',$this->salt,true);
		$criteria->compare('tipo',$this->tipo,true);*/
                $username = Yii::app()->user->name;
		return new CActiveDataProvider('Produto', array(
                    'criteria'=>array(
                    'condition'=>'cod_loc LIKE :username%',
                    'params' => array(
                        ':username'=>$username
                    )
                ),
            ));
	}

	/**
	 * 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 Produto the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}
}


And in my views>Produto>admin.php I have this code:

<?php
/* @var $this ProdutoController */
/* @var $model Produto */

$this->breadcrumbs=array(
	'Produtos'=>array('index'),
	'Manage',
);

$this->menu=array(
	array('label'=>'List Produto', 'url'=>array('index')),
	array('label'=>'Create Produto', 'url'=>array('create')),
);

Yii::app()->clientScript->registerScript('search', "
$('.search-button').click(function(){
	$('.search-form').toggle();
	return false;
});
$('.search-form form').submit(function(){
	$('#produto-grid').yiiGridView('update', {
		data: $(this).serialize()
	});
	return false;
});
");
?>

<h1>Manage Produtos</h1>

<p>
You may optionally enter a comparison operator (<b>&lt;</b>, <b>&lt;=</b>, <b>&gt;</b>, <b>&gt;=</b>, <b>&lt;&gt;</b>
or <b>=</b>) at the beginning of each of your search values to specify how the comparison should be done.
</p>

<?php echo CHtml::link('Advanced Search','#',array('class'=>'search-button')); ?>
<div class="search-form" style="display:none">
<?php $this->renderPartial('_search',array(
	'model'=>$model,
)); ?>
</div><!-- search-form -->
<?php echo $AP = Yii::app()->User->name; ?>
<?php $this->widget('zii.widgets.grid.CGridView', array(
	'id'=>'produto-grid',
	'dataProvider'=>$model->search(),
	'filter'=>$model,
	'columns'=>array(
		//'idProduto',
		'cod_art',
		'designacao',
		'unidades',
		'data_validade',
		'cod_loc',
		/*
		'username',
		*/
		array(
			'class'=>'CButtonColumn',
		),
	),
)); ?>

In mysql, i can do what i want -> SELECT * FROM produto WHERE cod_loc LIKE 'username%';


Solution

  • Not going deeply in your code an answer may be in this code example:

    $username = 'P01' ;
    Product::model()->findAll('cod_loc LIKE :username', array(
        ':username'=>"{$username}%"
    ));
    

    or in data provider:

    $dataProvider = new CActiveDataProvider('Product', array(
        'criteria'=>array(
            'condition'=>'cod_loc LIKE :username',
            'params' => array(
                ':username'=>"{$username}%"
            )
        ),
    ));
    

    By Product I mean the model class for t_product table.