2

I have a grid view with a condition "upload_date = today", but when I search for other dates it is not filtering the grid. Here is my model:

public function search()
{
    // Warning: Please modify the following code to remove attributes that
    // should not be searched.
    $date=date('Y-m-d');
    $criteria=new CDbCriteria(array('order'=>'upload_date ASC'));
    $criteria->condition = "upload_date='$date' ";
     if(isset($_GET['upload_date']))
           {
           $criteria->addCondition('upload_date = :upload_date','AND'); 
          $criteria->params[':upload_date'] = $this->upload_date;
             }

    $criteria->compare('book_id',$this->book_id);
    $criteria->compare('date_received',$this->date_received,true);
    $criteria->compare('batch',$this->batch,true);
    $criteria->compare('isbn_no',$this->isbn_no,true);
    $criteria->compare('book_title',$this->book_title,true);
    $criteria->compare('auther_name',$this->auther_name,true);
    $criteria->compare('upload_date',$this->upload_date,true);

    return new CActiveDataProvider($this, array(
        'criteria'=>$criteria,
        'pagination'=>array(
        'pageSize'=>50
        ),

    ));
}

I am trying to use both condition and addcondition in same search. What did I do wrong in the model above?

Kai
  • 38,985
  • 14
  • 88
  • 103
jayanthan
  • 371
  • 2
  • 10
  • 20

1 Answers1

6

Try this:

public function search()
{
 $criteria=new CDbCriteria(array('order'=>'upload_date ASC'));

 if(isset($_GET['ModelName']['upload_date']))
 {
  $criteria->compare('upload_date',$this->upload_date,true);
  // $criteria->addCondition('upload_date = :upload_date');
  // $criteria->params[':upload_date'] = $this->upload_date;
 }
 else 
 {
  $date=date('Y-m-d');
  $criteria->condition = "upload_date='$date' "; 
 }
  $criteria->compare('book_id',$this->book_id);
  $criteria->compare('date_received',$this->date_received,true);
  $criteria->compare('batch',$this->batch,true);
  $criteria->compare('isbn_no',$this->isbn_no,true);
  $criteria->compare('book_title',$this->book_title,true);
  $criteria->compare('auther_name',$this->auther_name,true);
  $criteria->compare('upload_date',$this->upload_date,true);

  return new CActiveDataProvider($this, array(
     'criteria'=>$criteria,
     'pagination'=>array(
     'pageSize'=>50
     ), 

 ));
}

You don't need addCondition, specially because you are adding a condition to the same column.

Edit:
In your main initial condition you have already set upload_date = $date, now if you add condition to it, say $_GET['ModelName']['upload_date'] provided by the user in the filter, your actual db query will become something like select * from tbl_name where upload_date = 'xxx' and upload_date = 'yyy' , here xxx=$date you gave, and yyy=date provided by user. Now if xxx != yyy, how will the query return any value? It is not possible.

Hope you got this explanation.

bool.dev
  • 17,508
  • 5
  • 69
  • 93