Custom Tooltip in Google Chart Timeline using php - javascript

Starting off, I want to say everything is working here, I am just wondering how can I attach a custom tooltip for the results.
I tried to add a new column type string and role tooltip and set the row v as a tooltip but it didn't worked
PHP Generator
$table['cols'] = array(
array('label' => 'str1', 'type' => 'string'),
array('label' => 'str1', 'type' => 'string'),
array('label' => 'data1', 'type' => 'date'),
array('label' => 'data2', 'type' => 'date')
);
foreach ($query as $r) {
$date1 = new DateTime($r['data_zakupu']);
$date2 = "Date(" . date_format($date1, 'Y') . ", " . ((int)date_format($date1, 'm') - 1) . ", " . date_format($date1, 'j') . ")";
$date3 = new DateTime($r['data_zakupu']);
$date3->modify("+ 1 day");
$date4 = "Date(" . date_format($date3, 'Y') . ", " . ((int)date_format($date3, 'm') - 1) . ", " . date_format($date3, 'j') . ")";
$temp = array();
if (!isset($pojazd)) {
$temp[] = array('v' => (string)$r['nr_rej']);
} else {
$temp[] = array('v' => (string)$r['kat']);
}
if ($r['kat'] === "Paliwo") {
$alias = $r['litry'] . " L";
} else {
$alias = $r['kat']." - ".$r['brutto'] . " zł";
}
$temp[] = array('v' => (string)$alias);
$temp[] = array('v' => (string)$date2);
$temp[] = array('v' => (string)$date4);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
echo json_encode($table);
HTML + JS
<script type="text/javascript"
src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
var d = new Date();
var n = d.getMonth() + 1;
var y = d.getFullYear();
$('#month_picker').val(n);
$('#year_picker').val(y);
google.charts.load("current", {packages: ["timeline"], 'language': 'pl'});
google.charts.setOnLoadCallback(drawChart);
$("#users").change(drawChart);
$('#month_picker').on('change', function () {
drawChart();
});
$(window).on("throttledresize", function (event) {
drawChart();
});
function drawChart() {
$.ajax({
url: '',
type: "POST",
data: {
customMonth: $('#month_picker').val(),
customYear: $('#year_picker').val(),
},
dataType: 'json',
success: function (responseText) {
var container = document.getElementById('visualization');
var chart = new google.visualization.Timeline(container);
var dataTable = new google.visualization.DataTable(responseText);
var options = {
timeline: {colorByRowLabel: true}
};
$(window).trigger('resize');
chart.draw(dataTable, options);
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
}
$(window).resize(function() {
$('#visualization').height('500px');// need autoheight
});
</script>
<div id="visualization" style="width: 100%;"></div>
JSON generated by php : https://jsonblob.com/17856337-ca0e-11e7-9220-89c8556cdc82

according to the data format for a Timeline,
the tooltip should be in Column 2
as such, the column definitions would be as follows...
$table['cols'] = array(
array('label' => 'str1', 'type' => 'string'),
array('label' => 'str1', 'type' => 'string'),
array('role' => 'tooltip', 'type' => 'string'),
array('label' => 'data1', 'type' => 'date'),
array('label' => 'data2', 'type' => 'date')
);
then add the tooltip content to each row...
...
$temp[] = array('v' => (string)$alias);
$temp[] = array('v' => (string)$tooltip);
$temp[] = array('v' => (string)$date2);
$temp[] = array('v' => (string)$date4);
$rows[] = array('c' => $temp);

Related

I am trying to retrieve the posts via ajax call but Wordpress Ajax gives server error 500

When I click on pagination link (page number) it gives me post_type, taxonomy, term_name. I passed the variables with JQuery Variables to Ajax wordpress function. The Ajax function is receiving the vaiables. But WP_Query loop does not work with the passed data.
JavaScript Code:
<script>
$(".category--pagination").on("click", "a", function (e) {
e.preventDefault();
var link = $(this).attr("href");
if (link.indexOf("/page/") >= 0) {
brands_page = parseInt(link.substr(link.indexOf("/page/") + 6, 4));
} else {
brands_page = 1;
}
mzm_filter_taxonomy();
});
// mzm_filter_tax
function mzm_filter_taxonomy() {
$("#brandCategoryItemDisplay").addClass("loading");
var post_type = $("#post_type").val();
var taxonomy = $("#taxonomy").val();
var term_slug = $("#term_slug").val();
var term_name = $("#term_name").val();
//console.log(post_type);
// console.log(taxonomy);
// console.log(term_name);
if (brands_page == undefined) {
brands_page = 1;
}
var data = {
action: "mzm_filter_taxonomy",
post_type: post_type,
taxonomy:taxonomy,
term_slug:term_slug,
term_name:term_name,
page:brands_page,
};
$.post(mzm_filter.ajax_url, data, function (response, textStatus, jqXHR) {
if (response.success) {
console.log("executed success");
$("#brandCategoryItemDisplay").removeClass("loading");
$("#brandCategoryItemDisplay").html(response.data.items);
$(".category--pagination").html(response.data.pagination);
//$("#taxonomy_pagination").html(response.data.pagination);
}
});
}
</script>
Wordpress Ajax Function:
function mzm_filter_taxonomy()
{
$post_type = isset($_POST['post_type']) ? filter_var(trim($_POST['post_type']), FILTER_SANITIZE_FULL_SPECIAL_CHARS) : null;
$taxonomy = isset($_POST['taxonomy']) ? filter_var(trim($_POST['taxonomy']), FILTER_SANITIZE_FULL_SPECIAL_CHARS) : null;
$term_slug = isset($_POST['term_slug']) ? filter_var(trim($_POST['term_slug']), FILTER_SANITIZE_FULL_SPECIAL_CHARS) : null;
$term_name = isset($_POST['term_name']) ? filter_var(trim($_POST['term_name']), FILTER_SANITIZE_FULL_SPECIAL_CHARS) : null;
$perpage = mzm_brand_perpage();
$paged = (isset($_POST['page']) && intval($_POST['page'])) ? intval($_POST['page']) : 1;
// $sort = ( isset( $_POST['sort'] ) && intval( $_POST['sort'] ) ) ? intval( $_POST['sort'] ) : 1;
// $sort = (isset($_POST['sort'])) ? intval($_POST['sort']) : 1;
// $args = array(
// 'post_type' => $post_type,
// 'hide_empty' => false,
// 'posts_per_page' => $perpage,
// 'paged' => $paged,
// 'post_status' => 'publish',
// 'tax_query' => array(
// array (
// 'taxonomy' => $taxonomy,
// 'field' => 'slug',
// 'terms' => $term_slug,
// )
// ),
// );
$the_query = new WP_Query( array(
'post_type' => $post_type,
'tax_query' => array(
array (
'taxonomy' => $taxonomy,
'field' => 'slug',
'terms' => $term_slug,
)
),
) );
// $the_query = new WP_Query($args);
ob_start();
// echo $post_type . '<br>';
// echo $taxonomy . '<br>';
// echo $term_name . '<br>';
// echo $term_slug . '<br>';
if ($the_query->have_posts()) {
while ($the_query->have_posts()) {
the_post();
// echo mzm_render_single_brand_card();
echo the_title();
}
wp_reset_postdata();
} else {
echo '<div class="no-criteria-search">Sorry, no posts matched your criteria.</div>';
}
$html = ob_get_clean();
$result = array(
'items' => $html,
'pagination' => 'mzm_render_pagination($the_query)',
);
wp_send_json_success($result);
}
add_action('wp_ajax_nopriv_mzm_filter_taxonomy', 'mzm_filter_taxonomy');
add_action('wp_ajax_mzm_filter_taxonomy', 'mzm_filter_taxonomy');
I am trying paginate via Ajax request. Other all scripts are working. But this is a single taxonomy page. On this page the loop doesn't executes. It gives server error 500.
I solved it myself.
The problem was in wp_query loop. I using custom $args and the loop object was $the_query.
So,
the_post();
//should be
$the_query->the_post();

My condition control in widget in modal window does not permit to edit exist condition but permit to create and save new

I am create widget in magento 2.3 that extend funcitonality of vendor Catalog List Product. By default Catalog List Product (CLP) does not allow to create and handle several condition control on same page. My widget allow to create several condition control.
Technically each my conditions control open in new modal window.
When the user need to create condition then he must click on button named "Choose"
Modal window opens and user set the conditions. When the user configures and ready to save condition then he click to button named "Save" on modal window ajax request sending to server and server respond decoded value to parent form input. The user close modal window and click on Save button on parent form. Widget saved. All done. Everything is right until this step:
When user want to edit saved widget and opens modal window saved data converts to aplicable form by another ajax and jQuery Prepend newchild
< li >
to < ul >
But prepended data becomes not interactable- user cannot edit and delete loaded rule.
widget.xml
<parameter name="cond1" xsi:type="block" visible="true" required="false">
<label translate="true">First Conditions</label>
<block class="MonteShot\MegaWidget\Block\Adminhtml\Conditions\Conditions">
<data>
<item name="condition" xsi:type="array">
<item name="id1" xsi:type="string" translate="true">1</item>
</item>
</data>
</block>
</parameter>
MonteShot\MegaWidget\Block\Adminhtml\Conditions\Conditions
<?php
namespace MonteShot\MegaWidget\Block\Adminhtml\Conditions;
use Magento\Backend\Block\Widget\Form\Generic;
use Magento\Backend\Block\Widget\Tab\TabInterface;
use Magento\Widget\Block\BlockInterface;
/**
* Class Conditions
*/
class Conditions extends Generic implements TabInterface, BlockInterface
{
/**
* Conditions constructor.
* #param \Magento\Backend\Block\Template\Context $context
* #param \Magento\Framework\Data\FormFactory $formFactory
* #param \Magento\Rule\Block\Conditions $conditions
* #param \Magento\Backend\Block\Widget\Form\Renderer\Fieldset $rendererFieldset
* #param \Magento\Framework\Registry $coreRegistry
* #param \MonteShot\MegaWidget\Model\RuleFactory $ruleModelFactory
* #param \Magento\CatalogWidget\Model\RuleFactory $ruleFactory
* #param \Magento\Widget\Helper\Conditions $conditionsHelper
* #param \Magento\Cms\Model\PageFactory $pageFactory
* #param \Magento\Framework\App\Response\Http $response
* #param array $data
*/
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\Framework\Data\FormFactory $formFactory,
\Magento\Rule\Block\Conditions $conditions,
\Magento\Backend\Block\Widget\Form\Renderer\Fieldset $rendererFieldset,
\Magento\Framework\Registry $coreRegistry,
\MonteShot\MegaWidget\Model\RuleFactory $ruleModelFactory,
\Magento\CatalogWidget\Model\RuleFactory $ruleFactory,
\Magento\Widget\Helper\Conditions $conditionsHelper,
\Magento\Cms\Model\PageFactory $pageFactory,
\Magento\Framework\App\Response\Http $response,
array $data = []
)
{
$this->response = $response;
$this->conditionsHelper = $conditionsHelper;
$this->ruleFactory = $ruleFactory;
$this->ruleModelFactory = $ruleModelFactory;
$this->_pageFactory = $pageFactory;
$this->coreRegistry = $coreRegistry;
$this->rendererFieldset = $rendererFieldset;
$this->conditions = $conditions;
parent::__construct($context, $coreRegistry, $formFactory, $data);
}
/**
* {#inheritdoc}
*/
public function getTabLabel()
{
return __('Conditions');
}
/**
/**
* #param \Magento\Framework\Data\Form\Element\AbstractElement $element
* #return \Magento\Framework\Data\Form\Element\AbstractElement
* #throws \Magento\Framework\Exception\LocalizedException
*/
public function prepareElementHtml(\Magento\Framework\Data\Form\Element\AbstractElement $element)
{
$uniqId = $this->mathRandom->getUniqueHash($element->getId());
$sourceUrl = $this->getUrl(
'megawidget/conditions_rule_conditioncontent/conditionpagecontroller',
[
'name' => $element->getData('name'),
'uniq_id' => $uniqId,
'button_num' => $this->getData('condition')[key($this->getData('condition'))]
]);
$chooser = $this->getLayout()->createBlock(
\MonteShot\MegaWidget\Block\Adminhtml\Widget\Chooser::class
)->setElement(
$element
)->setConfig(
$this->getConfig()
)->setFieldsetId(
$this->getFieldsetId()
)->setSourceUrl(
$sourceUrl
)->setUniqId(
$uniqId
)->setValue($this->getData('condition')[key($this->getData('condition'))]);
if ($element->getValue()) {
$page = $this->_pageFactory->create()->load((int)$element->getValue());
if ($page->getId()) {
$chooser->setLabel($this->escapeHtml($page->getTitle()));
}
}
$element->setData('after_element_html', $chooser->toHtml());
return $element;
}
/**
* Prepare form before rendering HTML
*
* #return Generic
* #throws \Magento\Framework\Exception\LocalizedException
*/
protected function _prepareForm()
{
$model = $this->ruleFactory->create();
// $model = $this->ruleModelFactory->create();
$id = $this->_request->getParam('uniq_id');
$name = $this->_request->getParam('name');
$cuttedName = trim(str_replace('parameters', '', $name), '[]');
/** #var \Magento\Framework\Data\Form $form */
$form = $this->_formFactory->create(
[
'data' => [
'id' => 'edit_form_modal',
'action' => $this->getUrl('megawidget/conditions_rule/savewidget',
[
'uniq_id' => $this->_request->getParam('uniq_id'),
'button_num' => $this->_request->getParam('button_num'),
'name' => $this->_request->getParam('name'),
]),
'method' => 'post',
],
]
);
$form->setUseContainer(true);
$form->setHtmlIdPrefix('rule_');
$this->getLayout()->createBlock("Magento\Widget\Block\Adminhtml\Widget\Options");
$renderer = $this->rendererFieldset->setTemplate(
'Magento_CatalogRule::promo/fieldset.phtml'
)->setNewChildUrl(
$this->getUrl('megawidget/conditions_rule/newConditionHtmlCatalog/form/rule_conditions_fieldset')
);
$fieldset = $form->addFieldset(
'conditions_fieldset',
[
'legend' => __(
'Apply the rule only if the following conditions are met (leave blank for all products).'
)
]
)->setRenderer(
$renderer
);
// $model->getConditions()->setJsFormObject('rule_conditions_fieldset');
// $model->setData('element_value', substr_replace($_POST['element_value'], '', 0, 26));
$model->getConditions()->setJsFormObject('rule_conditions_fieldset');
$fieldset->addField(
'conditions',
'text',
['name' => 'conditions', 'label' => __('Conditions'), 'title' => __('Conditions')]
)->setRule(
$model
)->setRenderer(
$this->conditions
);
$label = $id . 'label';
$valueId = $id . 'value';
$fieldset->addField(
'button-save',
'hidden',
['name' => 'select',
'label' => __('Save condition'),
'title' => __('Save condition'),
'class' => 'action-close',
'data-role' => 'closeBtn',
'data_attribute' => [
'mage-init' => ['button' => ['event' => 'saveandcontinue', 'target' => '#edit_form']],
],
'after_element_html' => '
<button data-role="closeBtn" id="rule_button-save-submit-' . $cuttedName . '" type="button">Save</button>
<script>
require([\'jquery\',\'jqueryForm\',\'Magento_Ui/js/modal/modal\'], function (jQuery,jqueryForm,modal){
jQuery(document).on(\'click\', "#rule_button-save-submit-' . $cuttedName . '", function () {
var serArr=JSON.stringify(jQuery("#edit_form_modal").serializeArray());
jQuery.ajax({
url: "' . $this->getUrl("megawidget/conditions_rule/preparedata") . '",
data: { form_key: window.FORM_KEY,serializedArray:serArr},
type: \'post\',
success: function (response) {
console.log(response.data);
jQuery("input[name=\'' . $name . '\']")[0].value=response.data;
},
error: function (response) {
alert(response.message);
console.log(response.message);
}
});
});
});
</script>
']);
$fieldset->addField(
'script-area',
'hidden',
['name' => 'select',
'class' => 'script-area-hidden',
'data_attribute' => [
'mage-init' => ['hidden' => ['event' => 'saveandcontinue', 'target' => '#edit_form_modal']],
],
'after_element_html' => '
<script>
require([\'jquery\',\'jqueryForm\'],
function ($,jqueryForm){
jQuery(document).ready(function (jQuery) {
jQuery.ajax({
url: "' . $this->getUrl("megawidget/conditions_rule/newConditionHtmlCatalog/form/rule_conditions_fieldset") . '",
data: {JsonToHtml:jQuery("input[name=\'' . $name . '\']")[0].value, form: window.FORM_KEY},
type: \'post\',
success: function (response) {
console.log(response.data);
jQuery(document.querySelector("#conditions__1__children")).prepend(response.data);
},
error: function (response) {
alert(response.message);
console.log(response.message);
}
});
});
});
</script>
']);
// $model->getConditions()->setJsFormObject('rule_conditions_fieldset');
$form->setValues($model->getData());
$this->setForm($form);
return parent::_prepareForm();
}
}
//Magento\Widget\Helper\Conditions encode when save button has been pressed
And code in modal window
$model = $this->ruleFactory->create();
// $model = $this->ruleModelFactory->create();
$id = $this->_request->getParam('uniq_id');
$name = $this->_request->getParam('name');
$cuttedName = trim(str_replace('parameters', '', $name), '[]');
/** #var \Magento\Framework\Data\Form $form */
$form = $this->_formFactory->create(
[
'data' => [
'id' => 'edit_form_modal',
'action' => $this->getUrl('megawidget/conditions_rule/savewidget',
[
'uniq_id' => $this->_request->getParam('uniq_id'),
'button_num' => $this->_request->getParam('button_num'),
'name' => $this->_request->getParam('name'),
]),
'method' => 'post',
],
]
);
$form->setUseContainer(true);
$form->setHtmlIdPrefix('rule_');
$this->getLayout()->createBlock("Magento\Widget\Block\Adminhtml\Widget\Options");
$renderer = $this->rendererFieldset->setTemplate(
'Magento_CatalogRule::promo/fieldset.phtml'
)->setNewChildUrl(
$this->getUrl('megawidget/conditions_rule/newConditionHtmlCatalog/form/rule_conditions_fieldset')
);
$fieldset = $form->addFieldset(
'conditions_fieldset',
[
'legend' => __(
'Apply the rule only if the following conditions are met (leave blank for all products).'
)
]
)->setRenderer(
$renderer
);
// $model->getConditions()->setJsFormObject('rule_conditions_fieldset');
// $model->setData('element_value', substr_replace($_POST['element_value'], '', 0, 26));
$model->getConditions()->setJsFormObject('rule_conditions_fieldset');
$fieldset->addField(
'conditions',
'text',
['name' => 'conditions', 'label' => __('Conditions'), 'title' => __('Conditions')]
)->setRule(
$model
)->setRenderer(
$this->conditions
);
// $fieldset->addElement($this->getLayout()->createBlock(\MonteShot\MegaWidget\Renderer\Conditions::class));
$label = $id . 'label';
$valueId = $id . 'value';
$fieldset->addField(
'button-save',
'hidden',
['name' => 'select',
'label' => __('Save condition'),
'title' => __('Save condition'),
'class' => 'action-close',
'data-role' => 'closeBtn',
'data_attribute' => [
'mage-init' => ['button' => ['event' => 'saveandcontinue', 'target' => '#edit_form']],
],
'after_element_html' => '
<button data-role="closeBtn" id="rule_button-save-submit-' . $cuttedName . '" type="button">Save</button>
<script>
require([\'jquery\',\'jqueryForm\',\'Magento_Ui/js/modal/modal\'], function (jQuery,jqueryForm,modal){
jQuery(document).on(\'click\', "#rule_button-save-submit-' . $cuttedName . '", function () {
var serArr=JSON.stringify(jQuery("#edit_form_modal").serializeArray());
jQuery.ajax({
url: "' . $this->getUrl("megawidget/conditions_rule/preparedata") . '",
data: { form_key: window.FORM_KEY,serializedArray:serArr},
type: \'post\',
success: function (response) {
console.log(response.data);
jQuery("input[name=\'' . $name . '\']")[0].value=response.data;
},
error: function (response) {
alert(response.message);
console.log(response.message);
}
});
});
});
</script>
']);
$fieldset->addField(
'script-area',
'hidden',
['name' => 'select',
'class' => 'script-area-hidden',
'data_attribute' => [
'mage-init' => ['hidden' => ['event' => 'saveandcontinue', 'target' => '#edit_form_modal']],
],
'after_element_html' => '
<script>
require([\'jquery\',\'jqueryForm\'],
function ($,jqueryForm){
jQuery(document).ready(function (jQuery) {
jQuery.ajax({
url: "' . $this->getUrl("megawidget/conditions_rule/newConditionHtmlCatalog/form/rule_conditions_fieldset") . '",
data: {JsonToHtml:jQuery("input[name=\'' . $name . '\']")[0].value, form: window.FORM_KEY},
type: \'post\',
success: function (response) {
console.log(response.data);
jQuery(document.querySelector("#conditions__1__children")).prepend(response.data);
},
error: function (response) {
alert(response.message);
console.log(response.message);
}
});
});
});
</script>
']);
$form->setValues($model->getData());
$this->setForm($form);
return parent::_prepareForm();
}
PrepareData Controller
<?php
/**
* Copyright (c) 2019. MonteShot
*/
namespace MonteShot\MegaWidget\Controller\Adminhtml\Conditions\Rule;
use Magento\Framework\Json\Helper\Data as JsonHelper;
/**
* Class PrepareData
*/
class PrepareData extends \MonteShot\MegaWidget\Controller\Adminhtml\Conditions\Rule
{
/**
* #param \Magento\Backend\App\Action\Context $context
* #param \Magento\Framework\Registry $coreRegistry
* #param \Magento\Framework\App\Response\Http\FileFactory $fileFactory
* #param \Magento\Framework\Stdlib\DateTime\Filter\Date $dateFilter
* #param \MonteShot\MegaWidget\Model\RuleFactory $ruleFactory
* #param \Magento\Widget\Helper\Conditions $conditionsHelper
* #param \Psr\Log\LoggerInterface $logger
* #param \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory
* #param JsonHelper $jsonHelper
*/
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Magento\Framework\Registry $coreRegistry,
\Magento\Framework\App\Response\Http\FileFactory $fileFactory,
\Magento\Framework\Stdlib\DateTime\Filter\Date $dateFilter,
\MonteShot\MegaWidget\Model\RuleFactory $ruleFactory,
\Magento\Widget\Helper\Conditions $conditionsHelper,
\Psr\Log\LoggerInterface $logger,
\Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory,
JsonHelper $jsonHelper
)
{
$this->jsonHelper = $jsonHelper;
$this->resultJsonFactory = $resultJsonFactory;
$this->conditionsHelper = $conditionsHelper;
parent::__construct($context, $coreRegistry, $fileFactory, $dateFilter, $ruleFactory, $logger);
}
/**
* #return \Magento\Framework\App\ResponseInterface|\Magento\Framework\Controller\Result\Json|\Magento\Framework\Controller\ResultInterface|void
*/
public function execute()
{
if (!$this->getRequest()->getPostValue()) {
$this->_redirect('megawidget/*/');
}
try {
$serializedConditionArray =
$this->conditionsHelper->decode($this->getRequest()->getParam('serializedArray'));
$templateArray = [];
foreach ($serializedConditionArray as $index => $singleArrItem) {
if ($singleArrItem['name'] == 'form_key') {
unset($serializedConditionArray[$index]);
continue;
}
if ($singleArrItem['name'] == 'select') {
unset($serializedConditionArray[$index]);
continue;
}
if (!empty($templateArray[str_replace('rule', '', $singleArrItem['name'])])) {
$templateArray[str_replace('rule', '', $singleArrItem['name'])] .= ',' . $singleArrItem['value'];
} else {
$templateArray[str_replace('rule', '', $singleArrItem['name'])] = $singleArrItem['value'];
}
//$templateArray[str_replace('rule', '', $singleArrItem['name'])] = $singleArrItem['value'];
}
$finalArr = [];
foreach ($templateArray as $index => $data) {
$indexName = $this->get_string_between(str_replace('[conditions]', '', $index), '[', ']');
$paramName = $this->get_string_between(str_replace('[conditions][' . $indexName . ']', '', $index), '[', ']');
$multiValue = str_replace('parameters[conditions][' . $indexName . ']' . '[' . $paramName . ']', '', $index);
if ($paramName == 'value' && strpos($data, ',')) {
$finalArr[$indexName][$paramName] = [$data];
} else {
$finalArr[$indexName][$paramName] = $data;
}
if ($paramName == 'value' && $multiValue == '[]') {
if ($finalArr[$indexName][$paramName]) {
if ($finalArr[$indexName][$paramName]) {
$temp = $finalArr[$indexName][$paramName];
unset($finalArr[$indexName][$paramName]);
$finalArr[$indexName][$paramName][0] = $data;
} else {
$finalArr[$indexName][$paramName][0] .= ',' . $data;
}
} else {
$finalArr[$indexName][$paramName][0] = [$data];
}
}
}
$this->data = $this->conditionsHelper->encode($finalArr);
$this->message = 'success';
} catch (\Magento\Framework\Exception\LocalizedException $e) {
$this->messageManager->addErrorMessage($e->getMessage());
$id = (int)$this->getRequest()->getParam('rule_id');
if (!empty($id)) {
$this->_redirect('megawidget/*/edit', ['id' => $id]);
} else {
$this->_redirect('megawidget/*/new');
}
return;
} catch (\Exception $e) {
$this->messageManager->addErrorMessage(
__('Something went wrong while saving the rule data. Please review the error log.')
);
$this->error = $e->getMessage();
$this->message = 'success';
$this->logger->critical($e);
$data = !empty($data) ? $data : [];
$this->_session->setPageData($data);
$this->_redirect('megawidget/*/edit', ['id' => $this->getRequest()->getParam('rule_id')]);
return;
}
$resultJson = $this->resultJsonFactory->create();
$resultData = substr(substr($this->jsonHelper->jsonEncode($this->data), 1), 0, -1);
return $resultJson->setData([
'message' => $this->message,
'data' => $resultData,
'error' => $this->error
]);
}
protected function get_string_between($string, $start, $end)
{
$string = ' ' . $string;
$ini = strpos($string, $start);
if ($ini == 0) return '';
$ini += strlen($start);
$len = strpos($string, $end, $ini) - $ini;
return substr($string, $ini, $len);
}
}
Controller that return data that ready to prepend in jQuery
<?php
/**
* Copyright (c) 2019. MonteShot
*/
namespace MonteShot\MegaWidget\Controller\Adminhtml\Conditions\Rule;
use Magento\Framework\Json\Helper\Data as JsonHelper;
class NewConditionHtmlCatalog extends \MonteShot\MegaWidget\Controller\Adminhtml\Conditions\Rule
{
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Magento\Framework\Registry $coreRegistry,
\Magento\Framework\App\Response\Http\FileFactory $fileFactory,
\Magento\Framework\Stdlib\DateTime\Filter\Date $dateFilter,
\MonteShot\MegaWidget\Model\RuleFactory $ruleFactory,
\Psr\Log\LoggerInterface $logger,
\Magento\Widget\Helper\Conditions $conditions,
\Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory,
JsonHelper $jsonHelper,
\Magento\CatalogWidget\Model\RuleFactory $ruleCatalogFactory,
\Magento\Rule\Model\Condition\CombineFactory $combineModelFactory
)
{
$this->combineModelFactory = $combineModelFactory;
$this->ruleCatalogFactory = $ruleCatalogFactory;
$this->jsonHelper = $jsonHelper;
$this->resultJsonFactory = $resultJsonFactory;
$this->conditions = $conditions;
parent::__construct($context, $coreRegistry, $fileFactory, $dateFilter, $ruleFactory, $logger);
}
public function execute()
{
if (!empty($this->getRequest()->getParam('id'))) {
$id = $this->getRequest()->getParam('id');
$typeArr = explode('|', str_replace('-', '/', $this->getRequest()->getParam('type')));
$type = $typeArr[0];
$model = $this->_objectManager->create(
$type
)->setId(
$id
)->setType(
$type
)->setRule(
$this->ruleFactory->create()
)->setPrefix(
'conditions'
);
if (!empty($typeArr[1])) {
$model->setAttribute($typeArr[1]);
}
if ($model instanceof \Magento\Rule\Model\Condition\AbstractCondition) {
$model->setJsFormObject($this->getRequest()->getParam('form'));
$html = $model->asHtmlRecursive();
} else {
$html = '';
}
return $this->getResponse()->setBody($html);
} elseif (!empty($this->getRequest()->getParam('JsonToHtml'))) {
$conditionDecoded = $this->conditions->decode($this->getRequest()->getParam('JsonToHtml'));
foreach ($conditionDecoded as $idx => $condition) {
if ($idx == '1') {
continue;
} else {
$id = $idx;
$type = $conditionDecoded[$idx]['type'];
$rule = $this->ruleCatalogFactory->create();
// $rule->setConditions($conditionDecoded);
$combineModel = $this->combineModelFactory->create();
$combineModel->loadArray($conditionDecoded);
$validateResult = $rule->validateData(new \Magento\Framework\DataObject($rule->getData()));
if ($validateResult !== true) {
foreach ($validateResult as $errorMessage) {
$this->message = $errorMessage;
}
return;
}
$rule->loadPost($rule->getData());
$model = $this->_objectManager->create(
$type
)->setId(
$id
)->setType(
$type
)->setPrefix(
'conditions'
)->setData(
'conditions', $rule
)->setRule(
$rule
);
if (!empty($conditionDecoded[$idx]['attribute'])) {
$model->setAttribute($conditionDecoded[$idx]['attribute']);
}
if (!empty($conditionDecoded[$idx]['value'])) {
$model->setValue($conditionDecoded[$idx]['value']);
}
}
if ($model instanceof \Magento\Rule\Model\Condition\AbstractCondition) {
// if (empty($this->data)) {
// $model->setJsFormObject($this->getRequest()->getParam('form'));
// $this->data = '<li class>' . $model->asHtmlRecursive() . '</li>';
// $this->data = $model->asHtmlRecursive();
// } else {
$model->setJsFormObject($this->getRequest()->getParam('form'));
$this->data = '<li class>' . $model->asHtmlRecursive() . '</li>';
//$this->data = $this->data . "\n" . '<li class>' . $model->asHtmlRecursive() . '</li>';
// }
} else {
$this->data = '';
}
$this->getResponse()->setBody($this->data);
}
}
}
// return $this->getResponse()->setBody($this->data);
$resultJson = $this->resultJsonFactory->create();
return $resultJson->setData([
'message' => $this->message,
'data' => $this->data,
'error' => $this->error
]);
}
}
How i can return interactivity to loaded data
protected function _prepareForm()
{
$model = $this->ruleFactory->create();
// $model = $this->ruleModelFactory->create();
$id = $this->_request->getParam('uniq_id');
$name = $this->_request->getParam('name');
$cuttedName = trim(str_replace('parameters', '', $name), '[]');
// if ($this->ruleResourceCollection->getSize() == 0) {
//
// } else {
// if (!$id) {
// $model = $this->ruleResourceCollection
// ->addFieldToFilter(\MonteShot\MegaWidget\Model\Rule::UNIQ_BUTTON_ID,
// $id
// )->load();
// }
// }
/** #var \Magento\Framework\Data\Form $form */
$form = $this->_formFactory->create(
[
'data' => [
'id' => 'edit_form_modal',
'action' => $this->getUrl('megawidget/conditions_rule/savewidget',
[
'uniq_id' => $this->_request->getParam('uniq_id'),
'button_num' => $this->_request->getParam('button_num'),
'name' => $this->_request->getParam('name'),
]),
'method' => 'post',
],
]
);
$form->setUseContainer(true);
$form->setHtmlIdPrefix('rule_');
$this->getLayout()->createBlock("Magento\Widget\Block\Adminhtml\Widget\Options");
$renderer = $this->rendererFieldset->setTemplate(
'Magento_CatalogRule::promo/fieldset.phtml'
)->setNewChildUrl(
$this->getUrl('megawidget/conditions_rule/newConditionHtmlCatalog/form/rule_conditions_fieldset')
);
$fieldset = $form->addFieldset(
'conditions_fieldset',
[
'legend' => __(
'Apply the rule only if the following conditions are met (leave blank for all products).'
)
]
)->setRenderer(
$renderer
);
$model->getConditions()->setJsFormObject('rule_conditions_fieldset');
try {
$conditions = $this->conditionsHelper->decode($this->getRequest()->getParam('element_value'));
$model->loadPost(['conditions' => $conditions]);
} catch (\InvalidArgumentException $invalidArgumentException) {
//do nothing
}
$element = $fieldset->addField(
'condition',
'text',
['name' => 'conditions',
'label' => __('Condition'),
'title' => __('Condition'),
'data_attribute' => [
'mage-init' => ['button' => ['event' => 'saveandcontinue', 'target' => '#edit_form_modal']],
]
])
->setRule(
$model
)->setRenderer(
$this->conditions
);
$sourceUrl = $this->getUrl(
'megawidget/conditions_rule_conditioncontent/conditionmodalpagecontroller');
$condition = $this->getLayout()->createBlock(
\MonteShot\MegaWidget\Block\Adminhtml\Widget\Options::class
)->setElement(
$element
)->setConfig(
$this->getConfig()
)->setFieldsetId(
$this->getFieldsetId()
)->setSourceUrl(
$sourceUrl
)->setConfig(
$this->getConfig()
)->setFieldsetId(
$this->getFieldsetId()
)->setUniqId(
$id
);
// $fieldset->addElement($this->getLayout()->createBlock(\MonteShot\MegaWidget\Renderer\Conditions::class));
$label = $id . 'label';
$valueId = $id . 'value';
$fieldset->addField(
'button-save',
'hidden',
['name' => 'select',
'label' => __('Save condition'),
'title' => __('Save condition'),
'class' => 'action-close',
'data-role' => 'closeBtn',
'data_attribute' => [
'mage-init' => ['button' => ['event' => 'saveandcontinue', 'target' => '#edit_form']],
],
'after_element_html' => '
<button data-role="closeBtn" id="rule_button-save-submit-' . $cuttedName . '" type="button">Save</button>
<script>
require([\'jquery\',\'jqueryForm\',\'Magento_Ui/js/modal/modal\'], function (jQuery,jqueryForm,modal){
jQuery(document).on(\'click\', "#rule_button-save-submit-' . $cuttedName . '", function () {
var serArr=JSON.stringify(jQuery("#edit_form_modal").serializeArray());
jQuery.ajax({
url: "' . $this->getUrl("megawidget/conditions_rule/preparedata") . '",
data: { form_key: window.FORM_KEY,serializedArray:serArr},
type: \'post\',
success: function (response) {
console.log(response.data);
jQuery("input[name=\'' . $name . '\']")[0].value=response.data;
},
error: function (response) {
alert(response.message);
console.log(response.message);
}
});
});
});
</script>
']);
$form->setValues($model->getData());
$this->setForm($form);
return parent::_prepareForm();
}

Using setColumns() in Google Charts with a JSON table

Is there a function in the Google Charts API similar to setColumns() that will work on JSON data?
I am trying to minimize PHP calls by combining my data into one array and then specifying to Google Charts which columns to use.
Using the code below I get the error that the function does not exist:
var data = new google.visualization.DataTable(jsonData);
data.setColumns([0,1,2]);
EDIT:
Here are the relevant portions of each file.
Javascript File:
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: "getData.php",
dataType:"json",
async: false
}).responseText;
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
data.setColumns([0,1,2]);
var options = {
width: chartWidth,
height: chartHeight,
backgroundColor: '#FFFFFF',
legend:{
textStyle:{color:'black'}
},
hAxis: {
title: 'Time (EST)',
baselineColor: 'black',
textStyle:{color:'black',fontSize:'9'},
slantedText: true,
slantedTextAngle:45,
titleTextStyle:{color:'black'}
},
vAxis: {
title: 'Temperature(F)',
baselineColor: 'black',
textStyle:{color:'black'},
titleTextStyle:{color:'black'}
},
colors: ['#FF0000', '#005F00']
};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.LineChart(document.getElementById('Tchart_div'));
chart.draw(data, options);
Relevant PHP Code:
// Build an array thats Google Charts Readable ... ... ...
$table=array();
$table['cols'] = array(
// Chart Labels (i.e. column headers)
array('label' => 'dateTime', 'type' => 'string'),
array('label' => 'Temp', 'type' => 'number'),
array('label' => 'Dew', 'type' => 'number'),
array('label' => 'Heat Index', 'type' => 'number'),
array('label' => 'Wind Chill', 'type' => 'number'),
array('label' => 'Pressure', 'type' => 'number'),
array('label' => 'Radiation', 'type' => 'number'),
array('label' => 'UV Index', 'type' => 'number'),
array('label' => 'WindSpeed', 'type' => 'number'),
array('label' => 'WindGustSpeed', 'type' => 'number')
);
$rows = array();
while($r = mysql_fetch_assoc($query))
{
$mdat = $r['dateTime'];
if ( ($mdat % 900) == 0) // If it's within our interval, save the data
{
// Date/Time
$tdat = new DateTime("#$mdat");
$tdat->setTimeZone(new DateTimeZone('America/New_York'));
$rdat = $tdat->format('H:i');
//Temp/Dew
$Tdat = $r['outTemp'];
$Tdat = number_format($Tdat, 2, '.', '');
$Ddat = $r['dewpoint'];
$Ddat = number_format($Ddat, 2, '.', '');
//Heat Index/Wind Chill
$HIdat = $r['heatindex'];
$HIdat = number_format($pdat, 2, '.', '');
$WCdat = $r['windchill'];
$WCdat = number_format($wdat, 2, '.', '');
//Pressure
$Pdat = $r['barometer'];
if ($Pdat == 0)
{
$Pdat = 29.92;
}
$Pdat = $Pdat * 33.8637526;
$Pdat = number_format($Pdat, 2, '.', '');
//Solar
$RADdat = $r['radiation'];
$RADdat = number_format($RADdat, 2, '.', '');
$Udat = $r['UV'];
//Wind
$Wdat = $r['windSpeed'];
$Wdat = number_format($Wdat, 2, '.', '');
$Gdat = $r['windGust'];
// Now save everything in an array...
$temp = array();
$temp[] = array('v' => (string) $rdat); //Time
$temp[] = array('v' => (float) $Tdat); //Temp
$temp[] = array('v' => (float) $Ddat); //Dewp
$temp[] = array('v' => (float) $HIdat); //Heat Index
$temp[] = array('v' => (float) $WCdat); //Wind Chill
$temp[] = array('v' => (float) $Pdat); //Pressure
$temp[] = array('v' => (float) $RADdat); //Solar Radiation
$temp[] = array('v' => (float) $Udat); //UV Index
$temp[] = array('v' => (float) $Wdat); //Wind Speed
$temp[] = array('v' => (float) $Gdat); //Wind Gusts
// Make the previous array a row in this new array
$rows[] = array('c' => $temp);
}
}
$table['rows'] = $rows; // Build a table out of the rows array
$jsonTable = json_encode($table); //encode the table into the json format
So in a nutshell, I want to tell the Charts API to only select certain fields from the JSON table
Instead of data.setColumns([0,1,2]);you should use setView.
data.setView({columns:[0,1,2]});
You are probably looking for setColumns function of DataView Class. In that case the following example demonstrates how to set visible columns in Google Chart:
google.load("visualization", "1.1", { packages: ["table"] });
google.setOnLoadCallback(drawTable);
function drawTable() {
getWeatherData(function (data) {
var table = new google.visualization.Table(document.getElementById('table_div'));
table.draw(data, { showRowNumber: true, width: '100%', height: '100%' });
});
}
function getWeatherData(complete) {
$.getJSON('https://gist.githubusercontent.com/vgrem/2d1436388ae8872f149d/raw/7193623c50cf2e093989391182aa67aaf8fdad2b/WeatherData.json', function (json) {
var dataTable = new google.visualization.DataTable(json);
var dataView = new google.visualization.DataView(dataTable);
dataView.setColumns([0,1,2]);
complete(dataView);
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<div id="table_div"></div>
WeatherData.json

ajax function outputs a "0" when I use die() at the end

I have a php page that is making a couple of ajax calls. The first ajax call is made and on success it activates a second ajax function. Each function has die() at the end. No matter what I do, die() keeps outputting a "0" to the screen. I tried commenting the die() out of the first ajax function, but it never processes the ajax request when I do that. The loading gif just keeps spinning. When I comment out the die() in the second function, it outputs "0" twice. I have no clue why it keeps printing that to the screen.
This is the first function.
function json_info() {
// The $_REQUEST contains all the data sent via ajax
if ( isset($_REQUEST) ) {
// create a new array to store projects
$projectsArray = array();
// get values for all three drop-down menus
$status = $_REQUEST['status'];
$industry = $_REQUEST['services'];
$state = $_REQUEST['state'];
// array of values for earch of the three drop-downs
$statusAll = array('complete','incomplete');
$industryAll = array('mining','textile','construction');
$statesAll = array('sc','tx','wa');
// set $statusArray dependent on whether or not "all" is selected
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);
$projectsArray = array();
if($my_query->have_posts()) :
while($my_query->have_posts()) :
$my_query->the_post();
$image = get_field('project_photo');
$image = $image['sizes']['thumbnail'];
$projectsArray[] = array(
'title' => get_the_title(),
'lat' => get_field('latitude'),
'long' => get_field('longitude'),
'status' => get_field('status'),
'industry' => get_field('industry'),
'state' => get_field('state'),
'link' => get_permalink(),
'photo' => $image,
'num' => $paged
);
endwhile; endif;
wp_reset_query();
} // end of isset
?>
<?php
echo json_encode($projectsArray);
// Always die in functions echoing ajax content
die();
}
add_action( 'wp_ajax_json_info', 'json_info' );
add_action( 'wp_ajax_nopriv_json_info', 'json_info' );
And this is the second 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 earch of the three drop-downs
$statusAll = array('complete','incomplete');
$industryAll = array('mining','textile','construction');
$statesAll = array('sc','tx','wa');
// set $statusArray dependent on whether or not "all" is selected
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 class="group">
<?php the_title(); ?>
</li>
<?php
endwhile;endif;
wp_reset_query();
} // end of isset
?>
<?php
// Always die in functions echoing ajax content
die();
}
add_action( 'wp_ajax_json_info2', 'json_info2' );
add_action( 'wp_ajax_nopriv_json_info2', 'json_info2' );
And this is the ajax call to both functions:
function run_ajax() {
// Get values from all three dropdown menus
var state = $('#states').val();
var markets = $('#markets').val();
var services = $('#services').val();
// This does the ajax request
$.ajax({
url: ajaxurl,
data: {
'action' : 'json_info',
'state' : state,
'status' : markets,
'services' : services
},
success:function(data) {
// This outputs the result of the ajax request
var jsonData = JSON.parse(data);
do_ajax();
} /*,
error: function(errorThrown){
console.log(errorThrown);
}*/
}); // end of ajax call for json_info
function do_ajax() {
$.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
}
I'm not sure what I'm missing or doing wrong that is causing the "0" to print to the screen.
Well, it turns out that I'm an idiot, and I was just overlooking the problem. There was a third function called by ajax, and I didn't have die() at the end of it. I was thinking the issue was in my second function since the 0 was showing up in the div where I was printing that content.

Yii+datepicker boostrap how update grid

I have the following problem. I have a city that I want to put two boxes Dates (From-To). When selecting a period of time I want to update the grid, but right here is the problem. Here's my code so far
$dateisOn = CHtml::textField('Event[from_date]', '',
array('id' => 'from', 'data-date-format' => 'yyyy-mm-dd')) .
' До ' . CHtml::textField('Event[from_date]', '',
array('id' => 'to', 'data-date-format' => 'yyyy-mm-dd'));
$this->widget('ext.widgets.StyledGridWidget', array(
'id' => 'event-grid',
'dataProvider' => $model->search(),
'enablePagination' => false,
'filter' => $model,
'columns' => array(
array(
'name' => 'product_id',
'value' => '$data->product_id'
),
array(
'name' => 'cnt',
'header' => 'Брой',
'value' => '$data->cnt'
),
array(
'name' => 'code',
'value' => '$data->code'
),
array(
'name' => 'date',
'filter' => $dateisOn,
),
),
));
Here is js datepicker:
var checkin = $('#from').datepicker({
onRender: function(date) {
}
}).on('changeDate', function(ev) {
var newDate = new Date(ev.date);
newDate.setDate(newDate.getDate() + 1);
checkout.setValue(newDate);
checkin.hide();
$('#to')[0].focus();
}).data('datepicker');
var checkout = $('#to').datepicker({
onRender: function(date) {
}
}).on('changeDate', function(ev) {
checkout.hide();
}).data('datepicker');
And this is a my model function search
public function search() {
//var_dump($this->date_first); exit;
$criteria = new CDbCriteria;
$criteria->with = (array('order', 'product'));
$criteria->compare('product.id', $this->product_id);
$criteria->compare('product.code', $this->code);
$criteria->compare('cnt', $this->cnt);
$criteria->select = 'count(t.product_id) AS cnt, t.product_id, product.code';
$criteria->order = 'cnt DESC';
$criteria->group='t.product_id';
$criteria->limit = 10;
if (!empty($this->from_date) && empty($this->to_date)) {
$criteria->condition = "order.updated_at >= '$this->from_date'";
} elseif (!empty($this->to_date) && empty($this->from_date)) {
$criteria->condition = "order.updated_at <= '$this->to_date'";
} elseif (!empty($this->to_date) && !empty($this->from_date)) {
$criteria->condition = "order.updated_at >= '$this->from_date' and order.updated_at <= '$this->to_date'";
}
$criteria->together = true;
return new CActiveDataProvider($this, array(
'criteria' => $criteria,
));
}
First, you should fix the to_date field :
$dateisOn = CHtml::textField('Event[from_date]', '',
array('id' => 'from', 'data-date-format' => 'yyyy-mm-dd')) .
' До ' . CHtml::textField('Event[to_date]', '',
array('id' => 'to', 'data-date-format' => 'yyyy-mm-dd'));
You could also modify your search function, you can simply use :
$criteria->compare('order.updated_at', '>='.$this->from_date);
$criteria->compare('order.updated_at', '<='.$this->to_date);

Categories