How to add order key for DynaGrid? - php

I have an ActionColumn for each tables. I need to add order => ORDER_FIX_RIGHT per table for ActionColumn. How can i add order key in my DynaGridViewAdvanced?
I tried to write:
protected function applyColumns()
{
$columns = [];
$newColumns = [];
foreach ($this->columns as $column) {
$order = ArrayHelper::getValue($column, 'order', self::ORDER_MIDDLE);
if ($order == self::ORDER_FIX_LEFT) {
$newColumns[] = $column;
unset($column['order']);
$columns[] = $column;
}
}
foreach ($this->_visibleKeys as $key) {
if (empty($this->_columns[$key])) {
continue;
}
$column = $this->_columns[$key];
$newColumns[] = $column;
if (isset($column['order'])) {
unset($column['order']);
}
if (isset($column['visible'])) {
unset($column['visible']);
}
$columns[] = $column;
}
foreach ($this->columns as $column) {
$order = ArrayHelper::getValue($column, 'order', self::ORDER_MIDDLE);
$isActionColumn = is_array($column) && array_key_exists('class', $column) && (new $column['class']) instanceof ActionColumn;
if ($order == self::ORDER_FIX_RIGHT) {
$newColumns[] = $column;
unset($column['order']);
$columns[] = $column;
}
if ($isActionColumn) {
$column['order'] = self::ORDER_FIX_RIGHT;
$newColumns[] = $column;
unset($column['order']);
$columns[] = $column;
}
}
$this->columns = $newColumns;
$this->gridOptions['columns'] = $columns;
}
But it makes second column. If i write:
protected function prepareColumns()
{
$this->_columns = $this->columns;
$columns = [];
foreach ($this->columns as $column) {
$isActionColumn = is_array($column) && array_key_exists('class', $column) && (new $column['class']) instanceof ActionColumn;
if (is_array($column) && !$isActionColumn) {
unset($column['order']);
}
if ($isActionColumn) {
$column['order'] = $this->actionColumnsPosition;
}
$columns[] = $column;
}
$this->gridOptions['columns'] = $columns;
}
All working fine, but when i change some in columns, i have exception about:
Setting unknown property ...ActionColumn::order

Done. I created method setDefaultOrderToActionColumns with content:
private function setDefaultOrderToActionColumns() {
foreach ($this->columns as &$column) {
$columnTypeIsAction = is_array($column) && array_key_exists('class', $column) && (new $column['class']) instanceof ActionColumn;
if ($columnTypeIsAction) {
$column['order'] = $this->actionColumnsPosition;
}
}
}
And called it in redefined method run:
public function run() {
...
$this->setDefaultOrderToActionColumns();
}

Related

How to join table dynamically in codeigniter?

I want to join table dynamically in codeigniter by passing table name as parameter.
below is my controller function to call model function
function index(){
$table=array('branch'=>'branch_id','specialization'=>'spec_branch_id');
$this->model->join($table);
}
and this is my model function
function join($table){
foreach($table as $table_name=>$table_id){
/*i want here table*/
$table1=$table_name;
}
$this->db->select('*');
$this->db->from(''.$table1.' t1');
$this->db->join(''.$table2.' t2','t1.'.$t1id.'=t2.'.$t2id);
return $this->db->get();
echo $this->db->last_query();die;
}
As in above function i want dynamic table name like table1=branch;
table2=specializaton in my model function, so please help me to solve and if someone have another also can share.
here is my custom code dynamically join.
mode form.
<?php public function commonGet($options) {
$select = false;
$table = false;
$join = false;
$order = false;
$limit = false;
$offset = false;
$where = false;
$or_where = false;
$single = false;
$where_not_in = false;
$like = false;
extract($options);
if ($select != false)
$this->db->select($select);
if ($table != false)
$this->db->from($table);
if ($where != false)
$this->db->where($where);
if ($where_not_in != false) {
foreach ($where_not_in as $key => $value) {
if (count($value) > 0)
$this->db->where_not_in($key, $value);
}
}
if ($like != false) {
$this->db->like($like);
}
if ($or_where != false)
$this->db->or_where($or_where);
if ($limit != false) {
if (!is_array($limit)) {
$this->db->limit($limit);
} else {
foreach ($limit as $limitval => $offset) {
$this->db->limit($limitval, $offset);
}
}
}
if ($order != false) {
foreach ($order as $key => $value) {
if (is_array($value)) {
foreach ($order as $orderby => $orderval) {
$this->db->order_by($orderby, $orderval);
}
} else {
$this->db->order_by($key, $value);
}
}
}
if ($join != false) {
foreach ($join as $key => $value) {
if (is_array($value)) {
if (count($value) == 3) {
$this->db->join($value[0], $value[1], $value[2]);
} else {
foreach ($value as $key1 => $value1) {
$this->db->join($key1, $value1);
}
}
} else {
$this->db->join($key, $value);
}
}
}
$query = $this->db->get();
if ($single) {
return $query->row();
}
return $query->result();
} ?>
and view index page
<?php function index(){
$option = array(
'table' => 't1',
'join' => array('t2' => 't2.id = t1.id')
);
$this->model->commonGet($option);
}?>
You can try this code also for two table join.
Controller function.
function index(){
$table=array('branch'=>'branch_id','specialization'=>'spec_branch_id');
$this->model->join($table);
}
Model function
function join($tables){
$i=1;
foreach($tables as $table_name=>$table_id){
${'table'.$i}=$table_name;
${'t'.$i.'id'}=$table_id;
$i++;
}
$this->db->select('*');
$this->db->from(''.$table1.' t1');
$this->db->join(''.$table2.' t2','t1.'.$t1id.'=t2.'.$t2id);
//$this->output->enable_profiler(TRUE);
return $this->db->get();
}

Sort multidimensional array by another array and complete missing keys in the same order

I'm trying to export data from leads table to excel using PHP/Laravel, the leads table caמ be customized to show specific columns and the export columns should be same as the table columns. the problem is - if column not exists in a specific row the column not shown empty and the 'xls' file is exported really messy...
my code looks like this:
public function excelExport(Request $request, $client_id=null)
{
$client_id = is_null($client_id) ? \Auth::client()->id : $client_id;
if(is_null($this->client_users)){
$this->client_users = $this->clientsController->listClientUsers($client_id);
}
$columns = $this->account_settings->getColumnsDef($client_id);
$query = Lead::select(array_keys($columns))->where('client_id',strval($client_id))->where('deleted',0);
$query = $this->setQueryDates($request,$query,$client_id);
$query = $this->leadsFiltersController->setExportQuery($request,$query);
$arr = $query->get()->toArray();
Excel::create('leads' , function($excel) use ($arr,$columns){
$excel->sheet('Leads' , function($sheet) use ($arr,$columns){
$rows = [];
$count = 0;
foreach($arr as $lead){
$row = $this->setExportRowData($lead,$count,$columns);
$rows[] = $row;
$count++;
}
$sheet->fromArray($rows);
});
})->export('xls');
private function setExportRowData($lead,$count,$columns,$order = true)
{
$row = [];
$order = null;
foreach($lead as $k => $v) {
if (is_array($v)) {
switch (strtolower($k)) {
case "ga_details":
if (count($v) > 2) {
foreach ($v as $key => $ga_detail) {
if ($key != "realTime_data" && $key != "uacid") {
$row[$key] = $ga_detail;
}
}
}
break;
case "status":
if (isset($v['name']) && count($v['name'])) {
$row['status'] = $v['name'];
} else {
$row['status'] = "no status";
}
break;
case "owner":
if (isset($v['owner_id']) && count($v)) {
$row['owner'] = $this->getClientOwnerUserName($this->client_users, $v['owner_id']);
} else {
$row['owner'] = "no owner";
}
break;
case "prediction":
if (isset($v['score']) && count($v)) {
$row['prediction'] = $v['score'];
} else {
$row['prediction'] = "no prediction";
}
break;
case "the_lead":
foreach ($v as $key => $lead_detail) {
$row[$key] = $lead_detail;
}
break;
case "quality":
if (isset($v['name'])) {
$row['quality'] = $v['name'];
} else {
$row['quality'] = "no quality";
}
break;
case "feeds":
if (isset($v['feeds']) && count($v['feeds'])) {
$row['feeds'] = array_pop($v['feeds'])['message'];
}
break;
default :
$row[$k] = $v;
break;
}
} else {
if ($k != "_id") {
$row[$k] = $v;
}
}
}
return $order == true ? sortArrayByArrayValues($this->order,$row) : $row;
}
sortArrayByArrayValues function looks like this:
function sortArrayByArrayValues(Array $array, Array $orderArray)
{
$rtn = [];
foreach($array as $arr){
if(isset($orderArray[$arr])){
$rtn[$arr] = $orderArray[$arr];
}else{
$rtn[$arr] = '';
}
}
return $rtn;
}
I really have no clue how to solve it, appreciate any help!!! :)

How to Update Categories that Already Exists in Magento Database Using Custom Script

I have Already Created The Categories in Magento by using the custom script,
but issue is when I again run the same URL my script creates another set of same category. as i want to update the existing category and insert the new categories if exist in the csv.
My csv structure is:
Category 1,Description,Category 2,Description,Category 3,Description,Category 4,Description
1,COSTUMES,1,ADULTS,1,MENS
1,COSTUMES,1,ADULTS,1,MENS,2,ASIAN
1,COSTUMES,1,ADULTS,1,MENS,3,BIKER
1,COSTUMES,1,ADULTS,1,MENS,1,CAPES & ROBES
1,COSTUMES,1,ADULTS,1,MENS,5,CAVE PEOPLE
Thanking All of You in Advance For Your Answer
Below is my code to create multi level categories:
define('MAGENTO', realpath(dirname(__FILE__)));
require_once MAGENTO . '/app/Mage.php';
umask(0);
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$count = 0;
$file = fopen('export/web categories.csv', 'r');
function odd($var)
{
$odd = array();
foreach ($var as $k => $v) {
if ($k % 2 !== 0) {
$odd[$k] = $v;
}
}
return $odd;
}
function even($var)
{
$even = array();
foreach ($var as $k => $v) {
if ($k % 2 == 0) {
$even[$k] = $v;
}
}
return $even;
}
function strcount($str,$sy){
$ch= explode($sy, $str);
return count($ch);
}
$pos=0;
$row_config= array();
$test=array();
$catgoryID=array();
$parID = 1;
while (($line = fgetcsv($file)) !== FALSE) {
if(!in_array($valtest,$row_config)){
if($count == 0){
$count++;
continue;
}
$count++;
$filterd_data=array_filter($line);
$odd_cell_data=odd($filterd_data);
$even_cell_data=even($filterd_data);
$config=array();
$string='';
$intialID=$even_cell_data[0];
foreach($odd_cell_data as $key=>$val){
if(!in_array($val,$config)){
$config[] = $val;
$data['general']['name'] =$val;
$data['general']['meta_title'] = "";
$data['general']['meta_description'] = "";
$data['general']['is_active'] = "";
$data['general']['url_key'] = "";
$data['general']['is_anchor'] = 0;
$data['general']['position'] =1 ;
$storeId = 0;
$string .=$val.'~';
if(!array_key_exists($string, $row_config)){
$catID=createCategory($data, $storeId);
$catgoryID[$string]=$catID;
$row_config[$string]=$parID;
} else {
$parID =$row_config[$string] ;
$row_config[$string]=$row_config[$string];
}
if( strcount($string,'~')==2){
$parID=1;
}
$int[$string]=$parID;
assignCat($catgoryID[$string],$parID);
$parID = $catgoryID[$string];
sleep(0.5);
unset($data);
}
}
}
}
//This Function is used for create each category
function createCategory($data, $storeId) {
$category = Mage::getModel('catalog/category');
$category->setStoreId($storeId);
if (is_array($data)) {
$category->addData($data['general']);
if (!$category->getId()) {
$parentId = $data['category']['parent'];
if (!$parentId) {
if ($storeId) {
$parentId = Mage::app()->getStore($storeId)->getRootCategoryId();
} else {
$parentId = Mage_Catalog_Model_Category::TREE_ROOT_ID;
}
}
$parentCategory = Mage::getModel('catalog/category')->load($parentId);
$category->setPath($parentCategory->getPath());
} if ($useDefaults = $data['use_default']) {
foreach ($useDefaults as $attributeCode) {
$category->setData($attributeCode, null);
}
}
$category->setAttributeSetId($category->getDefaultAttributeSetId());
if (isset($data['category_products']) && !$category->getProductsReadonly()) {
$products = array();
parse_str($data['category_products'], $products);
$category->setPostedProducts($products);
} try {
$category->save();
$category = Mage::getModel('catalog/category')->load($category->getId());
$category->setPosition($data['general']['position']);
$category->addData($data['general']);
$category->save();
echo "Suceeded <br /> ";
} catch (Exception $e) {
echo "Failed <br />";
}
}
return $category->getId();
}
//This Function is used for moving category under respective parent
function assignCat($id, $parent){
$category = Mage::getModel( 'catalog/category' )->load($id);
Mage::unregister('category');
Mage::unregister('current_category');
Mage::register('category', $category);
Mage::register('current_category', $category);
$category->move($parent);
return;
}

Only variables should be passed by reference in

I inherited maintenance of a Drupal 7 website and I have zero PHP experience and I need some help. I have just updated Drupal to 7.31 and am getting the error "Only variables should be passed by reference in..." on lines 43 and 86 of an .inc file.
Here is line 43:
$item = array_shift(array_values($data));
Here is line 86:
$item = array_shift(array_values($data));
Can anyone help me out?
I don't know if this is allowed but here the code for the .inc file
<?php
$plugin = _cdd_core_content_type_plugin('nauticus_core', 'menu_full_leaf', 'Page: menu leaf', array(
'description' => 'Add menu children',
), array(
'override_title' => 1,
'override_title_text' => ''
), 'Sail Nauticus');
function nauticus_core_menu_full_leaf_content_type_plugin_render($subtype, &$conf, $panel_args) {
$trail = menu_get_active_trail();
$menu = '';
if (is_array($trail)) {
$leaf = array_pop($trail);
if (isset($leaf['menu_name'])) {
$menu_name = $leaf['menu_name'];
if ($menu_name !== 'navigation') {
$depth = $leaf['depth'];
$p1 = $leaf['p1'];
$data = menu_tree_page_data($menu_name, $depth + 1);
foreach ($data as $i => $item) {
if ($item['link']['mlid'] !== $leaf['plid']
&& !($leaf['plid'] == 0 && ($item['link']['mlid'] == $leaf['mlid']))
) {
unset($data[$i]);
}
}
if (sizeof($data) > 1) {
$menu = menu_tree_output($data);
foreach ($menu as $i => $item) {
if (isset($item['#original_link'])) {
if ($item['#original_link']['mlid'] !== $p1) {
if (isset($menu[$i]['#below'])) {
$menu[$i]['#below'] = array();
}
}
}
}
}
elseif (sizeof($data) == 1) {
$item = array_shift(array_values($data));
if (isset($item['below']) && !empty($item['below'])) {
$menu = menu_tree_output($item['below']);
foreach ($menu as $i => $item) {
if (isset($item['#original_link'])) {
if ($item['#original_link']['mlid'] !== $p1) {
if (isset($menu[$i]['#below'])) {
$menu[$i]['#below'] = array();
}
}
}
}
}
}
}
}
}
return $menu;
}
function nauticus_core_menu_full_leaf_content_type_plugin_title($subtype, &$conf, $panel_args) {
$title = 'Navigation';
$trail = menu_get_active_trail();
if (is_array($trail)) {
$leaf = array_pop($trail);
if (isset($leaf['menu_name'])) {
$menu_name = $leaf['menu_name'];
if ($menu_name !== 'navigation') {
$depth = $leaf['depth'];
$p1 = $leaf['p1'];
$data = menu_tree_page_data($menu_name, $depth + 1);
foreach ($data as $i => $item) {
if ($item['link']['mlid'] !== $leaf['plid']
&& !($leaf['plid'] == 0 && ($item['link']['mlid'] == $leaf['mlid']))
) {
unset($data[$i]);
}
}
if (sizeof($data) >= 1) {
$item = array_shift(array_values($data));
if (isset($item['link']) && !empty($item['link'])) {
if (isset($item['link']['link_title'])) {
$title = $item['link']['link_title'];
}
}
}
}
}
}
return $title;
}
array_shift requires that the first argument be a pass by reference and array_values returns an array.
change those lines that you have $item = array_shift(array_values($data)); to
$item = array_values($data);
$item = array_shift(&$item);
the & means the variable is pass by reference. This should fix your problem.
if that does not work just remove the &.
Change
$item = array_shift(array_values($data));
to
$tmp = array_values($data);
$item = array_shift($tmp);

KendoUI Grid Server Side Sort/Filter not applying to the SQL Query

I'm running into a Problem that my grid isn't Sorting/Filtering as expected. I always get all results back from the database.
Here is my JS:
<script>
'use strict';
(function($, kendo) {
$("#grid").kendoGrid({
dataSource: {
type: "json",
transport: {
read: {
url:"http://server01/read.php",
type: "POST"
}
},
schema: {
data: "data",
total: "total",
model: {
fields: {
tID: { type: "number" },
tTitle: { type: "string" },
oDate: { type: "date" },
eDate: { type: "date" },
cDate: { type: "date" },
tKeywords: { type: "string" }
}
}
},
pageSize: 2,
serverPaging: true,
serverFiltering: true,
serverSorting: true
},
height: 430,
filterable: true,
sortable: true,
pageable: true,
columns: [{
field:"tID",
title:"TicketID",
width:"60px",
filterable: false
},{
field: "tTitle",
title: "Ticket Bezeichnung"
}, {
field: "oDate",
title: "Ticket eröffnet",
format: "{0:MM/dd/yyyy}",
width: "160px"
}, {
field: "eDate",
title: "Ticket escaliert",
format: "{0:MM/dd/yyyy}",
width: "160px"
}, {
field: "cDate",
title: "Ticket geschlossen",
format: "{0:MM/dd/yyyy}",
width: "160px"
}, {
field: "tKeywords",
title: "keywords"
}
]
});
})(jQuery, kendo);
On the Server side it looks like this:
error_reporting(E_ALL);
include 'classes/classes.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
header('Content-Type: application/json');
$request = json_encode($_POST);
$result = new DataSourceResult('mysql:host=localhost;dbname=jarvis','root','',array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
echo json_encode($result->read('jar_ticketing_index', array('tID', 'tTitle', 'tDesc', 'oDate', 'eDate', 'cDate','tKeywords'), $request));
}else{
echo "Opps...";
}
For applying the filters to the Query I'm using the dataSourceResult class:
class DataSourceResult {
private $db;
private $stringOperators = array(
'eq' => 'LIKE',
'neq' => 'NOT LIKE',
'doesnotcontain' => 'NOT LIKE',
'contains' => 'LIKE',
'startswith' => 'LIKE',
'endswith' => 'LIKE'
);
private $operators = array(
'eq' => '=',
'gt' => '>',
'gte' => '>=',
'lt' => '<',
'lte' => '<=',
'neq' => '!='
);
private $aggregateFunctions = array(
'average' => 'AVG',
'min' => 'MIN',
'max' => 'MAX',
'count' => 'COUNT',
'sum' => 'SUM'
);
function __construct($dsn, $username=null, $password=null, $driver_options=null) {
$this->db = new PDO($dsn, $username, $password, $driver_options);
}
private function total($tableName, $properties, $request) {
if (isset($request->filter)) {
$where = $this->filter($properties, $request->filter);
$statement = $this->db->prepare("SELECT COUNT(*) FROM $tableName $where");
$this->bindFilterValues($statement, $request->filter);
} else {
$statement = $this->db->prepare("SELECT COUNT(*) FROM $tableName");
}
$statement->execute();
$total = $statement->fetch(PDO::FETCH_NUM);
return (int)($total[0]);
}
private function page() {
return ' LIMIT :skip,:take';
}
private function group($data, $groups, $table, $request, $properties) {
if (count($data) > 0) {
return $this->groupBy($data, $groups, $table, $request, $properties);
}
return array();
}
private function mergeSortDescriptors($request) {
$sort = isset($request->sort) && count($request->sort) ? $request->sort : array();
$groups = isset($request->group) && count($request->group) ? $request->group : array();
return array_merge($sort, $groups);
}
private function groupBy($data, $groups, $table, $request, $properties) {
if (count($groups) > 0) {
$field = $groups[0]->field;
$count = count($data);
$result = array();
$value = $data[0][$field];
$aggregates = isset($groups[0]->aggregates) ? $groups[0]->aggregates : array();
$hasSubgroups = count($groups) > 1;
$groupItem = $this->createGroup($field, $value, $hasSubgroups, $aggregates, $table, $request, $properties);
for ($index = 0; $index < $count; $index++) {
$item = $data[$index];
if ($item[$field] != $value) {
if (count($groups) > 1) {
$groupItem["items"] = $this->groupBy($groupItem["items"], array_slice($groups, 1), $table, $request, $properties);
}
$result[] = $groupItem;
$groupItem = $this->createGroup($field, $data[$index][$field], $hasSubgroups, $aggregates, $table, $request, $properties);
$value = $item[$field];
}
$groupItem["items"][] = $item;
}
if (count($groups) > 1) {
$groupItem["items"] = $this->groupBy($groupItem["items"], array_slice($groups, 1), $table, $request, $properties);
}
$result[] = $groupItem;
return $result;
}
return array();
}
private function addFilterToRequest($field, $value, $request) {
$filter = (object)array(
'logic' => 'and',
'filters' => array(
(object)array(
'field' => $field,
'operator' => 'eq',
'value' => $value
))
);
if (isset($request->filter)) {
$filter->filters[] = $request->filter;
}
return (object) array('filter' => $filter);
}
private function addFieldToProperties($field, $properties) {
if (!in_array($field, $properties)) {
$properties[] = $field;
}
return $properties;
}
private function createGroup($field, $value, $hasSubgroups, $aggregates, $table, $request, $properties) {
if (count($aggregates) > 0) {
$request = $this->addFilterToRequest($field, $value, $request);
$properties = $this->addFieldToProperties($field, $properties);
}
$groupItem = array(
'field' => $field,
'aggregates' => $this->calculateAggregates($table, $aggregates, $request, $properties),
'hasSubgroups' => $hasSubgroups,
'value' => $value,
'items' => array()
);
return $groupItem;
}
private function calculateAggregates($table, $aggregates, $request, $properties) {
$count = count($aggregates);
if (count($aggregates) > 0) {
$functions = array();
for ($index = 0; $index < $count; $index++) {
$aggregate = $aggregates[$index];
$name = $this->aggregateFunctions[$aggregate->aggregate];
$functions[] = $name.'('.$aggregate->field.') as '.$aggregate->field.'_'.$aggregate->aggregate;
}
$sql = sprintf('SELECT %s FROM %s', implode(', ', $functions), $table);
if (isset($request->filter)) {
$sql .= $this->filter($properties, $request->filter);
}
$statement = $this->db->prepare($sql);
if (isset($request->filter)) {
$this->bindFilterValues($statement, $request->filter);
}
$statement->execute();
$result = $statement->fetchAll(PDO::FETCH_ASSOC);
return $this->convertAggregateResult($result[0]);
}
return (object)array();
}
private function convertAggregateResult($properties) {
$result = array();
foreach($properties as $property => $value) {
$item = array();
$split = explode('_', $property);
$field = $split[0];
$function = $split[1];
if (array_key_exists($field, $result)) {
$result[$field][$function] = $value;
} else {
$result[$field] = array($function => $value);
}
}
return $result;
}
private function sort($properties, $sort) {
$count = count($sort);
$sql = '';
if ($count > 0) {
$sql = ' ORDER BY ';
$order = array();
for ($index = 0; $index < $count; $index ++) {
$field = $sort[$index]->field;
if (in_array($field, $properties)) {
$dir = 'ASC';
if ($sort[$index]->dir == 'desc') {
$dir = 'DESC';
}
$order[] = "$field $dir";
}
}
$sql .= implode(',', $order);
}
return $sql;
}
private function where($properties, $filter, $all) {
if (isset($filter->filters)) {
$logic = ' AND ';
if ($filter->logic == 'or') {
$logic = ' OR ';
}
$filters = $filter->filters;
$where = array();
for ($index = 0; $index < count($filters); $index++) {
$where[] = $this->where($properties, $filters[$index], $all);
}
$where = implode($logic, $where);
return "($where)";
}
$field = $filter->field;
if (in_array($field, $properties)) {
$index = array_search($filter, $all);
$value = ":filter$index";
if ($this->isDate($filter->value)) {
$field = "date($field)";
$value = "date($value)";
}
if ($this->isString($filter->value)) {
$operator = $this->stringOperators[$filter->operator];
} else {
$operator = $this->operators[$filter->operator];
}
return "$field $operator $value";
}
}
private function flatten(&$all, $filter) {
if (isset($filter->filters)) {
$filters = $filter->filters;
for ($index = 0; $index < count($filters); $index++) {
$this->flatten($all, $filters[$index]);
}
} else {
$all[] = $filter;
}
}
private function filter($properties, $filter) {
$all = array();
$this->flatten($all, $filter);
$where = $this->where($properties, $filter, $all);
return " WHERE $where";
}
private function isDate($value) {
$result = date_parse($value);
return $result["error_count"] < 1;
}
private function isString($value) {
return !is_bool($value) && !is_numeric($value) && !$this->isDate($value);
}
private function bindFilterValues($statement, $filter) {
$filters = array();
$this->flatten($filters, $filter);
for ($index = 0; $index < count($filters); $index++) {
$value = $filters[$index]->value;
$operator = $filters[$index]->operator;
$date = date_parse($value);
if ($operator == 'contains' || $operator == 'doesnotcontain') {
$value = "%$value%";
} else if ($operator == 'startswith') {
$value = "$value%";
} else if ($operator == 'endswith') {
$value = "%$value";
}
$statement->bindValue(":filter$index", $value);
}
}
public function create($table, $properties, $models, $key) {
$result = array();
$data = array();
if (!is_array($models)) {
$models = array($models);
}
$errors = array();
foreach ($models as $model) {
$columns = array();
$values = array();
$input_parameters = array();
foreach ($properties as $property) {
if ($property != $key) {
$columns[] = $property;
$values[] = '?';
$input_parameters[] = $model->$property;
}
}
$columns = implode(', ', $columns);
$values = implode(', ', $values);
$sql = "INSERT INTO $table ($columns) VALUES ($values)";
$statement = $this->db->prepare($sql);
$statement->execute($input_parameters);
$status = $statement->errorInfo();
if ($status[1] > 0) {
$errors[] = $status[2];
} else {
$model->$key = $this->db->lastInsertId();
$data[] = $model;
}
}
if (count($errors) > 0) {
$result['errors'] = $errors;
} else {
$result['data'] = $data;
}
return $result;
}
public function destroy($table, $models, $key) {
$result = array();
if (!is_array($models)) {
$models = array($models);
}
$errors = array();
foreach ($models as $model) {
$sql = "DELETE FROM $table WHERE $key=?";
$statement = $this->db->prepare($sql);
$statement->execute(array($model->$key));
$status = $statement->errorInfo();
if ($status[1] > 0) {
$errors[] = $status[2];
}
}
if (count($errors) > 0) {
$result['errors'] = $errors;
}
return $result;
}
public function update($table, $properties, $models, $key) {
$result = array();
if (in_array($key, $properties)) {
if (!is_array($models)) {
$models = array($models);
}
$errors = array();
foreach ($models as $model) {
$set = array();
$input_parameters = array();
foreach ($properties as $property) {
if ($property != $key) {
$set[] = "$property=?";
$input_parameters[] = $model->$property;
}
}
$input_parameters[] = $model->$key;
$set = implode(', ', $set);
$sql = "UPDATE $table SET $set WHERE $key=?";
$statement = $this->db->prepare($sql);
$statement->execute($input_parameters);
$status = $statement->errorInfo();
if ($status[1] > 0) {
$errors[] = $status[2];
}
}
if (count($errors) > 0) {
$result['errors'] = $errors;
}
}
if (count($result) == 0) {
$result = "";
}
return $result;
}
public function read($table, $properties, $request = null) {
$result = array();
$result['total'] = $this->total($table, $properties, $request);
$sql = sprintf('SELECT %s FROM %s', implode(', ', $properties), $table);
if (isset($request->filter)) {
$sql .= $this->filter($properties, $request->filter);
}
$sort = $this->mergeSortDescriptors($request);
if (count($sort) > 0) {
$sql .= $this->sort($properties, $sort);
}
if (isset($request->skip) && isset($request->take)) {
$sql .= $this->page();
}
$statement = $this->db->prepare($sql);
if (isset($request->filter)) {
$this->bindFilterValues($statement, $request->filter);
}
if (isset($request->skip) && isset($request->take)) {
$statement->bindValue(':skip', (int)$request->skip, PDO::PARAM_INT);
$statement->bindValue(':take', (int)$request->take, PDO::PARAM_INT);
}
$statement->execute();
$data = $statement->fetchAll(PDO::FETCH_ASSOC);
if (isset($request->group) && count($request->group) > 0) {
$data = $this->group($data, $request->group, $table, $request, $properties);
$result['groups'] = $data;
} else {
$result['data'] = $data;
}
if (isset($request->aggregate)) {
$result["aggregates"] = $this->calculateAggregates($table, $request->aggregate, $request, $properties);
}
return $result;
}
}
I always get all of the records back from the database. It looks like my DataSourceResult Object isn't getting the filter variables the right way. But I don't see any error at all.
Could you give me a hint?
Oke I pointed it out. The Filter I got by POST need to be passed as an object to the dataSourceResult Class.
$object = json_decode(json_encode($_POST), FALSE);
Now its working like a charm!

Categories