N-tier navigation in codeigniter - codeigniter

How to create top navigation in code-igniter?

In controller I have declare a function and call model
private function getNavigation(){
$this->load->model('xx');
$data['nav'] = $this->xx->prepareTree();
$this->load->view('index',$data);
}
And In model I have declare three functions
public function prepareTree(){
$this->db->select("`catalog_parent` as parent_id, `catalog_name` as menu_item, `catalog_id` as id, `catalog_template` as pager_id");
$this->db->from("catalog_category");
$this->db->where("`catalog_navigation` = '1'");
$this->q = $this->db->get();
$create = '';
if ($this->q->num_rows() > 0) {
$create = $this->prepareList($this->q->result_array());
}
if(!empty($create)){
return $this->category_tree($create);
} else {
return '';
}
}
private function prepareList(array $items, $pid = 0) {
$output = array();
foreach ($items as $item) {
if ((int) $item['parent_id'] == $pid) {
if ($children = $this->prepareList($items, $item['id'])) {
$item['children'] = $children;
}
$output[] = $item;
}
}
return $output;
}
private function category_tree($menu_items, $child = false){
$output = '';
if (count($menu_items)>0) {
$output .= ($child === false) ? '<ul id="main-menu" class="sm sm-blue">' : '<ul>' ;
foreach ($menu_items as $item) {
$output .= '<li>';
$output .= ''.$item['menu_item'].'';
if (isset($item['children']) && count($item['children'])) {
$output .= $this->category_tree($item['children'], true);
}
$output .= '</li>';
}
$output .= '</ul>';
}
return $output;
}
If some suggest an more easy way please suggest us.
Thanks

Related

Unique Case of "Call to a member function set_type() on null"

Hello guys i have gone through all 25 questions relating to the title of my question and i am made to believe my scenario is totally different.
Here is the error
Fatal error: Uncaught Error: Call to a member function set_type() on null in /path_to_file/login.php:55 Stack trace: #0 /path_to_call_page/login.php(24): login->authenticate() #1 {main} thrown in /path_to_file/login.php on line 55
Here is my code
<?php
class login
{
public $username;
public $password;
public $err;
public $table_name;
public $session_data;
public $md5 = true;
public $username_column = "username";
public $password_column = "password";
public $builder;
function _construct($username,$password)
{
$this->username = $username;
$this->password = $password;
$this->builder = new queryBuilder();
}
function set_table($tablename)
{
$this->table_name = $tablename;
}
/*
* Tells the login class where to find the username and password in database table
*/
function set_columns($username_col,$password_col)
{
$this->username_column = $username_col;
$this->password_column = $password_col;
}
function md5_on()
{
$this->md5 = true;
}
function md5_off()
{
$this->md5 = false;
}
function authenticate()
{
$db = new mySQLConnection();
$db->select();
// if md5 is turned on
if($this->md5)
$this->password = md5($this->password);
$this->builder->set_type("SELECT");
$this->builder->set_table_name($this->table_name);
$this->builder->set_where("WHERE $this->username_column = '$this->username' and $this->password_column = '$this->password'");
$query = $this->builder->build_query();
if($db->execute_query($query))
$data = $db->fetch($db->result);
else
{
die($db->error);
}
if($db->rows_affected() == 1)
{
$this->session_data = $data[0];
return true;
}
else
{
$this->err = "Invalid username or password. Please try again";
return false;
}
}
function get_error()
{
return $this->err;
}
}
?>
The error occurs everywhere i have
$this->builder
And i have defined it in the _construct method.
This is the queryBuilder class
class queryBuilder
{
var $data;
var $field;
var $tableName;
var $databaseName;
var $where;
var $order;
var $group;
var $limit;
var $queryString;
var $error;
private function put_quotes1($field)
{
$field = trim($field);
$field = "`".$field."`";
return $field;
}
private function put_quotes2($field)
{
$field = trim($field);
$field = "'".$field."'";
return $field;
}
function set_type($type)
{
$this->type = $type;
}
function set_data($data)
{
$this->data = $data;
}
function set_field($field = null)
{
$this->field = $field;
}
function set_where($where)
{
$this->where = $where;
}
function set_limit($limit)
{
$this->limit = $limit;
}
function set_order($order)
{
$this->order = $order;
}
function set_table_name($name)
{
$this->tableName = $name;
}
function prepare_data($data)
{
if(is_array($data))
{
foreach($data as $k => $v)
{
$this->field[] = $k; //setting the column names
$this->data[] = $v; // setting the values
}
}
}
function build_query()
{
switch($this->type)
{
case 'SHOW':
$database_name = $this->put_quotes1($this->databaseName);
$this->queryString = "SHOW ";
if(!isset($this->field) || is_null($this->field))
$this->queryString .= "DATABASES LIKE 'thirdeye%'; ";
else{
$noFields = count($this->field); //no of fields in table
for($i = 0; $i < $noFields; $i++)
{
if($i == ($noFields- 1)) // if on the last field
$this->queryString .= $this->put_quotes1($this->field[$i]).' ';
else
$this->queryString .= $this->put_quotes1($this->field[$i]).',';
}
}
break;
case 'INSERT':
$table_name = $this->put_quotes1($this->tableName);
$this->queryString = "INSERT INTO ".$table_name." (";
$noFields = count($this->field);
$noData = count($this->data);
if($noFields > 0 && $noData > 0)
{
for($i = 0; $i < $noFields; $i++)
{
if($i == ($noFields- 1))
$this->queryString .= $this->put_quotes1($this->field[$i]).')';
else
$this->queryString .= $this->put_quotes1($this->field[$i]).',';
}
$this->queryString.= " VALUES (";
for($i = 0; $i < $noData; $i++)
{
if($i == ($noData -1))
$this->queryString .= $this->put_quotes2($this->data[$i]).');';
else
$this->queryString .= $this->put_quotes2($this->data[$i]).',';
}
}
else
{
$this->error = "No column name or data was supplied";
}
break;
case 'SELECT':
$table_name = $this->put_quotes1($this->tableName);
$this->queryString = "SELECT ";
if(!isset($this->field) || is_null($this->field))
$this->queryString .= "* ";
else{
$noFields = count($this->field); //no of fields in table
for($i = 0; $i < $noFields; $i++)
{
if($i == ($noFields- 1)) // if on the last field
$this->queryString .= $this->put_quotes1($this->field[$i]).' ';
else
$this->queryString .= $this->put_quotes1($this->field[$i]).',';
}
}
$this->queryString .= "FROM ".$table_name;
if(isset($this->where))
$this->queryString .= " ".$this->where;
if(isset($this->order))
$this->queryString .= " ".$this->order;
if(isset($this->limit))
$this->queryString .= " ".$this->limit;
else
$this->queryString .= ";";
break;
case 'UPDATE':
$table_name = $this->put_quotes1($this->tableName);
$this->queryString = "UPDATE ". $table_name. " SET ";
$noFields = count($this->field); //no of fields in table
if(is_array($this->field) && is_array($this->data) && isset($this->where))
{
for($i = 0; $i < $noFields; $i++)
{
if($i == ($noFields -1))
$this->queryString .= $this->put_quotes1($this->field[$i])." = ". $this->put_quotes2($this->data[$i]).' ';
else
$this->queryString .= $this->put_quotes1($this->field[$i])." = ". $this->put_quotes2($this->data[$i]).',';
}
$this->queryString .= " ".$this->where.";";
}
else
{
$this->error = "Cannot build query. One of the following was not set";
}
break;
case 'DELETE':
$table_name = $this->put_quotes1($this->tableName);
$this->queryString = "DELETE FROM ".$table_name;
if(isset($this->where))
{
$this->queryString .= " ".$this->where.";";
}
else
{
$this->error = "Connot build. No condition was set";
}
break;
}
return $this->queryString;
}
}
Any pointers would help. Remember i have been through previous questions so a suggested edit or code answer would be great.

Get the information you entered to ID

This file is the database ID information all the fields and went and came to a Blade, I want to an ID information entered in the same panel Blade I send my face.
class DataGrid extends DataSet
{
protected $fields = array();
/** #var Column[] */
public $columns = array();
public $headers = array();
public $rows = array();
public $output = "";
public $attributes = array("class" => "table");
public $checkbox_form = false;
protected $row_callable = array();
/**
* #param string $name
* #param string $label
* #param bool $orderby
*
* #return Column
*/
public function add($name, $label = null, $orderby = false)
{
$column = new Column($name, $label, $orderby);
$this->columns[$column->name] = $column;
if (!in_array($name,array("_edit"))) {
$this->headers[] = $label;
}
if ($orderby) {
$this->addOrderBy($column->orderby_field);
}
return $column;
}
//todo: like "field" for DataForm, should be nice to work with "cell" as instance and "row" as collection of cells
public function build($view = '')
{
($view == '') and $view = 'rapyd::datagrid';
parent::build();
Persistence::save();
foreach ($this->data as $tablerow) {
$row = new Row($tablerow);
foreach ($this->columns as $column) {
$cell = new Cell($column->name);
$sanitize = (count($column->filters) || $column->cell_callable) ? false : true;
$value = $this->getCellValue($column, $tablerow, $sanitize);
$cell->value($value);
$cell->parseFilters($column->filters);
if ($column->cell_callable) {
$callable = $column->cell_callable;
$cell->value($callable($cell->value, $tablerow));
}
$row->add($cell);
}
if (count($this->row_callable)) {
foreach ($this->row_callable as $callable) {
$callable($row);
}
}
$this->rows[] = $row;
}
$routeParamters = \Route::current()->parameters();
return \View::make($view, array('dg' => $this, 'buttons'=>$this->button_container, 'label'=>$this->label,
'current_entity' => $routeParamters['entity']));
}
public function buildCSV($file = '', $timestamp = '', $sanitize = true,$del = array())
{
$this->limit = null;
parent::build();
$segments = \Request::segments();
$filename = ($file != '') ? basename($file, '.csv') : end($segments);
$filename = preg_replace('/[^0-9a-z\._-]/i', '',$filename);
$filename .= ($timestamp != "") ? date($timestamp).".csv" : ".csv";
$save = (bool) strpos($file,"/");
//Delimiter
$delimiter = array();
$delimiter['delimiter'] = isset($del['delimiter']) ? $del['delimiter'] : ';';
$delimiter['enclosure'] = isset($del['enclosure']) ? $del['enclosure'] : '"';
$delimiter['line_ending'] = isset($del['line_ending']) ? $del['line_ending'] : "\n";
if ($save) {
$handle = fopen(public_path().'/'.dirname($file)."/".$filename, 'w');
} else {
$headers = array(
'Content-Type' => 'text/csv',
'Pragma'=>'no-cache',
'"Cache-Control' => 'must-revalidate, post-check=0, pre-check=0',
'Content-Disposition' => 'attachment; filename="' . $filename.'"');
$handle = fopen('php://output', 'w');
ob_start();
}
fputs($handle, $delimiter['enclosure'].implode($delimiter['enclosure'].$delimiter['delimiter'].$delimiter['enclosure'], $this->headers) .$delimiter['enclosure'].$delimiter['line_ending']);
foreach ($this->data as $tablerow) {
$row = new Row($tablerow);
foreach ($this->columns as $column) {
if (in_array($column->name,array("_edit")))
continue;
$cell = new Cell($column->name);
$value = str_replace('"', '""',str_replace(PHP_EOL, '', strip_tags($this->getCellValue($column, $tablerow, $sanitize))));
$cell->value($value);
$row->add($cell);
}
if (count($this->row_callable)) {
foreach ($this->row_callable as $callable) {
$callable($row);
}
}
fputs($handle, $delimiter['enclosure'] . implode($delimiter['enclosure'].$delimiter['delimiter'].$delimiter['enclosure'], $row->toArray()) . $delimiter['enclosure'].$delimiter['line_ending']);
}
fclose($handle);
if ($save) {
//redirect, boolean or filename?
} else {
$output = ob_get_clean();
return \Response::make(rtrim($output, "\n"), 200, $headers);
}
}
protected function getCellValue($column, $tablerow, $sanitize = true)
{
//blade
if (strpos($column->name, '{{') !== false ||
strpos($column->name, '{!!') !== false) {
if (is_object($tablerow) && method_exists($tablerow, "getAttributes")) {
$fields = $tablerow->getAttributes();
$relations = $tablerow->getRelations();
$array = array_merge($fields, $relations) ;
$array['row'] = $tablerow;
} else {
$array = (array) $tablerow;
}
$value = $this->parser->compileString($column->name, $array);
//eager loading smart syntax relation.field
} elseif (preg_match('#^[a-z0-9_-]+(?:\.[a-z0-9_-]+)+$#i',$column->name, $matches) && is_object($tablerow) ) {
//switch to blade and god bless eloquent
$_relation = '$'.trim(str_replace('.','->', $column->name));
$expression = '{{ isset('. $_relation .') ? ' . $_relation . ' : "" }}';
$fields = $tablerow->getAttributes();
$relations = $tablerow->getRelations();
$array = array_merge($fields, $relations) ;
$value = $this->parser->compileString($expression, $array);
//fieldname in a collection
} elseif (is_object($tablerow)) {
$value = #$tablerow->{$column->name};
if ($sanitize) {
$value = $this->sanitize($value);
}
//fieldname in an array
} elseif (is_array($tablerow) && isset($tablerow[$column->name])) {
$value = $tablerow[$column->name];
//none found, cell will have the column name
} else {
$value = $column->name;
}
//decorators, should be moved in another method
if ($column->link) {
if (is_object($tablerow) && method_exists($tablerow, "getAttributes")) {
$array = $tablerow->getAttributes();
$array['row'] = $tablerow;
} else {
$array = (array) $tablerow;
}
$value = ''.$value.'';
}
if (count($column->actions)>0) {
$key = ($column->key != '') ? $column->key : $this->key;
$keyvalue = #$tablerow->{$key};
$routeParamters = \Route::current()->parameters();
$value = \View::make('rapyd::datagrid.actions', array('uri' => $column->uri, 'id' => $keyvalue, 'actions' => $column->actions,
'current_entity' => $routeParamters['entity']));
}
return $value;
}
public function getGrid($view = '')
{
$this->output = $this->build($view)->render();
return $this->output;
}
public function __toString()
{
if ($this->output == "") {
//to avoid the error "toString() must not throw an exception"
//http://stackoverflow.com/questions/2429642/why-its-impossible-to-throw-exception-from-tostring/27307132#27307132
try {
$this->getGrid();
}
catch (\Exception $e) {
$previousHandler = set_exception_handler(function (){ });
restore_error_handler();
call_user_func($previousHandler, $e);
die;
}
}
return $this->output;
}
public function edit($uri, $label='Edit', $actions='show|modify|delete', $key = '')
{
return $this->add('_edit', $label)->actions($uri, explode('|', $actions))->key($key);
}
public function getColumn($column_name)
{
if (isset($this->columns[$column_name])) {
return $this->columns[$column_name];
}
}
public function addActions($uri, $label='Edit', $actions='show|modify|delete', $key = '')
{
return $this->edit($uri, $label, $actions, $key);
}
public function row(\Closure $callable)
{
$this->row_callable[] = $callable;
return $this;
}
protected function sanitize($string)
{
$result = nl2br(htmlspecialchars($string));
return Config::get('rapyd.sanitize.num_characters') > 0 ? str_limit($result, Config::get('rapyd.sanitize.num_characters')) : $result;
}
public function rowCount()
{
return count($this->rows);
}
}
This is the source of a rapyd-laravel widget/package, not a custom code.
According to DataGrid/DataSet documentation, you can use many sources:
https://github.com/zofe/rapyd-laravel/wiki/DataSet
DataSet/DataGrid are presenters, you can retrieve all data of your data source using
{{ $item->field }} or {{ $row->field }} respectively
See the docs please
https://github.com/zofe/rapyd-laravel/wiki

When echo multiple file data it only display last file info

On my multiple upload library I have a function which is called upload data.
And another function called upload.
For some reason when I select multiple images and is success full when I use on my controller
$data = $this->multiple_upload->upload_data();
echo $data['file_name'];
It will only get the name of the last file selected it does not return all file names selected. It should display all file names selected.
Question: How on my library function upload_data() can I make sure can return data correctly rather than just the last one. the upload_data function just seems to only return the last file information.
Library
<?php
class Multiple_upload {
public function __construct($config = array()) {
$this->CI =& get_instance();
$this->files = $this->clean($_FILES);
empty($config) OR $this->set_config($config);
}
public function set_config($config) {
foreach ($config as $key => $value) {
$this->$key = $value;
}
return $this;
}
public function upload($field = 'userfile') {
if (empty($this->upload_path)) {
$this->set_error('upload_path_not_set');
return FALSE;
}
if (!realpath(FCPATH . $this->upload_path)) {
$this->set_error('upload_path_in_correct');
return FALSE;
}
if (!empty($this->files[$field]['name'][0])) {
$check_error = 0;
foreach ($this->files[$field]['name'] as $key => $value) {
$this->file_name = $this->files[$field]['name'][$key];
$this->file_temp = $this->files[$field]['tmp_name'][$key];
$this->file_size = $this->files[$field]['size'][$key];
$this->get_file_extension = explode('.', $this->files[$field]['name'][$key]);
$this->get_file_extension_end = strtolower(end($this->get_file_extension));
if (!in_array($this->get_file_extension_end, $this->allowed_types)) {
$this->set_error('file_extension_not_allowed');
$check_error++;
}
if ($this->files[$field]['size'][$key] > $this->max_size) {
$this->set_error('file_size_check');
$check_error++;
}
if ( ! #copy($this->file_temp, FCPATH . $this->upload_path . '/' . $this->file_name)) {
if ( ! #move_uploaded_file($this->file_temp, FCPATH . $this->upload_path . '/' . $this->file_name)) {
$this->set_error('upload_destination_error', 'error');
$check_error++;
}
}
}
if($check_error > 0 ) {
return FALSE;
}
// This lets me get file data in another function
return $this;
}
}
public function upload_data() {
$data = array(
'file_name' => $this->file_name,
'file_path' => FCPATH . $this->upload_path . '/'
);
return $data;
}
public function set_error($message) {
$this->CI->lang->load('upload', 'english');
$msg = "";
if ($message == 'upload_path_not_set') {
$msg .= $this->CI->lang->line($message);
}
if ($message == 'upload_path_in_correct') {
$msg .= $this->CI->lang->line($message);
}
if ($message == 'file_extension_not_allowed') {
$msg .= sprintf($this->CI->lang->line($message), $this->file_name, $this->get_file_extension_end);
}
if ($message == 'file_size_check') {
$msg .= sprintf($this->CI->lang->line($message), $this->file_name, $this->max_size);
}
return $this->error_message[] = $msg;
}
public function display_error_messages($open_tag = '<p>', $close_tag = '</p>') {
$message = "";
if (isset($this->error_message)) {
foreach($this->error_message as $msg) {
$message .= $open_tag . $msg . $close_tag;
}
}
return $message;
}
public function clean($data) {
if (is_array($data)) {
foreach ($data as $key => $value) {
unset($data[$key]);
$data[$this->clean($key)] = $this->clean($value);
}
} else {
$data = htmlspecialchars($data, ENT_COMPAT, 'UTF-8');
}
return $data;
}
}
I have tried
public function upload_data() {
$data[] = array(
'file_name' => $this->file_name,
'file_path' => FCPATH . $this->upload_path . '/'
);
return $data;
}
Controller index function
public function index(){
$data['error'] = '';
$this->load->library('multiple_upload');
$config['upload_path'] = 'uploads';
$config['allowed_types'] = array('jpg', 'png');
$config['max_size'] = 3000000;
//$config['max_size'] = 1000;
$config['overwrite'] = TRUE;
$this->multiple_upload->set_config($config);
if ($this->multiple_upload->upload() == FALSE) {
$data['error'] = $this->multiple_upload->display_error_messages('<div class="alert alert-danger">', '</div>');
$this->load->view('upload', $data);
} else {
$data = $this->multiple_upload->upload_data();
echo $data['file_name'];
}
}
<?php
class Multiple_upload {
private $filenames;
public function __construct($config = array()) {
$this->CI =& get_instance();
$this->files = $this->clean($_FILES);
$this->filenames = array();
empty($config) OR $this->set_config($config);
}
public function set_config($config) {
foreach ($config as $key => $value) {
$this->$key = $value;
}
return $this;
}
public function upload($field = 'userfile') {
if (empty($this->upload_path)) {
$this->set_error('upload_path_not_set');
return FALSE;
}
if (!realpath(FCPATH . $this->upload_path)) {
$this->set_error('upload_path_in_correct');
return FALSE;
}
if (!empty($this->files[$field]['name'][0])) {
$check_error = 0;
foreach ($this->files[$field]['name'] as $key => $value) {
$this->file_name = $this->files[$field]['name'][$key];
$this->filenames[] = $this->files[$field]['name'][$key];
$this->file_temp = $this->files[$field]['tmp_name'][$key];
$this->file_size = $this->files[$field]['size'][$key];
$this->get_file_extension = explode('.', $this->files[$field]['name'][$key]);
$this->get_file_extension_end = strtolower(end($this->get_file_extension));
if (!in_array($this->get_file_extension_end, $this->allowed_types)) {
$this->set_error('file_extension_not_allowed');
$check_error++;
}
if ($this->files[$field]['size'][$key] > $this->max_size) {
$this->set_error('file_size_check');
$check_error++;
}
if ( ! #copy($this->file_temp, FCPATH . $this->upload_path . '/' . $this->file_name)) {
if ( ! #move_uploaded_file($this->file_temp, FCPATH . $this->upload_path . '/' . $this->file_name)) {
$this->set_error('upload_destination_error', 'error');
$check_error++;
}
}
}
if($check_error > 0 ) {
return FALSE;
}
// This lets me get file data in another function
return $this;
}
}
public function upload_data()
{
$data = array();
foreach($this->filenames as $filename)
{
$data[] = array(
'file_name' => $filename,
'file_path' => FCPATH . $this->upload_path . '/'
);
}
return $data;
}
public function set_error($message) {
$this->CI->lang->load('upload', 'english');
$msg = "";
if ($message == 'upload_path_not_set') {
$msg .= $this->CI->lang->line($message);
}
if ($message == 'upload_path_in_correct') {
$msg .= $this->CI->lang->line($message);
}
if ($message == 'file_extension_not_allowed') {
$msg .= sprintf($this->CI->lang->line($message), $this->file_name, $this->get_file_extension_end);
}
if ($message == 'file_size_check') {
$msg .= sprintf($this->CI->lang->line($message), $this->file_name, $this->max_size);
}
return $this->error_message[] = $msg;
}
public function display_error_messages($open_tag = '<p>', $close_tag = '</p>') {
$message = "";
if (isset($this->error_message)) {
foreach($this->error_message as $msg) {
$message .= $open_tag . $msg . $close_tag;
}
}
return $message;
}
public function clean($data) {
if (is_array($data)) {
foreach ($data as $key => $value) {
unset($data[$key]);
$data[$this->clean($key)] = $this->clean($value);
}
} else {
$data = htmlspecialchars($data, ENT_COMPAT, 'UTF-8');
}
return $data;
}
}
And
public function index()
{
$data['error'] = '';
$this->load->library('multiple_upload');
$config['upload_path'] = 'uploads';
$config['allowed_types'] = array('jpg', 'png');
$config['max_size'] = 3000000;
//$config['max_size'] = 1000;
$config['overwrite'] = TRUE;
$this->multiple_upload->set_config($config);
if ($this->multiple_upload->upload() == FALSE)
{
$data['error'] = $this->multiple_upload->display_error_messages('<div class="alert alert-danger">', '</div>');
$this->load->view('upload', $data);
}
else
{
$data = $this->multiple_upload->upload_data();
foreach($data as $file)
{
echo $file['file_name']."<br>";
}
}
}
you can use array to save all files information in upload_data function.
public function upload_data() {
$data = array(
'file_name' => $this->file_name,
'file_path' => FCPATH . $this->upload_path . '/'
);
return $data;
}
to
public function upload_data() {
$data[] = array(
'file_name' => $this->file_name,
'file_path' => FCPATH . $this->upload_path . '/'
);
return $data;
}
it will return array of all the file details

Like Query Is Not Working properly

In Code igniter Model I am using like query to fetch all the products having first name rice which is not working controller while using get_where('name') it works fine.
public function fetchdeal_products($id) {
$this->db->select('*');
$this->db->from('products');
$q = $this->db->like("name", $id);
if ($q->num_rows() > 0) {
foreach (($q->result()) as $row) {
$data[] = $row;
}
return $data;
}
}
I am using like query to fetch all the products having first name rice which is not working controller while using get_where('name') it works fine.
//Controller
function ajaxdealcategorydata($id = NULL) {
$this->sma->checkPermissions('index');
$id = $this->input->get('id');
$subcategories = $this->pos_model->getdealcategory($id);
$scats = '';
foreach ($subcategories as $category) {
$scats .= "<button id=\"subcategory-" . $category->id . "\" type=\"button\" value='" . $category->id . "' class=\"btn-prni subcategory\" ><img src=\"assets/uploads/thumbs/" . ($category->image ? $category->image : 'no_image.png') . "\" style='width:" . $this->Settings->twidth . "px;height:" . $this->Settings->theight . "px;' class='img-rounded img-thumbnail' /><span>" . $category->name . "</span></button>";
}
$products = $this->ajaxdealproducts($id);
if (!($tcp = $this->pos_model->products_count($id))) {
$tcp = 0;
}
echo json_encode(array('products' => $products, 'subcategories' => $scats, 'tcp' => $tcp));
}
I am using like query to fetch all the products having first name rice which is not working controller while using get_where('name') it works fine.
function ajaxdealproducts() {
$this->sma->checkPermissions('index');
if ($this->input->get('id') ) {
$id = $this->input->get('id');
} else {
$category_id = $this->pos_settings->default_category;
}
if ($this->input->get('subcategory_id')) {
$subcategory_id = $this->input->get('subcategory_id');
} else {
$subcategory_id = NULL;
}
if ($this->input->get('per_page') == 'n') {
$page = 0;
} else {
$page = $this->input->get('per_page');
}
$this->load->library("pagination");
$config = array();
$config["base_url"] = base_url() . "pos/ajaxdealproducts";
$config["total_rows"] = $subcategory_id ? $this->pos_model- >products_count($id, $subcategory_id) : $this->pos_model->products_count($id);
$config["per_page"] = $this->pos_settings->pro_limit;
$config['prev_link'] = FALSE;
$config['next_link'] = FALSE;
$config['display_pages'] = FALSE;
$config['first_link'] = FALSE;
$config['last_link'] = FALSE;
$this->pagination->initialize($config);
$products = $this->pos_model->fetchdeal_products($id, $config["per_page"], $page);
$pro = 1;
$prods = '<div>';
foreach ($products as $product) {
$count = $product->id;
if ($count < 10) {
$count = "0" . ($count / 100) * 100;
}
if ($category_id < 10) {
$category_id = "0" . ($category_id / 100) * 100;
}
$prods .= "<button id=\"product-" . $category_id . $count . "\" type=\"button\" value='" . $product->code . "' title=\"" . $product->name . "\" class=\"btn-prni btn-" . $this->pos_settings->product_button_color . " product pos-tip\" data-container=\"body\"><img src=\"" . base_url() . "assets/uploads/thumbs/" . $product->image . "\" alt=\"" . $product->name . "\" style='width:" . $this->Settings->twidth . "px;height:" . $this->Settings->theight . "px;' class='img-rounded' /><span>" . character_limiter($product->name, 15) . "</span></button>";
$pro++;
}
$prods .= "</div>";
if ($this->input->get('per_page')) {
echo $prods;
} else {
return $prods;
}
}
The database LIKE function only creates a LIKE in the SQL statement. You'll still need to call the GET mothod afterwards; Like this;
$this->db->like('name', $id);
$q = $this->db->get();
You are using $this->db_like() incorrectly.
$this->db->like('title', 'match');
// Produces: WHERE title LIKE '%match%'
(from documentation)
In your case the usage would be
$this->db->like('name', 'rice')
More info
public function fetchdeal_products($id)
{
$query = $this->db->query("Select products.* From products Where (products.name Like '%$id%')");
$result = $query->result_array();
return $result;
}
you have to write it as bellow.
public function fetchdeal_products($id) {
$this->db->like("name", $id);
$q = $this->db->get('products');
if ($q->num_rows() > 0) {
foreach (($q->result()) as $row) {
$data[] = $row;
}
return $data;
}
}

Magento Issues with category dropdown

I need to display all the subcategories under root category name using . I am unable to find the root category details. Root category name is displaying as '/' How to overcome this issue?
Currently i am getting all the categories including root categories (/).
My code is as in below:
public function toOptionArray()
{
$categories = array();
$categoryCollection = Mage::getResourceModel('catalog/category_collection')->addFieldToFilter(
'path',
array('neq' => '1')
);
foreach ($categoryCollection as $category) {
var_dump($category->getData());
echo '<br />';
$category = Mage::getModel('catalog/category')->load($category->getId());
$categories[$category->getId()] = $category->getUrlPath();
}
return $categories;
}
protected function _renderOptions(Varien_Object $row)
{
$categories = $this->getColumn()->getOptions();
$html = sprintf('<select class="category_select" name="mapping[%s]">', $row->getData('reference_id'));
$html .= '<option value=""></option>';
foreach ($categories as $id => $name) {
$html .= sprintf(
'<option value="%s"%s>%s</option>',
$this->escapeHtml($id),
$id == $row->getData('category_id') ? ' selected="selected"' : '',
$this->escapeHtml($name)
);
}
$html .= '</select>';
return $html;
}
I need to add into the category dropdown, which is subcategories displaying under root category name.
Can anyone help me please.
Thank You.
I fixed the issue using following:
protected function _renderOptions(Varien_Object $row)
{
$categories = $this->getColumn()->getOptions();
$parentIdArray = array();
foreach ($categories as $id => $name) {
$category = Mage::getModel('catalog/category')->load($id);
$parentId = $category->getParentId();
if($parentId == 1){
$parentIdArray[] = $id;
}
}
$html = sprintf('<select class="category_select" name="mapping[%s]">', $row->getData('reference_id'));
$html .= '<option value=""></option>';
foreach ($parentIdArray as $parentId) {
$parentCategory = Mage::getModel('catalog/category')->load($parentId);
$name = $parentCategory->getName();
$html .= sprintf(
'<optgroup label="'.$name.'">
<option value="%s"%s>%s</option>
</optgroup>',
$this->escapeHtml($parentId),
$parentId == $row->getData('category_id') ? ' selected="selected"' : '',
$this->escapeHtml($name)
);
$categories = Mage::getModel('catalog/category')->getCategories($parentId);
$subCategories = $this->get_categories($categories);
foreach ($subCategories as $id => $name) {
$html .= sprintf(
'<option style="padding-left: 10px;" value="%s"%s>%s</option>',
$this->escapeHtml($id),
$id == $row->getData('category_id') ? ' selected="selected"' : '',
$this->escapeHtml($name)
);
}
}
$html .= '</select>';
return $html;
}
public function get_categories($categories) {
$subCategories = array();
foreach($categories as $category) {
$subCategory = Mage::getModel('catalog/category')->load($category->getId());
$subCategories[$subCategory->getId()] = $subCategory->getUrlPath();
if($category->hasChildren()) {
$children = Mage::getModel('catalog/category')->getCategories($category->getId());
$childrenCategories = $this->get_categories($children);
foreach ($childrenCategories as $id => $name) {
$subCategories[$id] = $name;
}
}
}
return $subCategories;
}

Resources