Not display NULL value in multi-axis chart - php

I am using multi-axis chart from Highcharts.
It works fine but I don't want to display my variable if it’s NULL , where should I put the test on the NULL value ?
I have done it in a pie chart but now with all this arrays I am lost
my multi-axis chart function which took an array composed of years and 4 arrays:
public function multiAxeChartDyn($date, $list1, $list2,$list3,$list4)
{
$dates = $date;
$ob = new Highchart();
$ob->chart->renderTo('containerMultiaxe'); // The #id of the div where to render the chart
$ob->chart->type('column');
$ob->title->text('Budget');
$ob->xAxis->categories($dates);
$ob->legend->enabled(true);
$dataSeries= array(
$list1,
$list2,
$list3,
$list4,
);
$yData = array(
array(
'labels' => array(
'formatter' => new Expr('function () { return this.value + " %" }'),
'style' => array('color' => '#AA4643')
),
'title' => array(
'text' => 'Taux',
'style' => array('color' => '#AA4643')
),
'opposite' => true,
),
array(
'labels' => array(
'formatter' => new Expr('function () { return this.value + " mDT" }'),
'style' => array('color' => '#4572A7')
),
'gridLineWidth' => 0,
'title' => array(
'text' => 'Budget',
'style' => array('color' => '#4572A7')
),
),
);
$ob->yAxis($yData);
$formatter = new Expr('function () {
var unit = {
"Budget": "mDT",
"Ressource": "mDT",
"Taux global": "%",
"Taux Consumption": "%"
}[this.series.name];
return this.x + ": <b>" + this.y + "</b> " + unit;
}');
$ob->tooltip->formatter($formatter);
$ob->series( $dataSeries);
return $ob;
}
my controller :
public function indexAction(Survey $survey)
{
$chart=new ChartController();
$ent = $survey ->getEnt();
$year= $survey->getYear();
$qb = $this->getDoctrine()->getManager()->createQueryBuilder();
$qb->select('e')
->from('AppBundle:Survey, 'e')
->where('e.year <= :year')
->andWhere('e.ent = :ent')
->setParameter('year', $year)
->setParameter('ent', $ent->getId())
->orderBy('e.year', 'DESC')
->setMaxResults(4);
$survey_year = $qb->getQuery()->getResult();
$date = array();
$data1 = array();
$data2 = array();
$data3 = array();
$data4 = array();
$survey_year= array_reverse($survey_year, true);
foreach($survey_year as $ea){
$date[] = $ea->getyear();
$data1[] = $ea->getForm ()->getBudget()/1000;
$data2[] = $ea->getForm ()->getRessources()/1000;
$data3[] = $ea->getForm ()->getTauxGlobal ();
$data4[] = $ea->getForm ()->getTauxConsumption ();
}
$list1= array(
'name' => 'Budget',
'type' => 'column',
'color' => '#4572A7',
'yAxis' => 1,
'dataLabels' => array(
'enabled' => true
),
'data' => $data1
);
$list2 = array(
'name' => 'Ressource',
'type' => 'column',
'color' => '#D49EDA',
'yAxis' => 1,
'dataLabels' => array(
'enabled' => true
),
'data' => $data2
);
$list3= array(
'name' => 'Taux global',
'type' => 'spline',
'color' => '#0A0F19',
'dataLabels' => array(
'enabled' => true
),
'data' => $data3
);
$list4 = array(
'name'=> 'Taux Consumption',
'type' => 'spline',
'color' => '#225824',
'dataLabels' => array(
'enabled' => true
),
'data' => $data4
);
$containermultiaxe=$chart->multiAxeChartDyn($date, $list1, $list2,$list3,$list4);
$html = $this->render('AppBundle:Charting:index.html.twig',array(
'survey' =>$survey,
'containerMultiaxe' => $containermultiaxe,
));
return $html;
}

Related

CGridView in yii 1.1 sorts date as number rather than date

Well Im new to YII 1.1 framework and I have to debug a code.Here the widget CGridView sorts date as number rather than date. That is 01-02-2017,10-01-2017,15-01-2017,21-12-2016.
It should sort with month and year that is 21-12-2016,10-01-2017,15-01-2017,01-02-2017.
My code for view is following :-
<article class="listBox list-view">
<?php
$this->widget('zii.widgets.grid.CGridView', array(
'id' => 'child-invoice-payments-grid',
'htmlOptions' => array('class' => 'table-responsive'),
'itemsCssClass' => 'table invoiceTable',
'summaryText' => '',
'dataProvider' => new CArrayDataProvider($response, array(
'id' => 'id',
'sort' => array(
//'defaultOrder'=>'date_of_payment ASC',
'attributes' => array(
'date_of_payment','id', 'payment_mode','type','amount'
)
),
'pagination' => array(
'pageSize' => 10
)
)),
'enablePagination' => true,
'pagerCssClass' => 'text-center',
'pager' => array(
'header' => '',
'maxButtonCount' => 4,
'firstPageLabel' => '<<',
'prevPageLabel' => '<',
'nextPageLabel' => '>',
'lastPageLabel' => '>>',
'pageSize' => 5,
'htmlOptions' => array(
'class' => 'pagination',
)
),
'columns' => array(
array(
'name' => 'id',
'type' => 'raw',
'header' => 'Transaction ID',
'value' => 'CHtml::link($data["id"], $data["url"])'
),
**array(
'name' => 'date_of_payment',
'type' => 'raw',
'header' => 'Payment Date',
'value' => 'CHtml::link($data["date_of_payment"], $data["url"])'
)**,
array(
'name' => 'payment_mode',
'type' => 'raw',
'header' => 'Payment Mode',
'value' => 'CHtml::link($data["payment_mode"], $data["url"])'
),
array(
'name' => 'type',
'type' => 'raw',
'header' => 'Payment Type',
'value' => 'CHtml::link($data["type"], $data["url"])'
),
array(
'name' => 'amount',
'type' => 'raw',
'header' => 'Amount',
'value' => 'CHtml::link($data["amount"], $data["url"])'
)
)
));
?>
</article>
and the code for the controller is as follows :-
public function actionPayments($child_id) {
$response = array();
$criteria = new CDbCriteria();
$criteria->condition = "child_id = :child_id AND (invoice_type = 0 OR invoice_type = 1)";
$criteria->params = array(':child_id' => $child_id);
$invoiceModel = ChildInvoice::model()->findAll($criteria);
if (!empty($invoiceModel)) {
foreach ($invoiceModel as $invoice) {
$transactionModel = ChildInvoiceTransactions::model()->findAllByAttributes(array(
'invoice_id' => $invoice->id, 'credit_note_id' => NULL, 'payment_id' => NULL));
if (!empty($transactionModel)) {
foreach ($transactionModel as $transaction) {
$temp = array();
$temp['id'] = "Invoice Payment-" . $transaction->id;
$temp['amount'] = $transaction->paid_amount;
$temp['date_of_payment'] = $transaction->date_of_payment;
$temp['payment_mode'] = customFunctions::getPaymentOptionName($transaction->payment_mode);
$temp['type'] = "Invoice Payment";
$temp['url'] = Yii::app()->createUrl('childInvoice/view', array('child_id' => $invoice->child_id,
'invoice_id' => $invoice->id));
$response[] = $temp;
}
}
}
}
$creditNotesModel = ChildInvoice::model()->findAllByAttributes(array('child_id' => $child_id,
'invoice_type' => 3, 'is_deposit' => 1), array('order' => 'invoice_date'));
if (!empty($creditNotesModel)) {
foreach ($creditNotesModel as $creditNote) {
$temp = array();
$temp['id'] = "Credit Note-" . $creditNote->invoiceUrn;
$temp['amount'] = sprintf("%0.2f", -$creditNote->total);
$temp['date_of_payment'] = $creditNote->invoice_date;
$temp['payment_mode'] = $creditNote->description;
$temp['type'] = "Deposit";
$temp['url'] = Yii::app()->createUrl('childInvoice/updateCreditNote', array(
'id' => $creditNote->id, 'child_id' => $creditNote->child_id));
$response[] = $temp;
}
}
$paymentsModel = Payments::model()->findAllByAttributes(array('branch_id' => Yii::app()->session['branch_id']), array(
'order' => 'date_of_payment'));
if (!empty($paymentsModel)) {
foreach ($paymentsModel as $payments) {
if (in_array($child_id, explode(",", $payments->child_id))) {
$temp = array();
$temp['id'] = "Payment-" . $payments->id;
$temp['amount'] = sprintf("%0.2f", $payments->amount);
$temp['date_of_payment'] = $payments->date_of_payment;
$temp['payment_mode'] = customFunctions::getPaymentOptionName($payments->payment_mode);
$temp['type'] = "Payments";
$temp['url'] = Yii::app()->createUrl('payments/view', array('id' => $payments->id));
$response[] = $temp;
}
}
}
usort($response, function($i, $j) {
$a = strtotime(date("Y-m-d", strtotime($i['date_of_payment'])));
$b = strtotime(date("Y-m-d", strtotime($j['date_of_payment'])));
if ($a == $b)
return 0;
elseif ($a > $b)
return 1;
else
return -1;
});
$this->render('payments', array(
'**response**' => $response,
));
}
So the response array which looks like this will have to be formated :-
[0] => Array
(
[id] => Payment-8
[amount] => 100.00
[date_of_payment] => 06-03-2017
[payment_mode] => Cash
[type] => Payments
[url] => /new_management/index.php/payments/8
)
[1] => Array
(
[id] => Payment-12
[amount] => 1500.00
[date_of_payment] => 22-03-2017
[payment_mode] => Bank/Standing Order
[type] => Payments
[url] => /new_management/index.php/payments/12
)
[2] => Array
(
[id] => Payment-14
[amount] => 150.00
[date_of_payment] => 27-03-2017
[payment_mode] => Cheque
[type] => Payments
[url] => /new_management/index.php/payments/14
)
Below is screenshot of the page and the problem :-
enter image description here

Prestashop HelpForm type switch in module

I want create a input type switch in my backend module in prestashop 1.6.
I write this and work
array(
'type' => 'switch',
'label' => $this->l('Label'),
'name' => 'PRESTASHOP_INPUT_SWITCH',
'is_bool' => true,
'desc' => $this->l('Description'),
'values' => array(
array(
'id' => 'active_on',
'value' => true,
'label' => $this->l('Enabled')
),
array(
'id' => 'active_off',
'value' => false,
'label' => $this->l('Disabled')
)
),
)
But if i try with custom value e not boolean it not work
array(
'type' => 'switch',
'label' => $this->l('Label'),
'name' => 'PRESTASHOP_INPUT_SWITCH',
'is_bool' => false,
'desc' => $this->l('Description'),
'values' => array(
array(
'id' => 'value1',
'value' => 'value1',
'label' => $this->l('value1')
),
array(
'id' => 'value2',
'value' => 'value2',
'label' => $this->l('value2')
)
),
)
In backend appear two boxes with labels value 'no'.
In HelperForm classes of prestashop there is no trace of input type switch.
The same code with type radio work, but i want a switch type.
Unfortunately, as you can see here:
PrestaShop doesn't have possibility to use custom value in "switch" field.
You don't need to change default switch values.
This is how you handle submit form:
public function getContent()
{
if (Tools::isSubmit('submitForm'))
{
$my_value = ( (int)Tools::getValue('PRESTASHOP_INPUT_SWITCH') == 1 ) ? 'value1' : 'value2';
if (Configuration::updateValue('PRESTASHOP_INPUT_SWITCH', $my_value))
$echo .= $this->displayConfirmation($this->l('Value updated.'));
}
$echo .= $this->renderForm();
return $echo;
}
You probably already have something like this:
public function renderForm()
{
$fields_form = array(
'form' => array(
'legend' => array(
'title' => $this->l('Settings'),
'icon' => 'icon-cogs'
),
'input' => array(
array(
'type' => 'switch',
'label' => $this->l('Label'),
'name' => 'PRESTASHOP_INPUT_SWITCH',
'is_bool' => true,
'desc' => $this->l('Description'),
'values' => array(
array(
'id' => 'active_on',
'value' => 1,
'label' => $this->l('Value1')
),
array(
'id' => 'active_off',
'value' => 0,
'label' => $this->l('Value2')
)
),
)
),
'submit' => array(
'title' => $this->l('Save'),
)
),
);
$helper = new HelperForm();
$helper->module = $this;
$helper->show_toolbar = false;
$helper->table = $this->table;
$lang = new Language((int)Configuration::get('PS_LANG_DEFAULT'));
$helper->default_form_language = $lang->id;
$helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') ? Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') : 0;
$this->fields_form = array();
$helper->identifier = $this->identifier;
$helper->submit_action = 'submitForm';
$helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false).'&configure='.$this->name.'&tab_module='.$this->tab.'&module_name='.$this->name;
$helper->token = Tools::getAdminTokenLite('AdminModules');
$helper->tpl_vars = array(
'fields_value' => $this->getConfigFieldsValues(),
'languages' => $this->context->controller->getLanguages(),
'id_language' => $this->context->language->id
);
return $helper->generateForm(array($fields_form));
}
and loading the values:
public function getConfigFieldsValues()
{
return array(
'PRESTASHOP_INPUT_SWITCH' => Tools::getValue('PRESTASHOP_INPUT_SWITCH', Configuration::get('PRESTASHOP_INPUT_SWITCH') == 'value1' : 1 : 0),
);
}
Unfortunately prestashop doesn't support the custom value of switch but you can handle this like:
$config = Configuration::get('oneclickcheckout');
$this->settings = Tools::unSerialize($config);
$settings = $this->settings;
if (isset($settings['Description']) && $settings['Description'] == 1) {
}

Prestashop custom field in Product Feature not saving on Edit

I have created a custom field for Product Feature in my module override. Custom field for Feature is not saving in the database on edit. But on Add new feature it works fine. Here is the code for my AdminFeaturesController.php file:
<?php
class AdminFeaturesController extends AdminFeaturesControllerCore
{
public function __construct()
{
$this->table = 'feature';
$this->className = 'Feature';
$this->list_id = 'feature';
$this->identifier = 'id_feature';
$this->lang = true;
$this->fields_list = array(
'id_feature' => array(
'title' => $this->l('ID'),
'align' => 'center',
'class' => 'fixed-width-xs'
),
'name' => array(
'title' => $this->l('Name'),
'width' => 'auto',
'filter_key' => 'b!name'
),
'value' => array(
'title' => $this->l('Values'),
'orderby' => false,
'search' => false,
'align' => 'center',
'class' => 'fixed-width-xs'
),
'parent_id_feature' => array(
'title' => $this->l('ParentID'),
'align' => 'center',
'class' => 'fixed-width-xs'
),
'position' => array(
'title' => $this->l('Position'),
'filter_key' => 'a!position',
'align' => 'center',
'class' => 'fixed-width-xs',
'position' => 'position'
)
);
$this->bulk_actions = array(
'delete' => array(
'text' => $this->l('Delete selected'),
'icon' => 'icon-trash',
'confirm' => $this->l('Delete selected items?')
)
);
AdminController::__construct();
}
/**
* AdminController::renderForm() override
* #see AdminController::renderForm()
*/
public function renderForm()
{
$this->toolbar_title = $this->l('Add a new feature');
$this->fields_form = array(
'legend' => array(
'title' => $this->l('Feature with Parent'),
'icon' => 'icon-info-sign'
),
'input' => array(
array(
'type' => 'text',
'label' => $this->l('Name'),
'name' => 'name',
'lang' => true,
'size' => 33,
'hint' => $this->l('Invalid characters:').' <>;=#{}',
'required' => true
),
array(
'type' => 'select',
'label' => $this->l('Parent Feature'),
'name' => 'parent_id_feature',
'options' => array(
'query' => Feature::getFeaturesExcept($this->context->language->id, Tools::getValue('id_feature')),
'id' => 'id_feature',
'name' => 'name'
),
'required' => true
)
)
);
if (Shop::isFeatureActive())
{
$this->fields_form['input'][] = array(
'type' => 'shop',
'label' => $this->l('Shop association'),
'name' => 'checkBoxShopAsso',
);
}
$this->fields_form['submit'] = array(
'title' => $this->l('Save'),
);
return AdminController::renderForm();
}
public function renderView()
{
if (($id = Tools::getValue('id_feature')))
{
$this->setTypeValue();
$this->list_id = 'feature_value';
$this->position_identifier = 'id_feature_value';
$this->position_group_identifier = 'id_feature';
$this->lang = true;
// Action for list
$this->addRowAction('edit');
$this->addRowAction('delete');
if (!Validate::isLoadedObject($obj = new Feature((int)$id)))
{
$this->errors[] = Tools::displayError('An error occurred while updating the status for an object.').'
<b>'.$this->table.'</b> '.Tools::displayError('(cannot load object)');
return;
}
$this->feature_name = $obj->name;
$this->toolbar_title = $this->feature_name[$this->context->employee->id_lang];
$this->fields_list = array(
'id_feature_value' => array(
'title' => $this->l('ID'),
'align' => 'center',
'class' => 'fixed-width-xs'
),
'value' => array(
'title' => $this->l('Value')
),
'parent_id_feature_value' => array(
'title' => $this->l('ParentID'),
'align' => 'center',
'class' => 'fixed-width-xs'
),
'position' => array(
'title' => $this->l('Position'),
'filter_key' => 'a!position',
'align' => 'center',
'class' => 'fixed-width-xs',
'position' => 'position'
)
);
$this->_where = sprintf('AND `id_feature` = %d', (int)$id);
$this->_orderBy = 'position';
self::$currentIndex = self::$currentIndex.'&id_feature='.(int)$id.'&viewfeature';
$this->processFilter();
return AdminController::renderList();
}
}
/**
* AdminController::renderForm() override
* #see AdminController::renderForm()
*/
public function initFormFeatureValue()
{
$this->setTypeValue();
$parent_id = Feature::getParentFeatureID((int)Tools::getValue('id_feature'));
$this->fields_form[0]['form'] = array(
'legend' => array(
'title' => $this->l('Feature value'),
'icon' => 'icon-info-sign'
),
'input' => array(
array(
'type' => 'select',
'label' => $this->l('Feature'),
'name' => 'id_feature',
'options' => array(
'query' => Feature::getFeatures($this->context->language->id),
'id' => 'id_feature',
'name' => 'name'
),
'required' => true
),
array(
'type' => 'text',
'label' => $this->l('Value'),
'name' => 'value',
'lang' => true,
'size' => 33,
'hint' => $this->l('Invalid characters:').' <>;=#{}',
'required' => true
),
array(
'type' => 'select',
'label' => $this->l('Parent Feature Value'),
'name' => 'parent_id_feature_value',
'options' => array(
'query' => FeatureValue::getFeatureValuesWithLang($this->context->language->id, $parent_id),
'id' => 'id_feature_value',
'name' => 'value'
),
'required' => true
),
),
'submit' => array(
'title' => $this->l('Save'),
),
'buttons' => array(
'save-and-stay' => array(
'title' => $this->l('Save then add another value'),
'name' => 'submitAdd'.$this->table.'AndStay',
'type' => 'submit',
'class' => 'btn btn-default pull-right',
'icon' => 'process-icon-save'
)
)
);
$this->fields_value['id_feature'] = (int)Tools::getValue('id_feature');
// Create Object FeatureValue
$feature_value = new FeatureValue(Tools::getValue('id_feature_value'));
$this->tpl_vars = array(
'feature_value' => $feature_value,
);
$this->getlanguages();
$helper = new HelperForm();
$helper->show_cancel_button = true;
$back = Tools::safeOutput(Tools::getValue('back', ''));
if (empty($back))
$back = self::$currentIndex.'&token='.$this->token;
if (!Validate::isCleanHtml($back))
die(Tools::displayError());
$helper->back_url = $back;
$helper->currentIndex = self::$currentIndex;
$helper->token = $this->token;
$helper->table = $this->table;
$helper->identifier = $this->identifier;
$helper->override_folder = 'feature_value/';
$helper->id = $feature_value->id;
$helper->toolbar_scroll = false;
$helper->tpl_vars = $this->tpl_vars;
$helper->languages = $this->_languages;
$helper->default_form_language = $this->default_form_language;
$helper->allow_employee_form_lang = $this->allow_employee_form_lang;
$helper->fields_value = $this->getFieldsValue($feature_value);
$helper->toolbar_btn = $this->toolbar_btn;
$helper->title = $this->l('Add a new feature value');
$this->content .= $helper->generateForm($this->fields_form);
}
public function ajaxProcessUpdatePositions()
{
if ($this->tabAccess['edit'] === '1')
{
$way = (int)Tools::getValue('way');
$id = (int)Tools::getValue('id');
$table = 'feature';
$positions = Tools::getValue($table);
if (empty($positions))
{
$table = 'feature_value';
$positions = Tools::getValue($table);
}
$new_positions = array();
foreach ($positions as $v)
if (!empty($v))
$new_positions[] = $v;
foreach ($new_positions as $position => $value)
{
$pos = explode('_', $value);
if (isset($pos[2]) && (int)$pos[2] === $id)
{
if ($table == 'feature')
{
if ($feature = new Feature((int)$pos[2]))
if (isset($position) && $feature->updatePosition($way, $position, $id))
echo 'ok position '.(int)$position.' for feature '.(int)$pos[1].'\r\n';
else
echo '{"hasError" : true, "errors" : "Can not update feature '.(int)$id.' to position '.(int)$position.' "}';
else
echo '{"hasError" : true, "errors" : "This feature ('.(int)$id.') can t be loaded"}';
break;
}
elseif ($table == 'feature_value')
{
if ($feature_value = new FeatureValue((int)$pos[2]))
if (isset($position) && $feature_value->updatePosition($way, $position, $id))
echo 'ok position '.(int)$position.' for feature value '.(int)$pos[2].'\r\n';
else
echo '{"hasError" : true, "errors" : "Can not update feature value '.(int)$id.' to position '.(int)$position.' "}';
else
echo '{"hasError" : true, "errors" : "This feature value ('.(int)$id.') can t be loaded"}';
break;
}
}
}
}
}
}
And my Feature.php is:
<?php
class Feature extends FeatureCore
{
/** #var string Name */
public $parent_id_feature;
/**
* #see ObjectModel::$definition
*/
public static $definition = array(
'table' => 'feature',
'primary' => 'id_feature',
'multilang' => true,
'fields' => array(
'position' => array('type' => self::TYPE_INT, 'validate' => 'isInt'),
// Parent Feature ID
'parent_id_feature' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId', 'required' => false),
// Lang fields
'name' => array('type' => self::TYPE_STRING, 'lang' => true, 'validate' => 'isGenericName', 'required' => true, 'size' => 128),
)
);
/**
* Get a parent feature id for a given id_feature
*
* #param integer $id_feature Feature id
* #return integer ID of parent feature
* #static
*/
public static function getParentFeatureID($id_feature)
{
return Db::getInstance()->getValue('
SELECT parent_id_feature
FROM `'._DB_PREFIX_.'feature` f
WHERE f.`id_feature` = '.(int)$id_feature
);
}
/**
* Get all features for a given language except for given id
*
* #param integer $id_lang Language id
* #param integer $id_feature Feature id to exclude
* #return array Multiple arrays with feature's data
* #static
*/
public static function getFeaturesExcept($id_lang, $id_feature, $with_shop = true)
{
return Db::getInstance()->executeS('
SELECT DISTINCT f.id_feature, f.*, fl.*
FROM `'._DB_PREFIX_.'feature` f
'.($with_shop ? Shop::addSqlAssociation('feature', 'f') : '').'
LEFT JOIN `'._DB_PREFIX_.'feature_lang` fl ON (f.`id_feature` = fl.`id_feature` AND fl.`id_lang` = '.(int)$id_lang.')
WHERE f.id_feature != '.(int)$id_feature.'
ORDER BY f.`position` ASC');
}
}

Sort array and rebuild it

I have this array:
$all = array(
'meat' => Object(
'name' => 'meat',
'color' => 'red',
'class' => 'food'
),
'chicken' => Object(
'name' => 'chicken',
'color' => 'white',
'class' => 'food'
),
'apple' => Object(
'name' => 'apple',
'color' => 'green',
'class' => 'Fruit'
),
'blueberry' => Object(
'name' => 'blueberry',
'color' => 'blue',
'class' => 'Fruit'
)
);
and i want to Sort it and rebuild it to be like this:
$theright = array(
array(
'class' => 'food',
'menu' => array(
array(
'name' => 'meat',
'color' => 'red',
),
array(
'name' => 'chicken',
'color' => 'white',
)
)
),
array(
'class' => 'Fruit',
'menu' => array(
array(
'name' => 'apple',
'color' => 'green',
),
array(
'name' => 'blueberry',
'color' => 'blue',
)
)
)
);
I tried to Collect all classes in$all array then compare each value with $all array:
$classArray = array();
foreach($all as $key => $value) {
$classArray[$value->class] = array();
}
foreach($classArray as $key => $value) {
$theright[] = array('class' => $key, 'menu' => array());
}
this code get me this array:
$theright = array(
array(
'class' => 'food',
'menu' => array()
),
array(
'class' => 'Fruit',
'menu' => array()
)
);
and i stop here , how to complete it ?
You could just use the class as a key to group them together. Example:
$food = array();
// gather class
foreach($all as $item) {
if(!isset($food[$item->class])) {
$food[$item->class] = array(
'class' => $item->class,
'menu' => array(
array(
'name' => $item->name,
'color' => $item->name,
)
)
);
} else {
$food[$item->class]['menu'][] = array('name' => $item->name,'color' => $item->color,);
}
}
// simple reindex
$food = array_values($food);
There is no need for a second loop. This should do what you want.
$classMap = array();
foreach ($all as $item)
{
// check if class has been created in the class map
if ( ! array_key_exists($classMap, $item['class']))
{
$classMap[$item['class']] = array(
'class' => $item['class'],
'menu' => array()
);
}
$classMap[$item['class']]['menu'][] = array(
'name' => $item['name'],
'color' => $item['color']
);
}
Try with less loop counts (2)
$all = [];
function getSelectClassData(array &$all)
{
$finalArr = [];
while (count($all) > 1) {
$res = [];
$class = array_values($all)[0]->class;
$selectedDataArr = getSelectSimilerMenuData($all, $class);
$res['class'] = $class;
$res['menu'] = array_values($selectedDataArr);
$all = array_diff_key($all,array_flip(array_keys($selectedDataArr)));
$finalArr[] = $res;
}
return $finalArr;
}
function getSelectSimilerMenuData(array $all, $class)
{
return array_filter(
$all,
function ($e) use ($class) {
return $e->class == $class;
}
);
}
print_r(getSelectClassData($all));

Cakephp 2.4.1, using CakeDS Search plugin Array to string conversion,searching between dates

I trying to search between dates using the CakeDc plugin. I am trying to use 2 separate form fields in the form/view, 1 for start date and the other for end date.
I need to have a single array so I can use the function CreationDateRangeCondition in the controller (unless this can be sorted somehow in the controller function) but I don't know how to do this. I am trying to learn PHP and Cakephp
Controller:
public $presetVars = array(
array('creationDateBetween' => 'created', 'type' => 'value'),
);
public function index() {
$this->Prg->commonProcess();
$this->paginate = array(
'conditions' => $this->Post->parseCriteria($this->passedArgs));
$this->set('posts', $this->paginate());
}
Model:
public $actsAs = array('Search.Searchable');
public $filterArgs = array(
'creationDateBetween' => array(
'type' => 'expression',
'method' => 'CreationDateRangeCondition',
'field' => 'Post.created BETWEEN ? AND ?',
),
);
public function CreationDateRangeCondition($data = array()){
if(strpos($data['creationDateBetween'], ' - ') !== false){
$tmp = explode(' - ', $data['creationDateBetween']);
$tmp[0] = $tmp[0]."-01-01";
$tmp[1] = $tmp[1]."-12-31";
return $tmp;
}else{
return array($data['creationDateBetween']."-01-01", $data['creationDateBetween']."-12-31");
}
}
View:
<?php
echo $this->Form->create('Post', array(
'url' => array_merge(array('action' => 'index'), $this->params['pass'])
));
echo $this->Form->input('creationDateBetween', array(
'type' => 'date',
'div' => false,
'dateFormat' => 'DMY',
'minYear' => 2013,
'maxYear' => date('Y'),
'style' => 'margin-right: 2px; margin-left: 2px',
'empty' => true,
'timeFormat' => null,
'selected' => array(
'day' => 1,
'month' => 1,
'year' => 2013
),
'empty' => false
));
echo $this->Form->input('creationDateBetween2', array(
'type' => 'date',
'div' => false,
'dateFormat' => 'DMY',
'minYear' => 2013,
'maxYear' => date('Y'),
'empty' => true,
'style' => 'margin-right: 2px; margin-left: 2px',
'timeFormat' => null,
'selected' => array(
'day' => date('D'),
'month' => date('M'),
'year' => date('Y')
),
'empty' => false
));
?>
<?php
echo $this->Form->submit(__('Search', true), array('div' => false));
echo $this->Form->end();
?>
I would do this way:
In your Model
public $filterArgs = array(
'creationDateBetween' => array(
'type' => 'expression',
'method' => 'formatStartDate',
'field' => 'Post.created >= ?'
),
'creationDateBetween2' => array(
'type' => 'expression',
'method' => 'formatEndDate',
'field' => 'Post.created <= ?'
)
);
public function formatStartDate($data = array())
{
$date = implode('-', array($data['creationDateBetween']['year'], $data['creationDateBetween']['month'], $data['creationDateBetween']['day']));
return array($date);
}
public function formatEndDate($data = array())
{
$date = implode('-', array($data['creationDateBetween2']['year'], $data['creationDateBetween2']['month'], $data['creationDateBetween2']['day']));
return array($date);
}

Categories