Yii: searching for a date period - yii

I've a table with 2 mysql DATE field 'validFrom' and 'validTo'.
I need to allow user to search for a period beetween validFrom and validTo (included)
search using
validFrom >= searched validFrom
and
validTo <= searched validTo
What must I change ? the search() ? .
The Gii created code tell me this (i think it's a 'LIKE %string%' search )
$criteria->compare('validFromDate',$this->validFromDate,true);
$criteria->compare('validToDate',$this->validToDate,true);

$criteria->addBetweenCondition('colName', $this->validFrom, $this->validTo);

public function search() {
// Warning: Please modify the following code to remove attributes that
// should not be searched.
$criteria = new CDbCriteria;
$criteria->with = array('user');
$criteria->compare('nota_id', $this->nota_id, true);
$criteria->compare('user.nume', $this->filter_nume, true);
$criteria->compare('persoana1', $this->persoana1, true);
$criteria->compare('persoana2', $this->persoana2, true);
$d = $this->getFilterDateRange($this->data_discutie);
if (!empty($d[0]) && !empty($d[1])) {
// between condition
$criteria->addBetweenCondition('data_discutie', $d[0], $d[1]);
} else if (!empty($d[0])) {
$criteria->compare('data_discutie', '>=' . $d[0]);
} else if (!empty($d[1])) {
$criteria->compare('data_discutie', '<=' . $d[1]);
}
$d = null;
//echo $this->urmatoarea_discutie;
$d = $this->getFilterDateRange($this->urmatoarea_discutie);
//print_R($d);
if (!empty($d[0]) && !empty($d[1])) {
// between condition
$criteria->addBetweenCondition('urmatoarea_discutie', $d[0], $d[1]);
} else if (!empty($d[0])) {
$criteria->compare('urmatoarea_discutie', '>=' . $d[0]);
} else if (!empty($d[1])) {
$criteria->compare('urmatoarea_discutie', '<=' . $d[1]);
}
return new CActiveDataProvider($this, array(
'criteria' => $criteria,
'pagination' => array(
'pageSize' => '15',
),
'sort' => array(
'defaultOrder' => 'coalesce(nullif(t.urmatoarea_discutie, ""), \'zzzzzz\') ASC, t.data_discutie ASC',
'attributes' => array(
'urmatoarea_discutie',
'data_discutie',
'persoana2',
'persoana1',
'filter_nume' => array(
'asc' => 'user.nume asc',
'desc' => 'user.nume desc'
),
),
),
));
}
protected function getFilterDateRange($key) {
$ret = array(&$from, &$to);
switch ($key) {
case '-1':
// past
$to = strtotime('next hour');
break;
case '1':
// future
$from = strtotime('last hour');
break;
case '-7':
$from = strtotime('-1 week last monday midnight');
$to = strtotime('last sunday midnight');
break;
case '7':
$from = strtotime('last monday');
$to = strtotime('next sunday midnight');
break;
}
return $ret;
}

Depending on what you want to do, the search() in the model is not necessarily be the place you want to be looking. Here is a standard Yii query:
$model = WhateverModel::model()->findAll(array(
"condition" => "'.date('Y-m-d H:i:s' BETWEEN validRrom AND validTo).'",
));
You will have to give a bit more detail if you more detailed help :)

Related

Codeigniter post data from declared variable

function index_post() {
$sql = "SELECT id_so FROM so_detail ORDER BY id_so DESC LIMIT 1";
$last_id2 = $this->db->query($sql)->result();
foreach ($last_id2 as $row) {
$last_id = $row->id_so;
}
//echo $last_id;
$data = array(
'id_so' => $this->post($last_id),
'id_product' => $this->post('id_product'),
'harga' => $this->post('harga'),
'harga_dasar'=> $this->post('harga'),
'modal' => $this->post('modal'),
'pajak' => $this->post('pajak'),
'qty' => $this->post('qty'),
'keterangan' => $this->post('keterangan'),
'create_user'=> $this->post('create_user'),
'create_time'=> $this->post('create_time'),
'update_user'=> $this->post('create_user'),
'update_time'=> $this->post('create_time'));
$insert = $this->db->insert('so_detail', $data);
if ($insert) {
$this->response($data, 200);
} else {
$this->response(array('status' => 'fail', 502));
}
}
i got a problem that the posted id_so is "null". when i echo $last_id it show correct id ex: 120. but when i call it to $this->post($last_id), it just be null..
How to post id_so with a string that already declared before ($last_id) ??
there are many array in $last_id2 variable.data will insert multiple time based on your last_id2.try this:
foreach ($last_id2 as $row) {
$data = array(
'id_so' =>$row->id_so,
'id_product' => $this->post('id_product'),
'harga' => $this->post('harga'),
'harga_dasar'=> $this->post('harga'),
'modal' => $this->post('modal'),
'pajak' => $this->post('pajak'),
'qty' => $this->post('qty'),
'keterangan' => $this->post('keterangan'),
'create_user'=> $this->post('create_user'),
'create_time'=> $this->post('create_time'),
'update_user'=> $this->post('create_user'),
'update_time'=> $this->post('create_time'));
}
$this->db->insert_batch('so_detail',$data);

What is post type of Replies in Wordpress BBPress?

I did count active in 7 days topics of my Wordpress page. But It counts only Active (replied) topics not actual replies- I need more dynamic number to lure people using forum.
function count_new_forum_posts() {
$today = date("Y-m-d");
$date2 = date("Y-m-d", strtotime($today . "-7 Day"));
$args = array(
'post_type' => 'topic',
'meta_query' => array(
array(
'key' => '_bbp_last_active_time',
'value' => $date2,
'type' => 'DATE',
'compare' => '>='
),
)
);
$posts_query = new WP_Query($args);
$the_count = $posts_query->post_count;
return $the_count;
}
add_filter('wp_nav_menu_items', 'new_forums_notice_to_menu', 10, 2);
function new_forums_notice_to_menu($items, $args) {
if(count_new_forum_posts() > 0){
if( $args->theme_location == 'primary' )
$items .= '<li><font color="red">Šios savaitės naujos žinutės forume: <span>'.count_new_forum_posts().'</span></font></li>';
return $items;
}else{
if( $args->theme_location == 'primary' )
$items .= '<li><font color="gray">Šią savaitę forume dar niekas nepasisakė</span></font></li>';
return $items;
}
}
When i try to change post_type to 'reply' or 'replies' It counts to 0.

Creating a PDF document from a filtered CGridView - Yii

I am trying to create a PDF from a filtered CGridView. The value will be passed via dropdown in Advanced search but the problem is that i am unable to filter the search by my pdf function.
Controller
public function actionPrint() {
$mPDF1 = Yii::app()->ePdf->mpdf('ar','A4','14','dejavusanscondensed');
$model=new Country('search');
$model->center_id = 1;// This value will be passed from dropdown
//and i want the report to be made on this
$model->unsetAttributes();
if(isset($_GET['Country']))
$model->attributes=$_GET['Country'];
$html = '';
$html .= $this->renderPartial('candidates', array('model'=>$model, 'enablePagination' => false),true);
$mPDF1->WriteHTML($html, false);
$mPDF1->Output('list.pdf','D');
}
View
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'country-grid',
'dataProvider'=>$model->search($enablePagination),
'summaryText' => '',
// 'enablePagination' => false,
'filter'=>$model,
'columns'=>array(
'name',
array(
'header'=>' Total Registered Candidates',
'value'=>'$data->itemsTotal',
),
),
));
echo CHtml::link(
'Save as PDF',
Yii::app()->createUrl('country/print'),
array('class'=>'btnPrint btn btn-danger','target'=>'_blank'));
Model
public function search($enablePagination = true)
{
$criteria->together= true;
$criteria->with=array('center');
$criteria->compare('center.name', $this->center_id, true);
..........
if ($enablePagination)
{
$pagination = array(
'pageSize' => 30,
);
}
else
{
$pagination = false;
}
return new CActiveDataProvider($model, array(
'criteria' => $criteria,
'pagination' => $pagination,
));
}
Since center_id is a foreign key the line
$criteria->compare('center.name', $this->center_id, true);
should read
$criteria->compare('center_id', $this->center_id);
You could also do the following but this adds a condition on the joined table and could lead to slower queries.
$criteria->compare('center.id', $this->center_id);

Yii CJuiAutoComplete widget: event of empty response message

If the response does not contain data about the city, I want to see the output message. Also i want to change css of text in textfield when I get an empty response.
I have:
View:
$this->widget('zii.widgets.jui.CJuiAutoComplete', array(
'name'=>'city_id',
'value'=>'',
'source'=>CController::createUrl('/PromouterCity/autoComplete'),
'options'=>array(
'showAnim'=>'fold',
'minLength'=>'0',
'select'=>'js:function( event, ui ) {
$("#city_id").val( ui.item.name );
$("#selectedvalue").val( ui.item.id);
return false;
}',
),
'placeholder' => "Search...",
),
));
Controller:
public function actionAutoComplete(){
$match=$_GET['term'];
if(!empty($match)){
$match = addcslashes($match, '%_');
$q = new CDbCriteria( array(
'condition' => "name LIKE :match",
'params' => array(':match' => "$match%")
));
$query = City::model()->findAll($q);
}else{
$query=array(
'0'=>array(
'id'=>'1',
'name'=>'London',
)
);
}
$list = array();
foreach($query as $q){
$data['label']=$q['name'];
$data['id']= $q['id'];
$data['name']= $q['name'];
$list[]= $data;
unset($data);
}
echo CJSON::encode($list);
Yii::app()->end();
}
Decision:
'response'=> 'js:function( event, ui ) {
if (ui.content.length === 0) {
$("#empty-message").text("your message");
} else {
$("#empty-message").empty();
}
}',

cakephp 2.X override table prefix dynamically on join action

I a cakephp setup to manage multiple web-sites in which they a number of common models, with the table prefix 'main_'. And there's common model Fbuser is using a table 'main_fb_users'
And now, I have a web-site, and its table prefix is 'myweb_', and I have a model, Mymodel, which have to be left-join with Fbuser.
$this->Mymodel->find('all', array(
'joins' => array(
'table' => 'main_fb_users',
'alias' => 'Fbuser',
'type' => 'LEFT',
'conditions' => array('Mymodel.field01 = Fbuser.field02')
));
and here's the error message I have got
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'dbserver.myweb_main_fb_users' doesn't exist
obviously, it's due to the different in the table prefix, and I can't change the default table prefix set in the database.php.
so how can I override the table prefix inside the join query?
Pass the model object instead of the table name as a string:
$this->Mymodel->find('all', array(
'joins' => array(
'table' => $this->Mymodel->FbUser,
'alias' => 'Fbuser',
'type' => 'LEFT',
'conditions' => array('Mymodel.field01 = Fbuser.field02')
));
Seems to work for me.
Hacked Method (for version 2.x)
Go to - /lib/Cake/Model/Datasource/DboSource.php line #942
Modify the function fullTableName as below:
public function fullTableName($model, $quote = true, $schema = true, $prefix = true) {
if (is_object($model)) {
$schemaName = $model->schemaName;
$table = $model->tablePrefix . $model->table;
} elseif (!empty($this->config['prefix']) && strpos($model, $this->config['prefix']) !== 0) {
$table = (((!empty($prefix) && $prefix !== true)?$prefix:(($prefix === false)?'':$this->config['prefix'] ))). strval($model);
} else {
$table = strval($model);
}
if ($schema && !isset($schemaName)) {
$schemaName = $this->getSchemaName();
}
if ($quote) {
if ($schema && !empty($schemaName)) {
if (strstr($table, '.') === false) {
return $this->name($schemaName) . '.' . $this->name($table);
}
}
return $this->name($table);
}
if ($schema && !empty($schemaName)) {
if (strstr($table, '.') === false) {
return $schemaName . '.' . $table;
}
}
return $table;
}
Now go to line #1881 on same page and modify the function buildJoinStatement as:
public function buildJoinStatement($join) {
$data = array_merge(array(
'type' => null,
'alias' => null,
'table' => 'join_table',
'conditions' => '',
), $join);
if (!empty($data['alias'])) {
$data['alias'] = $this->alias . $this->name($data['alias']);
}
if (!empty($data['conditions'])) {
$data['conditions'] = trim($this->conditions($data['conditions'], true, false));
}
if (!empty($data['table']) && (!is_string($data['table']) || strpos($data['table'], '(') !== 0)) {
$data['table'] = (isset($data['prefix']))?$this->fullTableName($data['table'],true,true,$data['prefix']):$this->fullTableName($data['table']);
}
return $this->renderJoinStatement($data);
}
thats it...
now if you provide a prefix element in joins array then it will use the same prefix for that table.
Example
'joins'=>array(
array(
'table'=>'GDN_Comment',
'type'=>'LEFT',
'prefix'=>false,
'alias'=>'Comment',
'conditions'=>array('MyPost.DiscussionID = 2'),
),
),
Then it will use "GDN_Comment as Comment" in sql query
OR
'joins'=>array(
array(
'table'=>'GDN_Comment',
'type'=>'LEFT',
'prefix'=>'ds_',
'alias'=>'Comment',
'conditions'=>array('MyPost.DiscussionID = 2'),
),
),
Then it will use "ds_GDN_Comment as Comment" in sql query
You can adjust the table prefix on the fly in the controller:
$this->loadModel('MainFbUser');
$this->MainFbUser->tablePrefix = '';
In the documentation:
http://book.cakephp.org/2.0/en/models/model-attributes.html#tableprefix