Inserting a array of php values into a select options via javascript - javascript

I have multiple select elements, and each select form is either a block type or a block content. So in total i have around 10 select elements, 5 of which are block type and 5 are block content. The select options of block content will be determined by what the user select in block type.
I have 3 arrays (property, blogs, message), which have the values needed for block content.
So what i need to do is-
check what the user has selected for block type- which i have done.
Populate the block content with the relevant values- this is where i am having problems.
Here is my javascript code so far
$(".blockTypeWrapper .blockType").change(function() {
var currentBlock = $(this).val();
var blockContent = $(this).parent().siblings('.blockContentWrapper .blockContent');
if (currentBlock == '1') {
var option = document.createElement("option");
var propertyData = <?php echo $properties; ?>;
$.each(propertyData, function() {
options.append(new Option(option.text, option.value));
});
};
if (currentBlock == '2') {
$(this).siblings(".blockContent").addClass("active");
};
if (currentBlock == '3') {
$(this).siblings(".blockContent").addClass("active");
};
});
Ignore the currentBlock == '2' and 3 code, i am just trying to get it working for one first.
If there are any other easier way of achieving this then i'm all ears.
EDIT
echo $this->Form->input('main_block_type',
array(
'options' => array(
1 => 'Property',
2 => 'Blogs',
3 => 'Message'
),
'label' => 'Main Block Type',
'empty' => 'Please Select',
'class' => 'blockType',
'div' => array(
'class' => 'blockTypeWrapper'
)
)
);
echo $this->Form->input('main_block',
array(
'options' => $blogs,
'label' => 'Main Block Content',
'empty' => 'Please Select',
'class' => 'blockContent',
'div' => array(
'class' => 'blockContentWrapper'
)
)
);
Thanks

You can't access Array with echo. You need to access with:
<?php echo json_encode($properties); ?>;
try below code:
if (currentBlock == '1') {
var propertyData = <?php echo json_encode($properties); ?>;
$(".blockContent").empty(); // You can remove all the options by using empty() function.
$.each(propertyData, function (i, item) {
$('.blockContent').append($('<option>', {
value: item.value,
text: item.text
}));
});
}
PHP Array of properties should be like this:
$properties = array(
'item1' => array('text' => 'item1 text', 'value' => 'item 1 value'),
'item2' => array('text' => 'item2 text', 'value' => 'item 2 value'),
'item3' => array('text' => 'item3 text', 'value' => 'item 3 value')
);

Related

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() {

get all IDs of selected checkbox in Yii using javascript

I am trying to get the IDs of all the selected check boxes in yii using JAVASCRIPT. Now i am able to get only the first element ID. Can anyone please suggest the correct code to get all the check box ID.
My View:
<input type="button" value="Multiple Host Date Entries" onclick="act();" />
<div id="grid"></div>
<?php
//zii.widgets.grid.CGridView bootstrap.widgets.TbExtendedGridView
$obj=$this->widget('bootstrap.widgets.TbExtendedGridView', array(
'id'=>'host_grid',
'dataProvider'=>$dataProvider,
'type' => 'striped bordered',
//'filter' => $model,
//'type' => 'striped bordered condensed',
//'summaryText' => false,
////'afterAjaxUpdate'=>'\'changeTRColor()\'',
//'itemView'=>'_view',
'columns'=>array(
array(
'id' => 'selectedIds',
'class' => 'CCheckBoxColumn',
'selectableRows'=>2,
'value' => '$data->host_id',
'checkBoxHtmlOptions' => array('name' => 'idList[]'),
),
array( // display 'create_time' using an expression
'name'=>'host_name',
'value'=>'$data->host_name',
),
array(
'name'=>'host_serviceid',
'value'=>'$data->host_serviceid',
),
array(
'name'=>'status',
'value'=>'$data->status',
),
array(
'class'=>'CButtonColumn',
'template'=>'{edit_date}{update}{delete}',
'htmlOptions'=>array('width'=>'95px'),
'buttons' => array(
'update'=> array(
'label' => 'Update',
'imageUrl' => Yii::app()->baseUrl.'/images/icons/a.png',
),
'delete'=> array(
'label' => 'Delete',
'imageUrl' => Yii::app()->baseUrl.'/images/icons/d.png',
),
'edit_date' => array( //the name {reply} must be same
'label' => 'Add Date', // text label of the button
'url' => 'Yii::app()->createAbsoluteUrl("NimsoftHostsDetails/View", array("id"=>$data->host_id))', //Your URL According to your wish
'imageUrl' => Yii::app()->baseUrl.'/images/icons/m.png', // image URL of the button. If not set or false, a text link is used, The image must be 16X16 pixels
),
),)
),
))
;
?>
I must select some check boxes and click on multiple host date entries button to go to the specific controller.
My JavaScript:
function act()
{
var idList=$("input[type=checkbox]:checked").serializeArray();
var jsonStr = JSON.stringify(idList);
/* Object.keys(idList).forEach(function(key) {
console.log(key, idList[key]);
alert(idList[key]);
});*/
var a=$("input[type=checkbox]:checked").val();
alert(a);
if(idList!="")
{
if(confirm("Add Dates for multiple hosts?"))
{
var url='<?php echo $this->createUrl('Nimsoft/Date_all',array('idList'=>'val_idList')); ?>';
url=url.replace('val_idList',jsonStr);
//url=url.replace('val_idList',json_encode(idList));
//alert(url);
window.open(url);
/*$.post('Date_all',idList,function(response)
{
$.fn.yiiGridView.update("host_grid");
});*/
}
}
else
{
alert("Please Select atleast one host");
}
}
I need to pass the IDs to NIMSOFT controller so that I can have a for loop to process each one of those.
you can retrieve the checked column in client side (javasctipt):
var idArray = $(gridID).yiiGridView('getChecked', columnID);
// or
$.fn.yiiGridView.getSelection(gridID);
For all checked row ids we use this
var id = $.fn.yiiGridView.getChecked("your-grid-id", "selectedIds"); // array of seleted id's from grid

how to add live updating charts in yii with highchart

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 :)

Print a 'node/add' form in a lightbox with Drupal

I'm having some troubles printing a 'node/add' form in a lightbox.
I have in my custom.module a hook_menu like this:
$items['get-form/%'] = array(
'title' => t('Get a form'),
'description' => t('Get form'),
'page callback' => '_get_form',
'page arguments' => array(1),
'access arguments' => array('access content'),
'type' => MENU_CALLBACK,
);
... where % is the id, like "story_node_form".
Then, I have the callback function like this:
function _get_form($form_id){
module_load_include('inc', 'node', 'node.pages');
if (strpos($form_string, "_node_form")){
//Test if the form is a <type>_node_form. Is the node/add/<type>
$content_type = explode("_node_form", $form_id)[0];
print drupal_render(node_add($content_type));
}
The forms shows right, in the lightbox. The problem is that the javascript of the form (wysiwyg, node references, term references, ...) doesn't work.
I tried to execute Drupal.attachBehaviors(), Drupal.attachBehaviors(document) and Drupal.attachBehaviors("#story-node-form") but nothing seems to work.
Anyone can help?
This code should do the trick:
function _get_form($form_id){
global $user;
$node = (object) array(
'uid' => $user->uid,
'name' => (isset($user->name) ? $user->name : ''),
'type' => 'ENTER NODE TYPE HERE',
'language' => LANGUAGE_NONE
);
$form_state['build_info']['args'] = array($node);
form_load_include($form_state, 'inc', 'node', 'node.pages');
echo drupal_render(drupal_build_form($form_id, $form_state));
}
You will need to get the node type as well as the form_id for this to work but that shouldn't be to difficult.

Categories

Resources