I'm using xampp 1.77 version, codeigniter 1.7.2 with flexigrid.
I follow step by step this tutorial https://gembelzillonmendonk.wordpress.com/2010/06/28/flexigrid-and-codeigniter-with-advanced-searching-with-example/#comment-353 but I don't understand which code must have flexigrid.php in CI_Folder\system\application\controllers\flexigrid.php.
My flexigrid.php code is this:
<?php
class Flexigrid extends Controller {
function Flexigrid ()
{
parent::Controller();
$this->load->helper('flexigrid');
}
function index()
{
//ver lib
$this->load->model('ajax_model');
$records = $this->ajax_model->get_select_countries();
$options = '';
foreach( $records as $v ) {
$options .= $v['name'] . ';';
}
$options = substr($options, 0, -1);
/*
* 0 - display name
* 1 - width
* 2 - sortable
* 3 - align
* 4 - searchable (2 -> yes and default, 1 -> yes, 0 -> no.)
*/
$colModel['id'] = array('ID',40,TRUE,'center',2);
$colModel['iso'] = array('ISO',40,TRUE,'center',0);
$colModel['name'] = array('Name',180,TRUE,'left',1);
$colModel['printable_name'] = array('Printable Name',120,TRUE,'left',1,'options' => array('type' => 'date'));
$colModel['iso3'] = array('ISO3',130, TRUE,'left',1, 'options' => array('type' => 'select', 'edit_options' => $options));
$colModel['numcode'] = array('Number Code',80, TRUE, 'right',1, 'options' => array('type' => 'select', 'edit_options' => ":All;AND:AND;KK:KK;RE:RE"));
$colModel['actions'] = array('Actions',80, FALSE, 'right',0);
/*
* Aditional Parameters
*/
$gridParams = array(
'width' => 'auto',
'height' => 400,
'rp' => 15,
'rpOptions' => '[10,15,20,25,40]',
'pagestat' => 'Displaying: {from} to {to} of {total} items.',
'blockOpacity' => 0.5,
'title' => 'Hello',
'showTableToggleBtn' => true
);
/*
* 0 - display name
* 1 - bclass
* 2 - onpress
*/
$buttons[] = array('Delete','delete','test');
$buttons[] = array('separator');
$buttons[] = array('Select All','add','test');
$buttons[] = array('DeSelect All','delete','test');
$buttons[] = array('separator');
//Build js
//View helpers/flexigrid_helper.php for more information about the params on this function
$grid_js = build_grid_js('flex1',site_url("/ajax"),$colModel,'id','asc',$gridParams,$buttons);
$data['js_grid'] = $grid_js;
$data['version'] = "0.36";
$data['download_file'] = "Flexigrid_CI_v0.36.rar";
$this->load->view('flexigrid',$data);
}
function example ()
{
$data['version'] = "0.36";
$data['download_file'] = "Flexigrid_CI_v0.36.rar";
$this->load->view('example',$data);
}
}
?>
When i type http://127.0.0.1/flexiadvanced/index.php/flexigrid browser give me a error:
Fatal error: Call to a member function query() on a non-object in C:\xampp\htdocs\flexiadvanced\system\application\models\ajax_model.php on line 34
this is the code of ajax_model.php
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
* Eye View Design CMS module Ajax Model
*
* PHP version 5
*
* #category CodeIgniter
* #package EVD CMS
* #author Frederico Carvalho
* #copyright 2008 Mentes 100Limites
* #version 0.1
*/
class Ajax_model extends Model
{
/**
* Instanciar o CI
*/
public function Ajax_model()
{
parent::Model();
$this->CI =& get_instance();
}
public function get_select_countries()
{
//Select table name
$table_name = "country";
//Build contents query
$separator = (string) ',';
//$this->db->select('concat(iso3, concat('. addcslashes($separator) .', iso3))')->from($table_name);
$query = $this->db->query("select concat(iso3, concat(':', iso3)) as name from country where iso3 is not null");
//Get contents
return $query->result_array();
}
public function get_countries()
{
//Select table name
$table_name = "country";
//Build contents query
$this->db->select('id,iso,name,printable_name,iso3,numcode')->from($table_name);
$this->CI->flexigrid->build_query();
//Get contents
$return['records'] = $this->db->get();
//echo $this->db->last_query();
//Build count query
$this->db->select('count(id) as record_count')->from($table_name);
$this->CI->flexigrid->build_query(FALSE);
$record_count = $this->db->get();
$row = $record_count->row();
//Get Record Count
$return['record_count'] = $row->record_count;
//Return all
return $return;
}
/**
* Remove country
* #param int country id
* #return boolean
*/
public function delete_country($country_id)
{
$delete_country = $this->db->query('DELETE FROM country WHERE id='.$country_id);
return TRUE;
}
}
?>
My database is called country and database table is called also country. This is information in CI_Folder\system\application\config
$db['default']['hostname'] = "localhost";
$db['default']['username'] = "root";
$db['default']['password'] = "";
$db['default']['database'] = "country";
$db['default']['dbdriver'] = "mysql";
Can you help me to write correct code inside flexigrid.php?
This is my code for CI_Folder\system\application\helpers\flexigrid_helper.php but is correct?
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
* Flexigrid CodeIgniter implementation
*
* PHP version 5
*
* #category CodeIgniter
* #package Flexigrid CI
* #author Frederico Carvalho (frederico#eyeviewdesign.com)
* #version 0.3
* Copyright (c) 2008 Frederico Carvalho (http://flexigrid.eyeviewdesign.com)
* Dual licensed under the MIT (MIT-LICENSE.txt)
* and GPL (GPL-LICENSE.txt) licenses.
*/
if (! function_exists('build_grid_js'))
{
/**
* Build Javascript to display grid
*
* #param grid id, or the div id
* #param url to make the ajax call
* #param array with colModel info:
* * 0 - display name
* * 1 - width
* * 2 - sortable
* * 3 - align
* * 4 - searchable (2 -> yes and default, 1 -> yes, 0 -> no.)
* * 5 - hidden (TRUE or FALSE, default is FALSE. This index is optional.)
* #param array with button info:
* * 0 - display name
* * 1 - bclass
* * 2 - onpress
* #param default sort column name
* #param default sort order
* #param array with aditional parameters
* #return string
*/
function build_grid_js($grid_id,$url,$colModel,$sortname,$sortorder,$gridParams = NULL,$buttons = NULL)
{
//Basic propreties
$grid_js = '<script type="text/javascript">$(document).ready(function(){';
$grid_js .= '$("#'.$grid_id.'").flexigrid({';
$grid_js .= "url: '".$url."',";
$grid_js .= "dataType: 'json',";
$grid_js .= "sortname: '".$sortname."',";
$grid_js .= "sortorder: '".$sortorder."',";
$grid_js .= "usepager: true,";
$grid_js .= "useRp: true,";
//Other propreties
if (is_array($gridParams))
{
//String exceptions that dont have ' '. Must be lower case.
$string_exceptions = array("rpoptions");
//Print propreties
foreach ($gridParams as $index => $value) {
//Check and print with or without ' '
if (is_numeric($value)) {
$grid_js .= $index.": ".$value.",";
}
else
{
if (is_bool($value))
if ($value == true)
$grid_js .= $index.": true,";
else
$grid_js .= $index.": false,";
else
if (in_array(strtolower($index),$string_exceptions))
$grid_js .= $index.": ".$value.",";
else
$grid_js .= $index.": '".$value."',";
}
}
}
$grid_js .= "colModel : [";
//Get colModel
foreach ($colModel as $index => $value) {
$grid_js .= "{display: '".$value[0]."', ".($value[2] ? "name : '".$index."', sortable: true," : "")." width : ".$value[1].", align: '".$value[3]."'".(isset($value[5]) && $value[5] ? ", hide : true" : "")."},";
//If item is searchable
if ($value[4] != 0)
{
//Start searchitems var
if (!isset($searchitems))
$searchitems = "searchitems : [";
$options = '';
if (isset($value['options'])) {
if (isset($value['options']['type'])) {
$options = ", type : '".$value['options']['type']."'";
switch($value['options']['type']) {
case 'select' : $options .= ", editoptions : { value : '" . $value['options']['edit_options'] . "' }"; break;
case 'date' :
case 'radio' :
case 'checkbox' :
default :
}
}
}
if ($value[4] == 2)
$searchitems .= "{display: '".$value[0]."', name : '".$index."', isdefault: true " .$options. "},";
else if ($value[4] == 1)
$searchitems .= "{display: '".$value[0]."', name : '".$index."' " .$options. "},";
}
}
//Remove the last ","
$grid_js = substr($grid_js,0,-1).'],';
$searchitems = substr($searchitems,0,-1).']';
//Add searchitems to grid
$grid_js .= $searchitems;
//Get buttons
if (is_array($buttons))
{
$grid_js .= ",buttons : [";
foreach ($buttons as $index => $value) {
if ($value[0] == 'separator')
$grid_js .= "{separator: true},";
else
$grid_js .= "{name: '".$value[0]."', bclass : '".$value[1]."', onpress : ".$value[2]."},";
}
//Remove the last ","
$grid_js = substr($grid_js,0,-1).']';
}
//Finalize
$grid_js .= "}); })</script>";
return $grid_js;
}
}
?>
I solve looking here: https://github.com/sameersemna/ci-flexigrid
Just download codeigniter-flexigrid project, import database and set database credentials in database.php.
This is the live example from github project:
http://ci-flexigrid.sameershemna.com/countries
I like this solution because you do not need grocery-crud library but just simply codeigniter
cheers
Related
I have been working on moodle 2.7 framework, my requirement is i wanted to show 2 different custom menu for Teacher and Student Role, at present I have created custom menu in template options, but I have no idea how to create multiple custom menu in moodle. so far I tried doing it by searching group id and then use if statement to assign custom menu but still no output, so I request can anybody help me to sort this issues.
You can extend the custom menu - https://docs.moodle.org/dev/Extending_the_theme_custom_menu
Then use has_capability() to see if the user can see the menu item.
Something like this (I haven't tried it)
// theme/themename/renderers.php
class theme_themename_core_renderer extends core_renderer {
protected function render_custom_menu(custom_menu $menu) {
$context = context_system::instance();
if (has_capability('local_plugin/menuname:view', $context)) {
$branchlabel = get_string('menuname', 'local_myplugin');
$branchurl = new moodle_url('/local/myplugin/index.php');
$branchtitle = $branchlabel;
$branchsort = 10000;
$branch = $menu->add($branchlabel, $branchurl, $branchtitle, $branchsort);
}
return parent::render_custom_menu($menu);
}
}
Russell,
below is code from renderes.php
<?php
/*
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
This plugin is part of Archaius theme.
#copyright 2013 Daniel Munera Sanchez
*/
class theme_archaius_core_renderer extends core_renderer {
/**
* Prints a nice side block with an optional header.
*
* The content is described
* by a {#link block_contents} object.
*
* #param block_contents $bc HTML for the content
* #param string $region the region the block is appearing in.
* #return string the HTML to be output.
*/
function block(block_contents $bc, $region) {
$bc = clone($bc); // Avoid messing up the object passed in.
if (empty($bc->blockinstanceid) || !strip_tags($bc->title)) {
$bc->collapsible = block_contents::NOT_HIDEABLE;
}
if ($bc->collapsible == block_contents::HIDDEN) {
$bc->add_class('hidden');
}
if (!empty($bc->controls)) {
$bc->add_class('block_with_controls');
}
$skiptitle = strip_tags($bc->title);
if (empty($skiptitle)) {
$output = '';
$skipdest = '';
} else {
$output = html_writer::tag('a', get_string('skipa', 'access', $skiptitle), array('href' => '#sb-' . $bc->skipid, 'class' => 'skip-block'));
$skipdest = html_writer::tag('span', '', array('id' => 'sb-' . $bc->skipid, 'class' => 'skip-block-to'));
}
$title = '';
if ($bc->title) {
$title = html_writer::tag('h2', $bc->title);
}
$controlshtml = $this->block_controls($bc->controls);
if ($title || $controlshtml) {
$output .= html_writer::tag('div', html_writer::tag('div', $title , array('class' => 'title')), array('class' => 'header-tab'));
}
$output .= html_writer::start_tag('div', $bc->attributes);
if ($title || $controlshtml) {
$output .= html_writer::tag('div', html_writer::tag('div', html_writer::tag('div', '', array('class'=>'block_action')). $title . $controlshtml, array('class' => 'title')), array('class' => 'header'));
}
$output .= html_writer::start_tag('div', array('class' => 'content'));
if (!$title && !$controlshtml) {
$output .= html_writer::tag('div', '', array('class'=>'block_action notitle'));
}
$output .= $bc->content;
if ($bc->footer) {
$output .= html_writer::tag('div', $bc->footer, array('class' => 'footer'));
}
$output .= html_writer::end_tag('div');
$output .= html_writer::end_tag('div');
if ($bc->annotation) {
$output .= html_writer::tag('div', $bc->annotation, array('class' => 'blockannotation'));
}
$output .= $skipdest;
$this->init_block_hider_js($bc);
return $output;
}
/*
* From boostrapbase
* Overriding the custom_menu function ensures the custom menu is
* always shown, even if no menu items are configured in the global
* theme settings page.
*/
public function custom_menu($custommenuitems = '') {
global $CFG;
//TODO: Check this in a different way
$langs = get_string_manager()->get_list_of_translations();
if ( (count($langs) < 2) and (empty($CFG->custommenuitems))) {
return '';
}else{
if (!empty($CFG->custommenuitems))
$custommenuitems .= $CFG->custommenuitems;
$custommenu = new custom_menu($custommenuitems, current_language());
return $this->render_custom_menu($custommenu);
}
}
// http://docs.moodle.org/dev/Extending_the_theme_custom_menu
protected function render_custom_menu(custom_menu $menu) {
global $CFG;
require_once($CFG->dirroot.'/course/lib.php');
//navigation mycourses is no supported since 2.4
if (isloggedin() && !isguestuser() &&
$mycourses = enrol_get_my_courses(NULL, 'visible DESC, fullname ASC')) {
$branchlabel = get_string('mycourses') ;
$branchurl = new moodle_url('/course/index.php');
$branchtitle = $branchlabel;
$branchsort = 8000 ;
$branch = $menu->add($branchlabel, $branchurl, $branchtitle, $branchsort);
foreach ($mycourses as $mycourse) {
$branch->add($mycourse->shortname, new moodle_url(
'/course/view.php',
array('id' => $mycourse->id)),
$mycourse->fullname
);
}
}
$course_id = $this->page->course->id;
if (isloggedin() && $course_id > 1) {
$branchlabel = get_string('grades');
$branchurl = new moodle_url('/grade/report/index.php?id='.$this->page->course->id);
$branchtitle = $branchlabel;
$branchsort = 9000;
$branch = $menu->add($branchlabel, $branchurl, $branchtitle, $branchsort);
}
//From boostrapbase
// TODO: eliminate this duplicated logic, it belongs in core, not
// here. See MDL-39565.
$addlangmenu = true;
$langs = get_string_manager()->get_list_of_translations();
if (
count($langs) < 2
or empty($CFG->langmenu)
or ($this->page->course != SITEID
and !empty($this->page->course->lang))) {
$addlangmenu = false;
}
if ($addlangmenu) {
$branchlabel = get_string('language');
$branchurl = new moodle_url('#');
$branch = $menu->add($branchlabel, $branchurl, $branchlabel, 10000);
foreach ($langs as $langtype => $langname) {
$branch->add($langname,
new moodle_url(
$this->page->url,
array('lang' => $langtype)
),
$langname
);
}
}
return parent::render_custom_menu($menu);
}
protected function render_custom_menu_item(custom_menu_item $menunode) {
$transmutedmenunode = new theme_archaius_transmuted_custom_menu_item($menunode);
return parent::render_custom_menu_item($transmutedmenunode);
}
}
i take the code of Bayesian from site http://www.ibm.com/developerworks/library/wa-bayes3/
i am not able to remove the error of undefined from the select query.
here is the code :
<?php
/**
* #package NaiveBayes
* #author Paul Meagher <paul#datavore.com>
* #license PHP License v3.0
* #version 0.2
*
* This class must be supplied with training example data, attribute names,
* and class names. Once this information is supplied, you can then invoke
* the learn and classify methods.
*/
class NaiveBayes {
/**
* Database table to use.
*/
var $table = null;
/**
* 1D array of attributes names. Attribute names should
* correspond to field names in the specified database
* table.
*/
var $attributes = array();
/**
* 1D array of attribute values to classify.
*/
var $attribute_values = null;
/**
* Specifies table column holding classification values.
*/
var $class = array();
/**
* Specifies allowable classification values.
*/
var $class_values = array();
/**
* 3D array containing joint frequency infomation about
* how class names and attribute names covary. Used to
* derive the likelihood array in the classify method.
*/
var $joint_frequency = array();
/**
* 1D array containing prior probability of each class name.
*/
var $priors = array();
/**
* 1D array containing likeliood of the data for each class.
*/
var $likelihoods = array();
/**
* 1D array containing the posterior probability of each class
* name given the supplied attribute values.
*/
var $posterior = array();
/**
* Denotes the number of training examples used for learning.
*/
var $n = 0;
/**
* When the classifier method is called, $predict is set to
* class name with the highest posterior probability.
*/
var $predict = null;
/**
* Set database table to use.
*/
function setTable($table)
{
$this->table = $table;
}
/**
* Set attribute columns to use. The attribute columns should
* correspond to fields in your database table.
*/
function setAttributes($columns)
{
foreach($columns as $column)
{
$this->attributes[] = $column;
}
}
/**
* Set classification column names to use.
*/
function setClass($column) {
$this->class = $column;
}
/**
* Set classification names to use.
*/
function setClassValues($values) {
foreach($values as $value) {
$this->class_values[] = $value;
}
}
function inimat($lr, $ur, $lc, $uc, &$a, $x){
for(; $lr<=$ur; $lr++)
for($j=$lc; $j<=$uc; $j++) $a[$lr][$j]=$x;
}
/**
* Learn the prior probability of each class and the
* joint frequency of each class and attribute.
*/
function learn()
{
// include connection file
include("connect.php");
// parse array
foreach ($this->attributes as $attribute)
// get field list
$field_list = substr($attribute, 0, -1);
// parse array
foreach ($this->class_values as $class) {
// make an sql query
$sql = "SELECT $field_list FROM " . $this->table . " WHERE " . $this->class . "='$class'";
// execute sql query
$result = mysql_query($sql);
$this->priors["$class"] = mysql_num_rows($result);
while ($row = mysql_fetch_assoc($result))
{
foreach ($this->attributes as $attribute) {
// if row attribute haven't any data then set default value
$attribute_value = isset($row[$attribute]) ? $row[$attribute] : 0;
$this->joint_frequency[$class][$attribute][$attribute_value]++;
}
}
}
}
/**
* Given a set of attribute values, this routine will
* predict the class they most likley belong to.
*/
function classify($attribute_values) {
$this->attribute_values = $attribute_values;
$this->n = array_sum($this->priors);
$this->max = 0;
foreach($this->class_values as $class) {
$counter = 0;
$this->likelihoods[$class] = 1;
foreach($this->attributes as $attribute) {
$attribute_value = $attribute_values[$counter];
$joint_freq = $this->joint_frequency[$class][$attribute][$attribute_value];
$likelihood = $joint_freq / $this->priors[$class];
if ($joint_freq > 0) {
$this->likelihoods[$class] = $this->likelihoods[$class] * $likelihood;
}
$counter++;
}
$prior = $this->priors[$class] / $this->n;
$this->posterior[$class] = $this->likelihoods[$class] * $prior;
if ($this->posterior[$class] > $this->max) {
$this->predict = $class;
$this->max = $this->posterior[$class];
}
}
}
/**
* Output the posterior probabilities that were computed by
* the classify method.
*/
function toHTML() {
foreach($this->class_values as $class) {
$equation = "P($this->class = ". $class ." | ";
$counter = 0;
foreach($this->attributes as $attribute) {
$attribute_value = $this->attribute_values[$counter];
$equation .= $attribute ."=". $attribute_value ." & ";
$counter++;
}
$equation = substr($equation, 0, -7);
$equation .= ") = ". $this->posterior[$class];
if ($class == $this->predict) {
$equation .= " <sup>*</sup>";
}
echo $equation ."<br />";
}
}
}
?>
it give error
Notice: Undefined index: q1 in C:\wamp\www\Bayes3\NaiveBayes.php on line 130 : $attribute_value = $row[$attribute];
Notice: Undefined index: 0 in C:\wamp\www\Bayes3\NaiveBayes.php on line 131 :
$this->joint_frequency[$class][$attribute][$attribute_value]++;
Notice: Undefined index: 1 in C:\wamp\www\Bayes3\NaiveBayes.php on line 150 :
$joint_freq = $this->joint_frequency[$class][$attribute][$attribute_value];
kindly help me in this
this can be done through isset function
You can use isset function:
<?php
/**
* Learn the prior probability of each class and the
* joint frequency of each class and attribute.
*/
function learn()
{
// include connection file
include("connect.php");
// parse array
foreach ($this->attributes as $attribute)
// get field list
$field_list = substr($attribute, 0, -1);
// parse array
foreach ($this->class_values as $class) {
// make an sql query
$sql = "SELECT $field_list FROM " . $this->table . " WHERE " . $this->class . "='$class'";
// execute sql query
$result = mysql_query($sql);
$this->priors["$class"] = mysql_num_rows($result);
while ($row = mysql_fetch_assoc($result)) {
foreach ($this->attributes as $attribute) {
// if row attribute haven't any data then set default value
$attribute_value = isset($row[$attribute]) ? $row[$attribute] : 0;
$this->joint_frequency[$class][$attribute][$attribute_value]++;
}
}
}
}
?>
To suppress the error you can add '#' symbol before the variable which is throwing the error.
Add # like
$attribute_value = #$row[$attribute];
I have a tree login page as my first page in a survey. The issue is that , if the user does not select any node and clicks on the next button he is redirected to the same page . The problem is that he does not get any error message .
I want the user to get an error message 'Please select a group'
Please look into the below code which does this action
(P.S check the Display() function )
Correct me where I am going wrong
<?php
/**
* File: TreeLoginWidget.php
*
*
* Purpose: display tree page.
*
* Dependents: none
*
* Dependencies: SurveyItem
*
* Classes:
* 1. PinWidget
*
* Interface/public functions:
*
* Notes: ???
*
* Todo: none
*
**/
class DisplayTreeLoginWidget extends DisplayItem
{
function DisplayTreeLoginWidget(& $sourceObj)
{
// debug
if( $pDebugTraceFlag == _ID_FLAG_ON ) GDebugTraceFunc( __CLASS__." :: ".__FUNCTION__ );
$this->node = 0;
$surveywidget = getDataFromSession("surveywidget");
DisplayItem::DisplayItem();
$_SESSION["profile"]["rootNode"]=0;
if($_GET["nodeId"]) {
setDataToSession("postVar","");
}
$this->sourceObj =& $sourceObj;
}
/**
* Purpose: display pin page label text
*
* Input Params: none
*
* Output Params: none
*
* Return Value: none
*
* Notes:
*/
function display()
{
global $skin_path,$skin,$path;
setDataToSession("skipPage", 0);
setDataToSession('HideSave&Resume',0);
$currentPageNumber = currentPageNumber();
if($currentPageNumber!=1) {
setDataToSession('HideSave&Resume',1);
}
echo "<script type=\"text/javascript\" src=\"".$path."../lib/java/commonFuncs.js\"></script>";
// include the header
include_once ("../lib/include/path.inc.php");
include_once ("../lib/include/jshelper.php");
include_once("display/tree.inc.php");
include_once("display/commonTreeLayout.php");
include_once ("../lib/include/commonTreeCode.php");
setUpTreeAppProperty();
$postVar = getDataFromSession("postVar");
if(is_array($postVar)) {
$_POST = $postVar;
}
if($this->sourceObj->displayType == "expanded") {
$postVar["Expand_All"] = "Expand All";
$this->sourceObj->displayType = "";
}
if($this->sourceObj->levelShowing != "") {
setDataToSession("levelShowing",$this->sourceObj->levelShowing);
}
setUpElist($postVar, $_GET);
$verifiedStartingNode = getTreeStartingNode();
/** $matchedIdArr contains matched nodeIds or empty if no matches found/no search performed */
$matchedIdArr = doSearch($verifiedStartingNode, $postVar);
$eList = getEList();
$Tree = new TreeWithRadioButton($this->sourceObj);
$Tree->reSetupElist();
$startingNode = &$Tree->nodesArr[$verifiedStartingNode];
echo "<div class=\"body2 IE6trans\">";
displaySearchTable();
if(!$postVar["searchSubmit"]) {
$matchedIdArr = array(getDataFromSession("data,node_id"));
}
displayTree('Search Organization Structure', '', '', $startingNode, $eList, $matchedIdArr, $maxDepth, get_path_prefix(),$this->sourceObj->_errorMsg,$this->sourceObj->_prompt);
echo "<script type=\"text/javascript\">";
echo "$(document).ready(function () { $('input[name=\"wildText\"]').keyup(function(event){ if(event.keyCode == 13){ $('input[name=\"searchSubmit\"]').click(); } }); });";
echo "</script>";
echo "</div>";
}
/**
* Purpose: storing error message to _errorMsg
*
* Input Params: none
*
* Output Params: none
*
* Return Value: Boolean - true or false
*
* Notes:
*/
function validate()
{
// debug
if( $pDebugTraceFlag == _ID_FLAG_ON ) GDebugTraceFunc( __CLASS__." :: ".__FUNCTION__ );
$surveywidget = getDataFromSession('surveywidget');
$this->getPostData();
$this->sourceObj->_errorMsg = "";
$lastVisitedWidgetOid_Tree = getDataFromSession("lastVisitedWidgetOid_Tree");
setDataToSession("lastVisitedWidgetOid" , $lastVisitedWidgetOid_Tree);
setLoginUserLanguage($this->node);
$operations = ((strcmp($this->operation,getText2($surveywidget->saveResumeButtonText)) == 0)||
(strcmp($this->operation,getText2($surveywidget->backButtonText)) == 0)||
(strcmp($this->operation,getText2($surveywidget->nextButtonText)) == 0));
if(($operations) && ($this->node != "")) {
setDataToSession("data,node_id",$this->node);
// used to track the node id assigned to this pin when more than one login is used
setDataToSession("tree_login,node_id",$this->node);
setDataToSession("tree_login_before_saveresume,node_id",$this->node);
//Custom -
$oids = getListOfOidAndNodes(Array($this->node));
$_SESSION["conditionNodeList"] = $oids;
//End Custom
if(!getDataFromSession('multiLoginIndex')) {
$multiLoginIndex = 1;
} else {
$multiLoginIndex = getDataFromSession('multiLoginIndex');
}
$multiLoginIndex++;
setDataToSession("multiLoginIndex",$multiLoginIndex);
$this->sourceObj->_errorMsg = "";
} else if(($operations) && ($this->node == "")){
$this->sourceObj->_errorMsg = "Please select a group";
return false;
} else {
return false;
}
if($this->node == "") {
$this->node = 0;
}
// user click save&resume before visiting login page, we are redirecting to login page, That time user enter invalid node_id we are mainting save&resume flag to 1 for displaying submitbutton(it act like as save&resume)
if(getDataFromSession('save&resumeflag') == 1) {
setDataToSession('save&resumeloginpage',1);
}
return true;
}
/**
* Purpose: get post data
*
* Input Params: none
*
* Output Params: none
*
* Return Value: none
*
* Notes:
*/
function getPostData()
{
// debug
if( $pDebugTraceFlag == _ID_FLAG_ON ) GDebugTraceFunc( __CLASS__." :: ".__FUNCTION__ );
$postVar["exactText"] = (empty($_REQUEST["exactText"])==1) ?"" :stripslashes($_REQUEST["exactText"]);
$postVar["wildText"] = (empty($_REQUEST["wildText"])==1) ?"" :stripslashes($_REQUEST["wildText"]);
$postVar["searchSubmit"] = (empty($_REQUEST["searchSubmit"])==1) ?"" :$_REQUEST["searchSubmit"];
$postVar["Collapse_All"] = (empty($_REQUEST["Collapse_All"])==1) ?"" :$_REQUEST["Collapse_All"];
$postVar["idText"] = (empty($_REQUEST["idText"])==1) ?"" :$_REQUEST["idText"];
$postVar["node"] = (empty($_REQUEST["node"])==1) ?"" :$_REQUEST["node"];
$this->node = ($_REQUEST["node"] == "") ?"" :$_REQUEST["node"];
$this->operation = (empty($_REQUEST["Operation"])==1) ?"" :$_REQUEST["Operation"];
if($postVar["Collapse_All"]) {
$postVar["wildText"] = "";
}
setDataToSession('postVar',$postVar);
setDataToSession('Operation',$this->operation);
setDataToSession('node',$this->node);
}
}
?>
Your code is long, and I didn't read it.
But the typical way to do this is to pass a url parameter, and if the parameter exists print it out as a message.
I installed joomla 1.7(window/xampp/php 5.3) and my current template is beez_20. I have to override the pagination.php and to do so I copied the pagination.php from
\libraries\joomla\html
to
\templates\beez_20\html. When I reload the home page, I am getting a broken template as in the following picture.
I get the normal page when I remove the pagination.php from the html folder. I believe this is the correct method to override the pagination.php
what is missing ? need to change any configuration ? please post your comments
Thanks in advance
I do belive this is the correct way to do it...
Here is a pagnation.php for you to try with (works for me):
<?php
// no direct access
defined('_JEXEC') or die('Restricted access');
/**
* This is a file to add template specific chrome to pagination rendering.
*
* pagination_list_footer
* Input variable $list is an array with offsets:
* $list[limit] : int
* $list[limitstart] : int
* $list[total] : int
* $list[limitfield] : string
* $list[pagescounter] : string
* $list[pageslinks] : string
*
* pagination_list_render
* Input variable $list is an array with offsets:
* $list[all]
* [data] : string
* [active] : boolean
* $list[start]
* [data] : string
* [active] : boolean
* $list[previous]
* [data] : string
* [active] : boolean
* $list[next]
* [data] : string
* [active] : boolean
* $list[end]
* [data] : string
* [active] : boolean
* $list[pages]
* [{PAGE}][data] : string
* [{PAGE}][active] : boolean
*
* pagination_item_active
* Input variable $item is an object with fields:
* $item->base : integer
* $item->link : string
* $item->text : string
*
* pagination_item_inactive
* Input variable $item is an object with fields:
* $item->base : integer
* $item->link : string
* $item->text : string
*
* This gives template designers ultimate control over how pagination is rendered.
*
* NOTE: If you override pagination_item_active OR pagination_item_inactive you MUST override them both
*/
function pagination_list_footer($list)
{
// Initialize variables
$lang =& JFactory::getLanguage();
$html = "<div class=\"list-footer\">\n";
if ($lang->isRTL())
{
$html .= "\n<div class=\"counter\">".$list['pagescounter']."</div>";
$html .= $list['pageslinks'];
$html .= "\n<div class=\"limit\">".JText::_('Display Num').$list['limitfield']."</div>";
}
else
{
$html .= "\n<div class=\"limit\">".JText::_('Display Num').$list['limitfield']."</div>";
$html .= $list['pageslinks'];
$html .= "\n<div class=\"counter\">".$list['pagescounter']."</div>";
}
$html .= "\n<input type=\"hidden\" name=\"limitstart\" value=\"".$list['limitstart']."\" />";
$html .= "\n</div>";
return $html;
}
function pagination_list_render($list)
{
// Initialize variables
$lang =& JFactory::getLanguage();
$html = "<div class=\"pagination\"><ul>";
// Reverse output rendering for right-to-left display
if($lang->isRTL())
{
$html .= "<li class=\"pagination-start\">".$list['start']['data']."</li>";
$html .= "<li class=\"pagination-prev\">".$list['previous']['data']."</li>";
$list['pages'] = array_reverse( $list['pages'] );
foreach( $list['pages'] as $page ) {
if($page['data']['active']) {
// $html .= '<strong>';
}
$html .= "<li>".$page['data']."</li>";
if($page['data']['active']) {
// $html .= '</strong>';
}
}
$html .= "<li class=\"pagination-next\">".$list['next']['data']."</li>";
$html .= "<li class=\"pagination-end\">".$list['end']['data']."</li>";
// $html .= '«';
}
else
{
foreach( $list['pages'] as $page )
{
if($page['data']['active']) {
// $html .= '<strong>';
}
$html .= "<li>".$page['data']."</li>";
if($page['data']['active']) {
// $html .= '</strong>';
}
}
}
$html .= "</ul></div>";
return $html;
}
?>
You should not override the entire pagination.php in the manner you tried. You can only override certain functions. The reason you are seeing this page is because if you copied the entire pagination.php file with out changing anything, so you are re-declaring the JPagination class and you can't do that.
When you are try to make changes to the pagination.php you should only re-write the functions you wish to override not copy the entire file.
Please check out this article it's a little dated but the information still applies even in J! 2.5
http://docs.joomla.org/Understanding_Output_Overrides
I found this awesome code online to help with pagination, and it's working well, the only problem is: each page displays the same 4 rows.
Any ideas will be much appreciated
<?php
//Include the PS_Pagination class
include('includes/ps_pagination.php');
//Connect to mysql db
$conn = mysql_connect("localhost", "root", "root");
mysql_select_db('database',$conn);
$sql = "SELECT * FROM studies WHERE niche = '{$_GET['niche']}'";
//Create a PS_Pagination object
$pager = new PS_Pagination($conn,$sql,4,5);
//The paginate() function returns a mysql
//result set for the current page
$rs = $pager->paginate();
//Loop through the result set
while($row = mysql_fetch_assoc($rs)) {
$a=0;
while ($a < $num) {
$id=mysql_result($result,$a,"id");
$title=mysql_result($result,$a,"title");
$strategies=mysql_result($result,$a,"strategies");
$client=mysql_result($result,$a,"client");
$copy=mysql_result($result,$a,"copy");
$thumbmedia=mysql_result($result,$a,"thumbmedia");
$niche=mysql_result($result,$a,"niche");
echo '<div class="container"><p class="subheadred">'.$title.'</p></div>';
echo '<div class="containerstudy"><div class="column1"><p class="subheadsmall">Strategies</p><p class="sidebarred">'.$strategies.'</p>';
echo '<p class="subheadsmall">Client</p><p class="sidebargrey">'.$client.'</p></div>';
echo '<div class="column2"><p class="bodygrey">'.substr($copy, 0, 300).'...more</p></div>';
echo '<div class="column3"><img src="images/'.$thumbmedia.'" height="160" /></div></div>';
$a++;
}
}
//Display the navigation
echo $pager->renderNav();
?>
This is the included file:
<?php
/**
* PHPSense Pagination Class
*
* PHP tutorials and scripts
*
* #package PHPSense
* #author Jatinder Singh Thind
* #copyright Copyright (c) 2006, Jatinder Singh Thind
* #link http://www.phpsense.com
*/
// ------------------------------------------------------------------------
class PS_Pagination {
var $php_self;
var $rows_per_page; //Number of records to display per page
var $total_rows; //Total number of rows returned by the query
var $links_per_page; //Number of links to display per page
var $sql;
var $debug = false;
var $conn;
var $page;
var $max_pages;
var $offset;
/**
* Constructor
*
* #param resource $connection Mysql connection link
* #param string $sql SQL query to paginate. Example : SELECT * FROM users
* #param integer $rows_per_page Number of records to display per page. Defaults to 10
* #param integer $links_per_page Number of links to display per page. Defaults to 5
*/
function PS_Pagination($connection, $sql, $rows_per_page = 1, $links_per_page = 5) {
$this->conn = $connection;
$this->sql = $sql;
$this->rows_per_page = $rows_per_page;
$this->links_per_page = $links_per_page;
$this->php_self = htmlspecialchars($_SERVER['PHP_SELF']);
if(isset($_GET['page'])) {
$this->page = intval($_GET['page']);
}
}
/**
* Executes the SQL query and initializes internal variables
*
* #access public
* #return resource
*/
function paginate() {
if(!$this->conn) {
if($this->debug) echo "MySQL connection missing<br />";
return false;
}
$all_rs = #mysql_query($this->sql);
if(!$all_rs) {
if($this->debug) echo "SQL query failed. Check your query.<br />";
return false;
}
$this->total_rows = mysql_num_rows($all_rs);
#mysql_close($all_rs);
$this->max_pages = ceil($this->total_rows/$this->rows_per_page);
//Check the page value just in case someone is trying to input an aribitrary value
if($this->page > $this->max_pages || $this->page <= 0) {
$this->page = 1;
}
//Calculate Offset
$this->offset = $this->rows_per_page * ($this->page-1);
//Fetch the required result set
$rs = #mysql_query($this->sql." LIMIT {$this->offset}, {$this->rows_per_page}");
if(!$rs) {
if($this->debug) echo "Pagination query failed. Check your query.<br />";
return false;
}
return $rs;
}
/**
* Display the link to the first page
*
* #access public
* #param string $tag Text string to be displayed as the link. Defaults to 'First'
* #return string
*/
function renderFirst($tag='First') {
if($this->page == 1) {
return $tag;
}
else {
return ''.$tag.'';
}
}
/**
* Display the link to the last page
*
* #access public
* #param string $tag Text string to be displayed as the link. Defaults to 'Last'
* #return string
*/
function renderLast($tag='Last') {
if($this->page == $this->max_pages) {
return $tag;
}
else {
return ''.$tag.'';
}
}
/**
* Display the next link
*
* #access public
* #param string $tag Text string to be displayed as the link. Defaults to '>>'
* #return string
*/
function renderNext($tag=' >>') {
if($this->page < $this->max_pages) {
return ''.$tag.'';
}
else {
return $tag;
}
}
/**
* Display the previous link
*
* #access public
* #param string $tag Text string to be displayed as the link. Defaults to '<<'
* #return string
*/
function renderPrev($tag='<<') {
if($this->page > 1) {
return ''.$tag.'';
}
else {
return $tag;
}
}
/**
* Display the page links
*
* #access public
* #return string
*/
function renderNav() {
for($i=1;$i<=$this->max_pages;$i+=$this->links_per_page) {
if($this->page >= $i) {
$start = $i;
}
}
if($this->max_pages > $this->links_per_page) {
$end = $start+$this->links_per_page;
if($end > $this->max_pages) $end = $this->max_pages+1;
}
else {
$end = $this->max_pages;
}
$links = '';
$niche = $_GET['niche'];
for( $i=$start ; $i<$end ; $i++) {
if($i == $this->page) {
$links .= " $i ";
}
else {
$links .= ' '.$i.' ';
}
}
return $links;
}
/**
* Display full pagination navigation
*
* #access public
* #return string
*/
function renderFullNav() {
return $this->renderFirst().' '.$this->renderPrev().' '.$this->renderNav().' '.$this->renderNext().' '.$this->renderLast();
}
/**
* Set debug mode
*
* #access public
* #param bool $debug Set to TRUE to enable debug messages
* #return void
*/
function setDebug($debug) {
$this->debug = $debug;
}
}
?>
Just at first glance i see your query is repeating itself from the beginning every time you run it, so that means every time you run it it searches from the beggining. you need a counter to tell it where to start from on the next page. something like:
$sql = "SELECT * FROM studies WHERE niche = '{$_GET['niche']}' limit $startPoint, $offset";
that way the offset is the same as the number of items you want per page and the $startPoint is the point at which the search beggins at the next iteration.
somehting like this would work:
if(!$startPoint){$startPoint = 0;}else{$startPoint = {$_GET['$startPoint'];}
within your code pass the start point back to the query and increasing it by the offset after each iteration.
Please bear in mind i've not taking into consideration stuff like injection, and the fact that the variable $num doesn't seem to come from anywhere in the 1st file. I cant see where you initialized it so as to test $a against it.
After looking at your code more in depth i found a few things that need to be changed to get it work in the least here is the changed code:
<?php
//Include the PS_Pagination class
include('includes/ps_pagination.php');
//Connect to mysql db
$conn = mysql_connect("localhost", "root", "root");
mysql_select_db('database',$conn);
$sql = "SELECT * FROM studies";// WHERE niche = '{$_GET['niche']}'";
//Create a PS_Pagination object
$pager = new PS_Pagination($conn,$sql,4,5);
//The paginate() function returns a mysql
//result set for the current page
$rs = $pager->paginate();
//Loop through the result set
while($row = mysql_fetch_assoc($rs)) {
// $a=0;
// while ($a < $num) {
// $id=mysql_result($result,$a,"id");
// $title=mysql_result($result,$a,"title");
// $strategies=mysql_result($result,$a,"strategies");
// $client=mysql_result($result,$a,"client");
// $copy=mysql_result($result,$a,"copy");
// $thumbmedia=mysql_result($result,$a,"thumbmedia");
// $niche=mysql_result($result,$a,"niche");
$id=$row['id'];
$title=$row['title'];
$strategies=$row['strategies'];
$client=$row['client'];
$copy=$row['copy'];
$thumbmedia=$row['thumbmedia'];
$niche=$row['niche'];
echo '<div class="container"><p class="subheadred">'.$title.'</p></div>';
echo '<div class="containerstudy"><div class="column1"><p class="subheadsmall">Strategies</p><p class="sidebarred">'.$strategies.'</p>';
echo '<p class="subheadsmall">Client</p><p class="sidebargrey">'.$client.'</p></div>';
echo '<div class="column2"><p class="bodygrey">'.substr($copy, 0, 300).'...more</p></div>';
echo '<div class="column3"><img src="images/'.$thumbmedia.'" height="160" /></div></div>';
// $a++;
// }
}
//Display the navigation
echo $pager->renderNav();
?>
Notice i have commented out some part that where not necessary
the variable $a was meaningless as it compared to $num which doesn't exist therefore nothing would show. Now these lines:
// $id=mysql_result($result,$a,"id");
// $title=mysql_result($result,$a,"title");
// $strategies=mysql_result($result,$a,"strategies");
// $client=mysql_result($result,$a,"client");
// $copy=mysql_result($result,$a,"copy");
// $thumbmedia=mysql_result($result,$a,"thumbmedia");
// $niche=mysql_result($result,$a,"niche");
where also wrong as you are trying to get the result set from $result. at no place had you put the result set into $result the class you have imported does that and puts the result set into an identifier called $rs.
Since you are using $row = mysql_fetch_assoc($rs) to read through the result set then to get the variables all you need to do is get the column row through an array like this
$id=$row['id'];
and so on. once you do that then the code should work as expected. However this brings us back to this:
$sql = "SELECT * FROM studies WHERE niche = '{$_GET['niche']}'";
i had to get the last part out in that this variable is not getting passed back into the query string (seeing you are using get), the other problem is the 1st time you load the page this variable 'niche' doesn't exist so the 1st time you run the code you will get a blank page, unless this script is accessed through a link that passes in this variable. at this point i have left it commented out as am not sure what you were trying to do through niche.
Hope that helps.
Do you have page set in your query string?
I think that if you changed the paginate function, so that it would have one parameter $page and you would set $this->page = $page at the begining of the function, it would work.
You would also have to change the calling of this function in your code to $pager->paginate($_GET['page']).
The pager is also very inefficient, it gets the whole query just to find out, how many rows does the response have. I would use something like:
$all_rs = #mysql_query('SELECT COUNT(*) FROM (' . $this->sql . ')');
if(!$all_rs) {
if($this->debug) echo "SQL query failed. Check your query.<br />";
return false;
}
$this->total_rows = mysql_result($all_rs, 0, 0);
#mysql_close($all_rs);
I'm not sure what this pagination library does with the index of the rows, but you are always setting $a to 0. Perhaps the index is not relative to the page but to the overall recordset being returned?
In other words, what if you set $a to 0 on page 1, 4 on page 2, etc.
You should be able to use $rows_per_page and $page to calculate it. Or perhaps that is the $offset value, so that you set $a to offset and loop it until you hit $rows_per_page additional rows.
Edit clarifying solution:
So what I see you could do is:
$a=0;
while ($a < $pager->rows_per_page) {
$row = $a + $pager->offset;
$id=mysql_result($result,$row,"id");
$title=mysql_result($result,$row,"title");
$strategies=mysql_result($result,$row,"strategies");
$client=mysql_result($result,$row,"client");
$copy=mysql_result($result,$row,"copy");
$thumbmedia=mysql_result($result,$row,"thumbmedia");
$niche=mysql_result($result,$row,"niche");
...
$a++;
}