Yii Framework Forum: Cgridview Filter - Yii Framework Forum

Jump to content

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

Cgridview Filter Rate Topic: -----

#1 User is offline   blanker 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 10
  • Joined: 07-December 13

Posted 27 May 2014 - 12:21 PM

Cześć,

Wiem,ze dużo jest takich topiców, ale żaden nie rozwiązał mojego problemu. Otóż: po wpisaniu w polu wyszukiwania w cgridview zupelnie nic sie nie dzieje, nic nie daje enter. Nie pokazuje sie to "kołeczko", które kreci sie gdy sie laduje cgridview.

Moj model:

public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('title, short, text, date, author, category', 'required'),
			array('author, category', 'numerical', 'integerOnly'=>true),
			array('title, photo', 'length', 'max'=>255),
			// The following rule is used by search().
			// @todo Please remove those attributes that should not be searched.
			array('id, title, short, text, date, author, photo, category, categories.name', 'safe', 'on'=>'search'),
		);
	}


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('title',$this->title,true);
		$criteria->compare('short',$this->short,true);
		$criteria->compare('text',$this->text,true);
		$criteria->compare('date',$this->date,true);
		$criteria->compare('author',$this->author);
		$criteria->compare('photo',$this->photo,true);
		$criteria->compare('category',$this->category);

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


Widok:

<?php 
        $this->widget('zii.widgets.grid.CGridView', array(
    		'dataProvider' => $news->search(),
    		'filter' => $news,
            'itemsCssClass' => 'table table-striped',
            'pagerCssClass'=>'button-group float-right',
            'pager'=>array ('maxButtonCount'=>5,
                'nextPageLabel'=>'<i class="glyph-icon icon-chevron-right"></i>',
                'prevPageLabel'=>'<i class="glyph-icon icon-chevron-left"></i>',
                'lastPageLabel' => '',
                'firstPageLabel' => '',
                'header' => '',
                'cssFile' => Yii::app()->getBaseUrl(true) . '/public/cms/assets/css/pager.css',
            ),
            'summaryText' => '<p class="font-gray-dark">{start} - {end} z {count} rekordów</p>',
    		'columns' => array(
                    'title',
                    array(
    						'name' => 'category',
    						'type' => 'raw',
    						'value' => '$data->categories->name',
    				),
                    array(
    						'name' => 'author',
    						'type' => 'raw',
    						'value' => '$data->fullName()',
    				),
                    array(
    						'name' => 'date',
    						'type' => 'raw',
    						'value' => '$data->date',
    				),

    			array('class'=>'CButtonColumn',
                    'template'=>'{view} {update} {delete}',
                    'buttons'=>array (
                        'view'=>array(
                            'label' => '<i style="font-size: 1.4em;"  title="Zobacz" class="glyph-icon icon-search"></i>',
                            'imageUrl' => false,
                            'options'=>array("target"=>"_blank"),
                        ),
                        'update'=> array(
                            'label' => '<i style="font-size: 1.4em;" title="Edytuj" class="glyph-icon icon-edit"></i>',
                            'imageUrl' => false,
                        ),
                        'delete'=>array(
                            'label' => '<i style="font-size: 1.4em;" title="Usuń" class="glyph-icon icon-trash-o"></i>',
                            'imageUrl' => false,
                        ),
                    ),
                ),
                        
                        
        ),
        ));
    ?>


I Controller:

	public function actionIndex()
	{
        $news = new News;
		$news->unsetAttributes();  // clear any default values
        if(isset($_GET['News']))
        	$news->attributes=$_GET['News'];
		
		$this->render('index', array('news' =>$news));
	}


jquery załączone.

Mimo to nie działa...

Proszę o pomoc.

Pozdrawiam,
B.
0

#2 User is offline   .viktor. 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 88
  • Joined: 25-August 10
  • Location:Sokołów Podlaski, Poland

Posted 28 May 2014 - 12:18 AM

Cześć:
1. Zauważyłem, że masz relację z categories, więc w metodzie search()
powinieneś dadać klauzulę "with":

public function search()
        {

                $criteria=new CDbCriteria;

                $criteria->with = array( 'categories' );// <<< dołączenie relacji

                $criteria->compare('twoje_pole',$this->twoja zmienna);//<<< dołączenie obsługi filtra

                $criteria->compare('id',$this->id);
                $criteria->compare('title',$this->title,true);
                $criteria->compare('short',$this->short,true);
                $criteria->compare('text',$this->text,true);
                $criteria->compare('date',$this->date,true);
                $criteria->compare('author',$this->author);
                $criteria->compare('photo',$this->photo,true);
                $criteria->compare('category',$this->category);// << to jest id category?
                 /*wydaje mi się, że może powstać pewien konfilkt
                   bo w gridview używasz pola category a wartośc
                   categories->name ???
                 */

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


2. Wypadało by wskazać z jakiego scenariusza ma korzystać model:

public function actionIndex()
        {
           $news = new News('search'); //<<< wskazanie scenariusza search
           $news->unsetAttributes();  // clear any default values
           if(isset($_GET['News']))
                   $news->attributes=$_GET['News'];
                
           $this->render('index', array('news' =>$news));
        }

3. Jak nie zadziała po zmianach
- wyłącz ajax w widoku ajaxUpdate=>'false'
- w kontrolerze zrób var_dump i wyświetl pokaż mi tablicę $_GET
- pokaż cały model
0

#3 User is offline   blanker 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 10
  • Joined: 07-December 13

Posted 28 May 2014 - 12:59 PM

Hej,

Dodałem with w search, ale nic to nie dało. Zreszta nawet jesli zostawie samo np title to i tak nie dziala. Nie wiem czy dobrze dołączam obsługę filtra.

Cały model:

<?php

/**
 * This is the model class for table "news".
 *
 * The followings are the available columns in table 'news':
 * @property integer $id
 * @property string $title
 * @property string $short
 * @property string $text
 * @property string $date
 * @property integer $author
 * @property string $photo
 * @property integer $category
 */
class News extends CActiveRecord
{
    
    public $fullName;
	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'news';
	}

	/**
	 * @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('title, short, text, date, author, category', 'required'),
			array('author, category', 'numerical', 'integerOnly'=>true),
			array('title, photo', 'length', 'max'=>255),
			// The following rule is used by search().
			// @todo Please remove those attributes that should not be searched.
			array('id, title, short, text, date, author, photo, category, categories.name', '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(
            'users' => array(self::BELONGS_TO, 'Users', 'author'),
            'categories' => array(self::BELONGS_TO, 'Categories', 'category'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'title' => 'Tytuł',
			'short' => 'Treść skrócona',
			'text' => 'Treść w całości',
			'date' => 'Data dodania',
			'author' => 'Autor',
			'photo' => 'Miniatura',
			'category' => 'Kategoria',
		);
	}

	/**
	 * 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->with = array( 'categories' );

        $criteria->compare('categories.name',$this->categories);

		$criteria->compare('id',$this->id);
		$criteria->compare('title',$this->title,true);
		$criteria->compare('short',$this->short,true);
		$criteria->compare('text',$this->text,true);
		$criteria->compare('date',$this->date,true);
		$criteria->compare('author',$this->author);
		$criteria->compare('photo',$this->photo,true);
		$criteria->compare('category',$this->category);

		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 News the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}
    
    public function fullName(){
        return $this->users->name.' '.$this->users->surname;;
    }
}




W controllerze dodalem scenarusz search- w sumie nigdy tak nie robilem i dzialalo (choc to moze nie jest dobra praktyka ;) ). W kazdym razie nie dziala dalej.

Tablica GET zwraca tylko

array(1) { ["r"]=> string(15) "adminpanel/news" } 


wpisywanie frazy do wyszukani nic nie daje w tej kwesti- tak jak mowilem filtorwanie jakby sie nie odbywa

Controller:

	public function actionIndex() {
        $news = new News('search');
		$news->unsetAttributes();  // clear any default values
        if(isset($_GET['News']))
        	$news->attributes=$_GET['News'];
            
		$this->render('index', array('news' =>$news));
	}


Dodałem również widoku 'ajaxUpdate' => 'false' i nic to nie dalo

Widok:

<?php 
        $this->widget('zii.widgets.grid.CGridView', array(
    		'dataProvider' => $news->search(),
    		'filter' => $news,
            'ajaxUpdate'=>'false',
            'itemsCssClass' => 'table table-striped',
            'pagerCssClass'=>'button-group float-right',
            'pager'=>array ('maxButtonCount'=>5,
                'nextPageLabel'=>'<i class="glyph-icon icon-chevron-right"></i>',
                'prevPageLabel'=>'<i class="glyph-icon icon-chevron-left"></i>',
                'lastPageLabel' => '',
                'firstPageLabel' => '',
                'header' => '',
                'cssFile' => Yii::app()->getBaseUrl(true) . '/public/cms/assets/css/pager.css',
            ),
            'summaryText' => '<p class="font-gray-dark">{start} - {end} z {count} rekordów</p>',
    		'columns' => array(
                    'title',
                    array(
    						'name' => 'category',
    						'type' => 'raw',
    						'value' => '$data->categories->name',
    				),
                    array(
    						'name' => 'author',
    						'type' => 'raw',
    						'value' => '$data->fullName()',
    				),
                    array(
    						'name' => 'date',
    						'type' => 'raw',
    						'value' => '$data->date',
    				),

    			array('class'=>'CButtonColumn',
                    'template'=>'{view} {update} {delete}',
                    'buttons'=>array (
                        'view'=>array(
                            'label' => '<i style="font-size: 1.4em;"  title="Zobacz" class="glyph-icon icon-search"></i>',
                            'imageUrl' => false,
                            'options'=>array("target"=>"_blank"),
                        ),
                        'update'=> array(
                            'label' => '<i style="font-size: 1.4em;" title="Edytuj" class="glyph-icon icon-edit"></i>',
                            'imageUrl' => false,
                        ),
                        'delete'=>array(
                            'label' => '<i style="font-size: 1.4em;" title="Usuń" class="glyph-icon icon-trash-o"></i>',
                            'imageUrl' => false,
                        ),
                    ),
                ),
                        
                        
        ),
        ));
    ?>


Pozdrawiam,
Blanker
0

#4 User is offline   .viktor. 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 88
  • Joined: 25-August 10
  • Location:Sokołów Podlaski, Poland

Posted 29 May 2014 - 12:31 AM

1. W tablicy $_GET nie ma danych do filtrowania, czy var_dumpa robiłeś przed updateAjax=false ?
2. w modelu dodaj pole public kategorie
3. do rules dla scenariusza search dodaj kategorie
4. w metodzie search() zmień $criteria->compare('categories.name',$this->kategorie);
5. w widoku zmień 'name' => 'category' na 'name' => 'kategorie',
6. teraz podczas filtrowania zrób var_dumpa
7. Dla pewności, czy tabela Categories ma primary key ustawione na id ?
0

#5 User is offline   blanker 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 10
  • Joined: 07-December 13

Posted 30 May 2014 - 01:11 AM

Bez znaczenia kiedy robie var_dumpa- tak jak mówiłem żądanie ajaxowe jakby w ogole nie było wysyłane. Jak klikam na nagłówki kolumn to sortuje się tabela i widze, ze GET sie zmienia. Przy wyszukiwaniu tego nie ma. Nawet jesli usune wszystkie relacje i w widoku zostawie tylko "title" to i tak sie nic nie wyzsukuje. Po protu wpisuje wartosc w pole i nic sie zupelnie nie dzieje.

Czy jest naprzyklad cos co powienienem dolaczyc do szablonu zeby to wyszukiwanie ruszylo?
Moj widok:

    <?php 
        $this->widget('zii.widgets.grid.CGridView', array(
    		'dataProvider' => $news->search(),
    		'filter' => $news,
            'ajaxUpdate'=>'false',
            'itemsCssClass' => 'table table-striped',
            'pagerCssClass'=>'button-group float-right',
            'pager'=>array ('maxButtonCount'=>5,
                'nextPageLabel'=>'<i class="glyph-icon icon-chevron-right"></i>',
                'prevPageLabel'=>'<i class="glyph-icon icon-chevron-left"></i>',
                'lastPageLabel' => '',
                'firstPageLabel' => '',
                'header' => '',
                'cssFile' => Yii::app()->getBaseUrl(true) . '/public/cms/assets/css/pager.css',
            ),
            'summaryText' => '<p class="font-gray-dark">{start} - {end} z {count} rekordów</p>',
    		'columns' => array(
                    'title',
                    array(
    						'name' => 'categoryName',
    						'type' => 'raw',
    						'value' => '$data->categories->name',
    				),
                    array(
    						'name' => 'author',
    						'type' => 'raw',
    						'value' => '$data->fullName()',
    				),
                    array(
    						'name' => 'date',
    						'type' => 'raw',
    						'value' => '$data->date',
    				),

    			array('class'=>'CButtonColumn',
                    'template'=>'{view} {update} {delete}',
                    'buttons'=>array (
                        'view'=>array(
                            'label' => '<i style="font-size: 1.4em;"  title="Zobacz" class="glyph-icon icon-search"></i>',
                            'imageUrl' => false,
                            'options'=>array("target"=>"_blank"),
                        ),
                        'update'=> array(
                            'label' => '<i style="font-size: 1.4em;" title="Edytuj" class="glyph-icon icon-edit"></i>',
                            'imageUrl' => false,
                        ),
                        'delete'=>array(
                            'label' => '<i style="font-size: 1.4em;" title="Usuń" class="glyph-icon icon-trash-o"></i>',
                            'imageUrl' => false,
                        ),
                    ),
                ),
                        
                        
        ),
        ));
    ?>


Model:

<?php

/**
 * This is the model class for table "news".
 *
 * The followings are the available columns in table 'news':
 * @property integer $id
 * @property string $title
 * @property string $short
 * @property string $text
 * @property string $date
 * @property integer $author
 * @property string $photo
 * @property integer $category
 */
class News extends CActiveRecord
{
    
	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'news';
	}

	/**
	 * @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('title, short, text, date, author, category', 'required'),
			array('author, category', 'numerical', 'integerOnly'=>true),
			array('title, photo', 'length', 'max'=>255),
			// The following rule is used by search().
			// @todo Please remove those attributes that should not be searched.
			array('id, title, short, text, date, author, photo, category, categories.name', '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(
            'users' => array(self::BELONGS_TO, 'Users', 'author'),
            'categories' => array(self::BELONGS_TO, 'Categories', 'category'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'title' => 'Tytuł',
			'short' => 'Treść skrócona',
			'text' => 'Treść w całości',
			'date' => 'Data dodania',
			'author' => 'Autor',
			'photo' => 'Miniatura',
			'category' => 'Kategoria',
		);
	}

	/**
	 * 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 $categoryName;
    
	public function search()
	{
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria=new CDbCriteria;
        
        $criteria->with = array( 'categories' );

        $criteria->compare('categories.name',$this->categoryName);

		$criteria->compare('id',$this->id);
		$criteria->compare('title',$this->title,true);
		$criteria->compare('short',$this->short,true);
		$criteria->compare('text',$this->text,true);
		$criteria->compare('date',$this->date,true);
		$criteria->compare('author',$this->author);
		$criteria->compare('photo',$this->photo,true);
		$criteria->compare('category',$this->category);

		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 News the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}
    
    public function fullName(){
        return $this->users->name.' '.$this->users->surname;;
    }
}




Controller:

	public function actionIndex() {
        $news = new News('search');
		$news->unsetAttributes();  // clear any default values
        if(isset($_GET['News']))
        	$news->attributes=$_GET['News'];
            
		$this->render('index', array('news' =>$news));
	}


Dzieki za proby pomocy niesmialo licze na jeszcze troche :)
Pozdrawiam,
B.
0

#6 User is offline   .viktor. 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 88
  • Joined: 25-August 10
  • Location:Sokołów Podlaski, Poland

Posted 30 May 2014 - 01:39 AM

1. popraw tu:
//źle
 'ajaxUpdate'=>'false'
//dobrze
'ajaxUpdate'=>false,


2.teraz zrób var_dump($_GET) i dodatkowo var_dump($_POST), nie ma siły żeby nigdzie tego nie bylo widać, oczywiście pod warunkiem, że ajax jest na pewno wyłączony.

3. w poprzednim poście opisałem ci resztę zmian, testowałeś/
0

#7 User is offline   blanker 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 10
  • Joined: 07-December 13

Posted 30 May 2014 - 12:09 PM

Poprawione.

Tak, testowalem.

Post zupełnie pusty. Get tak jak wczesniej, chyba, ze przesortuje tabele klikając na nagłówek, wtedy mam:

array(2) { ["r"]=> string(21) "adminpanel/news/index" ["News_sort"]=> string(4) "date" }


Sprawa jest tym bardziej dziwna, ze tak jak mowie po wpisaniu w pole wyszukiwania nic się nie dzieje (a normalnie nawet jak wyszukiwanie w modelu nie działa to kreci się przynajmniej to kołeczku)
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