how to add live updating charts in yii with highchart - javascript

Am using Yii and Activehighcharts to show charts.
http://www.yiiframework.com/extension/activehighcharts
controller is as follows
public function actionChartView(){
$dataProvider=new CActiveDataProvider('ChartData',array(
'criteria'=>array(
'condition'=>'dID=2',
'order'=>'time ASC',
),
'pagination'=>array(
'pageSize'=>50,
),
)
);
$p=$dataProvider->pagination;
$p->setItemCount($dataProvider->getTotalItemCount());
$p->currentPage=$p->pageCount-1;
if(isset($_GET['json']) && $_GET['json'] == 1){
$count = ChartData::model()->count();
for($i=1; $i<=$count; $i++){
$data = ChartData::model()->findByPk($i);
$data->data += rand(-10,10);
$data->save();
}
echo CJSON::encode($dataProvider->getData());
}
else{
$this->render('ChartView',array('dataProvider'=>$dataProvider,));
}
}
View as
$this->Widget('ext.ActiveHighcharts.HighchartsWidget', array(
'dataProvider'=>$dataProvider,
'template'=>'{items}',
'id'=>'Temperature',
'options'=> array(
'title'=>array(
'text'=>'Temperature'
),
'chart'=>array(
"zoomType"=>'x',
),
'xAxis'=>array(
'title' => array('text' => 'Time',),
'categories' => 'time',
'labels' => array(
'rotation' => -90,
'y' => 20,
),
),
'yAxis'=>array(
'title' => array('text' => 'DegC'),
),
'series'=>array(
array(
'type'=>'areaspline',
'name'=>'Temperature', //title of data
'dataResource'=>'data', //data resource according to datebase column
)
),
)
));
i need to update the chart in every 2 minutes with ajax.
also i need to get old data.
how to handle these scenarios.

in your ajax call success call back update the data in the chart using the api methods provided in highcharts documentation.
please refer this link it will help you to find a good solution.

Ok. To best answer your question i will try to clear things as much as possible.
First you need to create a view (a php file that will contain your highchart code)
Second you need to edit your Controller (let's assume siteController) and create an action to call the view you've just create. Inside that action you will need to connect and query the database.
See the below sample code:
siteController action:
public function actionAtencionesMensuales() {
$sql = Yii::app()->db->createCommand('
SELECT DISTINCT MONTH(hora) as mes, count(*) as total
FROM visitas
WHERE YEAR(hora)=YEAR(CURDATE())
GROUP BY MONTH(hora)')->queryAll();
$mes = array();
$total = array();
for ($i = 0; $i < sizeof($sql); $i++) {
$mes[] = $sql[$i]["mes"];
$total[] = (int) $sql[$i]["total"];
}
$this->render('my_view', array('mes' => $mes, 'total' => $total));
}
}
In the View:
<?php
$this->Widget('ext.highcharts.HighchartsWidget', array(
'options' => array(
'exporting' => array('enabled' => true),
'title' => array('text' => 'Mes'),
'theme' => 'grid',
'rangeSelector' => array('selected' => 1),
'xAxis' => array(
'categories' => $mes
),
'yAxis' => array(
'title' => array('text' => 'Cantidad')
),
'series' => array(
array('name' => 'Total', 'data' => $total = array_map('intVal', $total)),
)
)
));
?>
Within the series of the chart, it's better to use when calling the variable:
$total = array_map('intVal', $total)
Instead of just:
$total
Good luck :)

Related

List all posts in custom post type by taxonomy not working

I am trying to get a list of all the posts in custom post type by taxonomy, I am stuck 3 days at this code, now i study with my father and he gave me a hint why my code is'nt working he a said i have too many args i will show you the code i hope anyone can help me understand why its not working and maybe if you really kind a explanation of the code in english
print_r(Array(
"1"=>"first",
"2"=>"second"
));
// just try to remove args that you don't need
//actually you need only one
$args = array(
'tax_query' => array(
'taxonomy' => 'your-custom-taxonomy',
'field' => 'slug',
'terms' => array( 'your-term' )
),
'post_type' => 'your-post-type'
);
$loop = new WP_Query($args);
if($loop->have_posts()) {
$term = $wp_query->queried_object;
while($loop->have_posts()) : $loop->the_post();
//Output what you want
echo '<li>'.get_the_title().'</li>';
endwhile;
}
So you have a custom post type called your-post-type
and you have a custom taxonomy called your-custom-taxonomy and you
want to get all the posts with a taxonomy term set called your-term.
You are doing it the right way with setting your arguments.
Notice: If you want to get all the posts of a custom post type, you do not need the whole 'tax_query' part of code.
I added some comments to describe what the code is doing:
$args = array( // define your arguments for query
'post_type' => 'your-post-type', // standard post type is 'post', you use a custom one
'tax_query' => array( // you check for taxonomy field values
array(
'taxonomy' => 'your-custom-taxonomy', // standard is 'category' you use a custom one
'field' => 'slug', // you want to get the terms by its slug (could also use id)
'terms' => 'your-term', // this is the taxonomy term slug the post has set
),
),
);
$loop = new WP_Query( $args ); // get post objects
// The Loop
if ( $loop ->have_posts() ) { // check if you received post objects
echo "<ul>"; // open unordered list
while ( $loop ->have_posts() ) { // loop through post objects
$loop ->the_post();
echo '<li>'.get_the_title().'</li>'; // list items
}
echo "</ul>"; // close unordered list
/* Restore original Post Data */
wp_reset_postdata(); // reset to avoid conflicts
} else {
// no posts found
}
Hope this helps!
EDIT: If you do not know how to use WP_Query
This code will get your wordpress posts ordered by their titles and output title and content. Put this inside a template file of your theme (learn something about template files: https://developer.wordpress.org/themes/basics/template-hierarchy/).
<?php
$args = array(
'post_type' => 'post',
'posts_per_page' => -1, // limit the number of posts if you like to
'orderby' => 'title',
'order' => 'ASC'
);
$custom_query = new WP_Query($args);
if ($custom_query->have_posts()) : while($custom_query->have_posts()) : $custom_query->the_post(); ?>
<h1><?php the_title(); ?></h1>
<?php the_content();?>
<?php endwhile; else : ?>
<p>No posts</p>
<?php endif; wp_reset_postdata(); ?>
You said you want to use a custom post type and do a taxonomy query. So you can adjust this with changing the arguments in $args.

Automatically move Wordpress post from one page to another after date has passed

I'm designing a website for a local performing arts venue, and I would like to add some code so that specific event posts on the "Events" page will automatically be moved from "Events" to a different "Past Performances" page after the date of the event has passed. I've looked around for any existing solution to this query and haven't yet found one.
Create a child theme or add page-events.php and page-past-performances.php, you may copy/paste your current theme page.php code.
Here you may choose 2 options:
Create a special loop for each template. For page-events.php:
<?php
$today = getdate();
$args = array('date_query' => array(
array(
'after' => array(
'year' => $today['year'],
'month' => $today['mon'],
'day' => $today['mday'],
),
'inclusive' => true
)
));
$query = WP_Query($args);
//Here goes the loop
For page-past-performances.php:
<?php
$today = getdate();
$args = array('date_query' => array(
array(
'before' => array(
'year' => $today['year'],
'month' => $today['mon'],
'day' => $today['mday'],
),
inclusive => false
)
));
$query = WP_Query($args);
//Here goes the loop
The second option uses the action hook pre_get_posts, it could look something like this (inside your functions.php file):
<?php
add_action('pre_get_posts', 'date_filter');
function date_filter($query) {
if($query->pagename == 'events') {
$query->set('date_query', [[
'after' => //same as above
'inclusive' => true
]]);
}
if($query->pagename == 'past-performances') {
$query->set('date_query', [[
'before' => //same as above
'inclusive' => false
]]);
}
}
?>

How to reset the page, go back to first page on wordpress ( wp_query,paginate_links)?

I use the follow code to handle WordPress pagination. For instance, if the user goes to page 9, My code will echo this URL
'http://jjh.com/Cute/page/9/?post_per_page=60'.
My problem is this:
can I reset the page to 1 whenever I change the post_per_page number?
I allow the user to change this parameter, and I want to reset to the top when they use it.
<?php
//I cut some unnecessary code
// I have a select dropdown to select post_per_page
$arg = array(
'post_type' => 'post',
'posts_per_page' => $post_per_page,
'cat' => $page_cat,
'paged' => $paged,
'offset' => $offset,
'prev_text' => __('«'),
'next_text' => __('»'),
'mid_size' => 2
);
$wp_query = new WP_Query($arg);
echo paginate_links( $arg );
?>
Try this code:
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$post_type = 'post';
$args=array(
'post_typr' => $post_type,
'cat' =>3,
'posts_per_page' => 6,
'paged' => $paged,
'orderby' => 'title',
'order' => 'asc'
);
$my_query = null;
$my_query = new WP_Query($args);
After adding this code use while query <?php if ($my_query->have_posts() ) :
while ($my_query->have_posts()) : $my_query->the_post(); ?>
After while query end tag use <?php
$big = 999999999; // need an unlikely integer
echo paginate_links( array(
'base' => str_replace( $big, '%#%', get_pagenum_link( $big ) ),
'format' => '?paged=%#%',
'current' => max( 1, get_query_var('paged') ),
'total' => $my_query->max_num_pages
) );
?>
And then close if statement. <?php endif; wp_reset_query();?>

wordpress custom query - orderby title will not work

I am having a problem getting a custom query to alphabetize. It keeps defaulting to displaying in the order of the date it was posted. Below is my php function.
function json_info2() {
// The $_REQUEST contains all the data sent via ajax
if ( isset($_REQUEST) ) {
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
// get values for all three drop-down menus
$status = $_REQUEST['status'];
$industry = $_REQUEST['services'];
$state = $_REQUEST['state'];
// array of values for each of the three drop-downs
$statusAll = array('complete','incomplete');
$industryAll = array('mining','textile','machinery');
$statesAll = array('SC','TX','WA');
// set $statusArray dependent on whether or not "all" is selected in the dropdown menu
if($status == "all") {
$statusArray = array( 'key' => 'status', 'value' => $statusAll, 'compare' => 'IN');
} else {
$statusArray = array( 'key' => 'status', 'value' => $status, 'compare' => '=');
}
if($industry == "all") {
$industryArray = array( 'key' => 'industry', 'value' => $industryAll, 'compare' => 'IN');
} else {
$industryArray = array( 'key' => 'industry', 'value' => $industry, 'compare' => '=');
}
if($state == "all") {
$stateArray = array( 'key' => 'state', 'value' => $statesAll, 'compare' => 'IN');
} else {
$stateArray = array( 'key' => 'state', 'value' => $state, 'compare' => '=');
}
$pages = array(
'post_type' => 'page',
'orderby' => 'title',
'order' => 'ASC',
'paged' => $paged,
'posts_per_page' => 5,
'meta_query' => array(
'relation' => 'AND',
$statusArray,
$industryArray,
$stateArray,
array(
'key' => '_wp_page_template',
'value' => 'template-individual-project.php',
'compare' => '='
)
)
);
// query results by page template
$my_query = new WP_Query($pages);
if($my_query->have_posts()) :
while($my_query->have_posts()) :
$my_query->the_post();
<li>
<?php the_title(); ?>
</li>
<?php
endwhile;endif;
wp_reset_query();
} // end of isset
?>
<?php
die();
}
add_action( 'wp_ajax_json_info2', 'json_info2' );
add_action( 'wp_ajax_nopriv_json_info2', 'json_info2' );
?>
This above function is called by the ajax function that follows:
function do_ajax() {
// Get values from all three dropdown menus
var state = $('#states').val();
var markets = $('#markets').val();
var services = $('#services').val();
$.ajax({
url: ajaxurl,
data: {
'action' : 'json_info2',
'state' : state,
'status' : markets,
'services' : services
},
success:function(moredata) {
// This outputs the result of the ajax request
$('#project-list').html( moredata );
$('#project-list').fadeIn();
}/*,
error: function(errorThrown){
var errorMsg = "No results match your criteria";
$('#project-list').html(errorMsg);
}*/
}); // end of ajax call
} // end of function do_ajax
Is there something simple that I'm missing here? I have a similar custom query on the page when it loads (although that initial load query doesn't have the select menu values as args), and they display in alphabetical order just fine. It's only after the ajax call to filter the list that they are no longer in order.
I have found the issue after googling the problem for quite a while. I read that some of the people who were having this problem found that their theme was using a plugin called Post Types Order. It overrides the ability to set the orderby arg.
I looked at the plugins, and sure enough, Post Types Order was there. Everything I read said that the problem could be solved by unchecking "auto sort" in the settings for the plugin. However, I did that, and orderby still didn't work. I had to completely deactivate the plugin to get orderby title to work.

yii cgridview update depending on dropdownlist

I'm newbie with Yii.
I have a CGridview with a cutom dataprovider which takes a parameter $select:
$this->widget('zii.widgets.grid.CGridView', array(
'id' => 'beneficiary-grid',
'dataProvider' => $model->searchForVoucherAssignment($select),
'filter' => $model,
'columns' => array(
'id',
'registration_code',
'ar_name',
'en_name',
'family_member',
'main_income_source',
'combine_household',
array( 'class'=>'CCheckBoxColumn', 'value'=>'$data->id', 'selectableRows'=> '2', 'header' => 'check',
),
),
));
That parameter $select takes its values from dropdownlist:
$data = CHtml::listData(Distribution::model()->findAll(array("condition"=>"status_id = 2")), 'id', 'code');
$select = key($data);
echo CHtml::dropDownList(
'distribution_id',
$select, // selected item from the $data
$data,
array(
)
);
So I defined a script to update the CGridview depending on the value of dropdownlist
Yii::app()->clientScript->registerScript('sel_status', "
$('#selStatus').change(function() {
$.fn.yiiGridView.update('beneficiary-grid', {
data: $(this).serialize()
});
return false;
});
");
My model:
public function searchForVoucherAssignment ($distribution_id = 0) {
$criteria = new CDbCriteria;
if ($distribution_id != 0) {
$criteria->condition = "Custom Query...!!";
}
$criteria->compare('id', $this->id);
//Custom Criteria
return new CActiveDataProvider($this, array(
'criteria' => $criteria,
'pagination' => array(
'pageSize' => 20,
),
));
}
The problem is that the CGridview isn't changing where a value of the dropdownlist changed...
I think you have selected the wrong Id for the change event. The Id should be
$('#distribution_id').change(function() {

Categories

Resources