I have joomla installed with custom functions, i need to use those custom functions in another php script that i have
in the joomla site i have functions in libraries>rvv>factory.php
and components>com_customs folder
on the view tmpl page the one of the functions is shown <?php $points = RFactory::getPoint($downLine->agentID); ?>
<th><?php echo $points['left'].' - '.$points['right']; ?></th>
on the component function script file
public function getDownLine($agentId)
{
ini_set('max_execution_time', 600); //300 seconds = 5 minutes
$this->downLinesRecursion($agentId);
function cmp( $a, $b )
{
if( $a->agentID == $b->agentID ){ return 0 ; }
return ($a->agentID < $b->agentID) ? -1 : 1;
}
usort($this->downLine,'cmp');
$this->_total = count($this->downLine);
$endDownLine = array_splice($this->downLine, $this->getState('limitstart'), $this->getState('limit'));
return $endDownLine;
}
protected function downLinesRecursion($agentId)
{
$downLineIDs = RFactory::getDownLines($agentId);
if($downLineIDs){
foreach ($downLineIDs as $downLineID){
$agent = RFactory::getAgent($downLineID->id);
$this->downLine[] = $agent;
$this->downLinesRecursion($agent->agentID);
}
}
}
public function getAgentExisting($agentId)
{
ini_set('max_execution_time', 300); //300 seconds = 5 minutes
$this->subAgentID = $agentId;
$this->existingRecursion($this->agentID);
return $this->agentExisting;
}
protected function existingRecursion($agentId)
{
$downLineIDs = RFactory::getDownLines($agentId);
if($downLineIDs){
foreach ($downLineIDs as $downLineID){
if($downLineID->id == $this->subAgentID){
$this->agentExisting = true;
}else{
$this->existingRecursion($downLineID->id);
}
}
}
}
public function getAgentId($username)
{
$userId = $this->getUserId($username);
if($userId){
$agentIds = RFactory::getAgentIds($userId);
foreach ($agentIds as $AgentId) {
$agentId = $AgentId->id;
break;
}
return $agentId;
}else {
return false;
}
}
ON THE FACTORY FILE:
public static function getAgent($agentId)
{
$db = JFactory::getDBO();
$query = $db->getQuery(true);
$query->select(' ag.id AS agentID, ag.user_id AS agentUserID, ag.parent_client_id, ag.directe_client_id, ag.position, date(ag.reg_time) AS joinDate, ag.offers_id, ag.cash');
$query->select(' ofr.* ');
$query->select(' usrinf.* ');
$query->select(' usr.name AS agentName, usr.username, usr.email, date(usr.registerDate) AS regDate ');
$query->select(' stk.value AS stockValue ');
$query->from(' #__r_clients AS ag ');
$query->leftJoin(' #__r_offers AS ofr ON ofr.id = ag.offers_id ');
$query->leftJoin(' #__r_clients_info AS usrinf ON usrinf.user_id = ag.user_id ');
$query->leftJoin(' #__users AS usr On usr.id = ag.user_id ');
$query->leftJoin(' #__r_stock AS stk On stk.client_id = ag.id ');
$query->where(' ag.id = '.$agentId);
$db->setQuery((string)$query);
$data = $db->loadObject();
if (!$db->query()) {
JError::raiseError(500, $db->getErrorMsg());
return false;
}else {
if ($db->getNumRows() < 1){
return false;
}else{
return $data;
}
}
}
public static function getAgents()
{
$db = JFactory::getDBO();
$query = $db->getQuery(true);
$query->select(' ag.id AS agentID, ag.user_id AS agentUserID, ag.parent_client_id, ag.directe_client_id, ag.position, date(ag.reg_time) AS joinDate, ag.offers_id, ag.cash');
$query->select(' ofr.* ');
$query->select(' usr.name AS agetName, usr.username, usr.email, usr.registerDate ');
$query->from(' #__r_clients AS ag ');
$query->leftJoin(' #__r_offers AS ofr ON ofr.id = ag.offers_id ');
$query->leftJoin(' #__users AS usr On usr.id = ag.user_id ');
$db->setQuery((string)$query);
$data = $db->loadObjectList();
if (!$db->query()) {
JError::raiseError(500, $db->getErrorMsg());
return false;
}else {
if ($db->getNumRows() < 1){
return false;
}else{
return $data;
}
}
}
public static function getDownLines($agentId)
{
$db = JFactory::getDBO();
$query = $db->getQuery(true);
$query->select(' id ');
$query->from(' #__r_clients ');
$query->where(' parent_client_id = '.$agentId);
$db->setQuery((string)$query);
$data = $db->loadObjectList();
if (!$db->query()) {
JError::raiseError(500, $db->getErrorMsg());
return false;
}else {
if ($db->getNumRows() < 1){
return false;
}else{
return $data;
}
}
}
public static function getPoint($agentId)
{
$downLines = self::getDownLines($agentId);
self::$rightPoint = 0;
self::$leftPoint = 0;
if($downLines){
foreach ($downLines as $downLine){
$agent = self::getAgent($downLine->id);
if($agent->position == 'R'){
self::$rightPoint += $agent->point;
self::rightPointRecursion($agent->agentID);
}else {
self::$leftPoint += $agent->point;
self::leftPointRecursion($agent->agentID);
}
}
return $pointArray = array('right' => self::$rightPoint, 'left' => self::$leftPoint);
}else {
return $pointArray = array('right' => 0, 'left' => 0);
}
}
private function rightPointRecursion($agentId)
{
$downLines = self::getDownLines($agentId);
if($downLines){
foreach ($downLines as $downLine){
$agent = self::getAgent($downLine->id);
self::$rightPoint += $agent->point;
self::rightPointRecursion($agent->agentID);
}
}
}
private function leftPointRecursion($agentId)
{
$downLines = self::getDownLines($agentId);
if($downLines){
foreach ($downLines as $downLine){
$agent = self::getAgent($downLine->id);
self::$leftPoint += $agent->point;
self::leftPointRecursion($agent->agentID);
}
}
}
the custom joomla code is inside the components>com_hierarchical>hierarchical.php contains :
JLoader::register('HierarchicalHelper', dirname(__FILE__) . DS . 'helpers'. DS . 'hierarchical.php');
jimport('joomla.application.component.controller');
$document =& JFactory::getDocument();
$script = JURI::base(true).'/components/com_hierarchical/assist/gscript.js';
$style = JURI::base(true).'/components/com_hierarchical/assist/gstyle.css';
$document->addScript($script);
$document->addStyleSheet($style);
$controller = JController::getInstance('Hierarchical');
$controller->execute(JFactory::getApplication()->input->get('task'));
$controller->redirect();
How can i use those functions into another php file outside the joomla script?
In your external php script just load Joomla frame work,
then you can use all the Joomla functions and Objects in your external php file.
define( '_JEXEC', 1 );
define('JPATH_BASE', dirname(__FILE__) );//this is when we are in the root
define( 'DS', DIRECTORY_SEPARATOR );
require_once ( JPATH_BASE .DS.'includes'.DS.'defines.php' );
require_once ( JPATH_BASE .DS.'includes'.DS.'framework.php' );
$mainframe =& JFactory::getApplication('site');
$mainframe->initialise();
Hope its helps..
Related
I have a php database class for managing all my database queries:
class DatabaseConnection()
{
private $link;
public $filter;
public function log_db_errors( $error, $query )
{
if( MY_DEBUG )
{
echo $message;
}
}
public function __construct()
{
global $connection;
mb_internal_encoding( 'UTF-8' );
mb_regex_encoding( 'UTF-8' );
$this->link = new mysqli( MY_HOST, MY_USER, MY_PASS, MY_DB );
$this->link->set_charset( "utf8" );
if( $this->link->connect_errno )
{
$this->log_db_errors( "Connect failed", $this->link->connect_error );
echo 'Server error. Please try again sometime. DB';
exit();
}
}
public function __destruct()
{
$this->disconnect();
}
public function filter( $data )
{
if( !is_array( $data ) )
{
$data = trim( htmlentities( $data ) );
$data = $this->link->real_escape_string( $data );
}
else
{
$data = array_map( array( 'DB', 'filter' ), $data );
}
return $data;
}
public function query( $query )
{
$full_query = $this->link->query( $query );
if( $this->link->error )
{
$this->log_db_errors( $this->link->error, $query );
$full_query->free();
return false;
}
else
{
$full_query->free();
return true;
}
}
public function my_table_exists_create( $table, $variables = array() ) {
$check = $this->link->query("SELECT * FROM '$table' LIMIT 1");
if( $check ) return true;
else {
if( empty( $variables ) ) {
return false;
exit;
}
$sql = "CREATE TABLE IF NOT EXISTS ". $table;
$fields = array();
$values = array();
foreach( $variables as $field ) {
$fields[] = $field; //$values[] = "'".$value."'";
}
$fields = ' (' . implode(', ', $fields) . ')';
$sql .= $fields;
$query = $this->link->query( $sql );
if( $this->link->error ) {
$this->log_db_errors( $this->link->error, $sql );
return false;
}
else return true;
}
}
public function my_num_rows( $query )
{
$num_rows = $this->link->query( $query );
if( $this->link->error )
{
$this->log_db_errors( $this->link->error, $query );
return $this->link->error;
}
else
{
return $num_rows->num_rows;
}
}
public function exists( $table = '', $check_val = '', $params = array() )
{
if( empty($table) || empty($check_val) || empty($params) )
{
return false;
exit;
}
$check = array();
foreach( $params as $field => $value )
{
if( !empty( $field ) && !empty( $value ) )
{
if( $this->db_common( $value ) )
{
$check[] = "$field = $value";
}
else
{
$check[] = "$field = '$value'";
}
}
}
$check = implode(' AND ', $check);
$rs_check = "SELECT $check_val FROM ".$table." WHERE $check";
$number = $this->my_num_rows( $rs_check );
if( $number === 0 )
{
return false;
}
else
{
return true;
}
exit;
}
public function disconnect()
{
$this->link->close();
}
}
I use this class to manage all my queries, like insert to the database :
$database = new DatabaseConnection();
$Item_Details = array(
'item_title' => trim($_POST['title']),
'item_content' => trim($_POST['content']),
'item_updated' => date('Y-m-d H:i:s'),
'item_updatedby' => $my_loginid,
);
$where_clause = array('itemid' => $itemid);
$updated = $database->as_update( 'my_item', $Item_Details , $where_clause, 1 );
Now I need to know I can use this class without having a lot of connections that can slow down connection to the server which leads to timeout and having too many connection. I thought I could use a global variable
function my_constant_initialize()
{
global $databasecon;
$databasecon = new DatabaseConnection();
return $databasecon;
}
So please advice how to avoid too many connections. Also as well as tell whether it is necessary to instanciate the database class for every query or I can just call it once because I have used a lot of Include and require functions in my php code.
Reaching the MySQL database connection limit is hard in OOP PHP because it destructs the connection object if the script is finished. Just to be safe, have a destruct function in your class and unset the object at the end of the script. If you are really worried about reaching the connection cap you can go into MySQL and modify the max_connection_limit from I think 1000 to higher and increase the buffer pool.
Additionally you might look into switching languages to like Java which has a technique called "connection pooling." Works better than PHP's version. No this is not the same as p_connect or whatever it is in PHP.
At least you don't have to initiate the connection every time you are calling your class.
To see how you could use your database class without having to instantiate it every time, we would need to see some more of your code. The already mentioned singleton pattern is the way to go, but it is hard to judge if it would really improve your code without knowing how you are actually programming.
This shows an implementation of your class as singleton:
class DatabaseConnection {
protected static $instance = null;
private $link;
public $filter;
public static function getInstance() {
if (self::$instance === null) {
self::$instance = new self;
}
return self::$instance;
}
protected function __construct() {
global $connection;
mb_internal_encoding( 'UTF-8' );
mb_regex_encoding( 'UTF-8' );
$this->link = new mysqli( MY_HOST, MY_USER, MY_PASS, MY_DB );
$this->link->set_charset( "utf8" );
if( $this->link->connect_errno )
{
$this->log_db_errors( "Connect failed", $this->link->connect_error );
echo 'Server error. Please try again sometime. DB';
exit();
}
}
protected function __clone() {
}
// add your other methods
}
You can call the connection by using
$databasecon = DatabaseConnection::getInstance();
By implementing it this way, when you call getInstance it checks if the connection has already been initialised so you can reuse it.
You set the __construct() as protected so the class can not be called without using the getInstance() method, same for __clone().
Sorry for my bad english, but I really need to know why this plugin does not work at all.
So i have Joomla 3.5.1 + JoomShopping 4.14.1
I want to connect the attributes filter plugin. But it does not work.
Help me please!!!
<?php
// No direct access.
defined('_JEXEC') or die;
class plgJShoppingOxboxAttribsFilter extends JPlugin
{
public function __construct(&$subject, $config)
{
parent::__construct($subject, $config);
}
public function onBeforeQueryCountProductList($controller, &$adv_result, &$adv_from, &$adv_query, &$order_query, &$filters = array())
{
$this->onBeforeQueryGetProductList($controller, &$adv_result, &$adv_from, &$adv_query, &$order_query, &$filters);
}
public function onBeforeQueryGetProductList($controller, &$adv_result, &$adv_from, &$adv_query, &$order_query, &$filters = array())
{
// Ïîëó÷àåì îáúåêò áàçû äàííûõ
$db = JFactory::getDBO();
//
$query = $db->getQuery(true);
//
$query->select('params');
//
$query->from('#__modules');
//
$query->where('module = "mod_oxbox_jshopping_attribute_filter"');
//
$query->where('published = 1');
//
$db->setQuery($query);
//
$list = $db->loadObjectList();
//
if (is_array($list) && count($list))
{
//
foreach ($list as $item)
{
//
$registry = new JRegistry();
//
$registry->loadString($item->params);
//
$item->params = $registry->toArray();
// Ïîëó÷àåì çíà÷åíèå
$vals = JRequest::getVar($item->params->get('param_name'), '');
//
$vals = urldecode($vals);
// Åñëè çíà÷åíèå íå ïóñòîå
if (!empty($vals))
{
// Åñëè ñîäåðæèò òî÷êó ñ çàïÿòîé
if (JString::strpos($vals, ';'))
{
// Ïðåîáðàçóåì â ìàññèâ
$vals = explode(';', $vals);
}
// Åñëè â ìàññèâå òîëüêî îäèí ýëåìåíò
if (is_array($vals) && count($vals) == 1)
{
//
$vals = $vals[1];
}
//
$attr_id = $item->params->get('attr_id');
//
$db->setQuery('SELECT independent FROM #__jshopping_attr WHERE attr_id = '.$attr_id);
// Ïîëó÷àåì ðåçóëüòàò
$independent = $db->loadResult();
// Åñëè àòðèáóò íåçàâèñèìûé
if ($independent)
{
$table = '#__jshopping_products_attr2';
$attr_value_id_field = 'attr_value_id';
}
else
{
$table = '#__jshopping_products_attr';
$attr_value_id_field = 'attr_'.$attr_id;
}
// Åñëè ôèëüòðóåì ïî çíà÷åíèÿì àòðèáóòîâ
if ($item->params->get('param_type', 'value') == 'value')
{
// Åñëè ýòî ìàññèâ
if (is_array($vals))
{
$adv_query .= 'AND prod.product_id IN (SELECT product_id FROM `'.$table.'` AS attr LEFT JOIN #__jshopping_attr_values AS attr_values ON attr_values.value_id = attr.'.$attr_value_id_field.' WHERE `name_ru-RU` in ('.implode(',', $vals).'))';
}
else
{
$adv_query .= 'AND prod.product_id IN (SELECT product_id FROM `'.$table.'` AS attr LEFT JOIN #__jshopping_attr_values AS attr_values ON attr_values.value_id = attr.'.$attr_value_id_field.' WHERE `name_ru-RU`="'.$vals.'")';
}
}
else // èíà÷å ôèëüòðóåì ïî èäåíòèôèêàòîðàì çíà÷åíèé àòðèáóòîâ
{
// Åñëè ýòî ìàññèâ
if (is_array($vals))
{
$adv_query .= ' AND prod.product_id IN (SELECT product_id FROM `'.$table.'` AS attr WHERE attr.'.$attr_value_id_field.' in ('.implode(',', $vals).'))';
}
else
{
$adv_query .= ' AND prod.product_id IN (SELECT attr.product_id FROM `'.$table.'` AS attr WHERE attr.'.$attr_value_id_field.' = '.$vals.')';
}
}
}
}
}
}
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have created a registration form and it works my only issues is I want to be able to hide the post info in the url if you click submit and the validation fails it does this
register.php?action=signup
is there a mod rewrite for this?
so that the url remains
register.php
removing the ?action=signup
I have searched every where but have came up with nothing
php code for register page
<?php
//Error reporting #1-8F636958
error_reporting(E_ALL | E_STRICT);
//End Error reporting
//Include Common Files #1-EDC1CE42
define("RelativePath", ".");
define("PathToCurrentPage", "/");
define("FileName", "NewPage1.php");
include_once(RelativePath . "/Common.php");
include_once(RelativePath . "/Template.php");
include_once(RelativePath . "/Sorter.php");
include_once(RelativePath . "/Navigator.php");
//End Include Common Files
class clsRecordusers { //users Class #2-9BE1AF6F
//Variables #2-9E315808
// Public variables
public $ComponentType = "Record";
public $ComponentName;
public $Parent;
public $HTMLFormAction;
public $PressedButton;
public $Errors;
public $ErrorBlock;
public $FormSubmitted;
public $FormEnctype;
public $Visible;
public $IsEmpty;
public $CCSEvents = "";
public $CCSEventResult;
public $RelativePath = "";
public $InsertAllowed = false;
public $UpdateAllowed = false;
public $DeleteAllowed = false;
public $ReadAllowed = false;
public $EditMode = false;
public $ds;
public $DataSource;
public $ValidatingControls;
public $Controls;
public $Attributes;
// Class variables
//End Variables
//Class_Initialize Event #2-627C035C
function clsRecordusers($RelativePath, & $Parent)
{
global $FileName;
global $CCSLocales;
global $DefaultDateFormat;
$this->Visible = true;
$this->Parent = & $Parent;
$this->RelativePath = $RelativePath;
$this->Errors = new clsErrors();
$this->ErrorBlock = "Record users/Error";
$this->DataSource = new clsusersDataSource($this);
$this->ds = & $this->DataSource;
$this->InsertAllowed = true;
if($this->Visible)
{
$this->ComponentName = "users";
$this->Attributes = new clsAttributes($this->ComponentName . ":");
$CCSForm = explode(":", CCGetFromGet("ccsForm", ""), 2);
if(sizeof($CCSForm) == 1)
$CCSForm[1] = "";
list($FormName, $FormMethod) = $CCSForm;
$this->EditMode = ($FormMethod == "Edit");
$this->FormEnctype = "application/x-www-form-urlencoded";
$this->FormSubmitted = ($FormName == $this->ComponentName);
$Method = $this->FormSubmitted ? ccsPost : ccsGet;
$this->btn_register = new clsButton("btn_register", $Method, $this);
$this->username = new clsControl(ccsTextBox, "username", "Soldier", ccsText, "", CCGetRequestParam("username", $Method, NULL), $this);
$this->username->Required = true;
$this->user_email = new clsControl(ccsTextBox, "user_email", "User Email", ccsText, "", CCGetRequestParam("user_email", $Method, NULL), $this);
$this->user_email->Required = true;
$this->user_birthdate = new clsControl(ccsTextBox, "user_birthdate", "User Birthdate", ccsText, "", CCGetRequestParam("user_birthdate", $Method, NULL), $this);
$this->user_birthdate->Required = true;
}
}
//End Class_Initialize Event
//Initialize Method #2-052CBF13
function Initialize()
{
if(!$this->Visible)
return;
$this->DataSource->Parameters["urluid"] = CCGetFromGet("uid", NULL);
}
//End Initialize Method
//Validate Method #2-B7C6592D
function Validate()
{
global $CCSLocales;
$Validation = true;
$Where = "";
$Validation = ($this->username->Validate() && $Validation);
$Validation = ($this->user_email->Validate() && $Validation);
$Validation = ($this->user_birthdate->Validate() && $Validation);
$this->CCSEventResult = CCGetEvent($this->CCSEvents, "OnValidate", $this);
$Validation = $Validation && ($this->username->Errors->Count() == 0);
$Validation = $Validation && ($this->user_email->Errors->Count() == 0);
$Validation = $Validation && ($this->user_birthdate->Errors->Count() == 0);
return (($this->Errors->Count() == 0) && $Validation);
}
//End Validate Method
//CheckErrors Method #2-E8847328
function CheckErrors()
{
$errors = false;
$errors = ($errors || $this->username->Errors->Count());
$errors = ($errors || $this->user_email->Errors->Count());
$errors = ($errors || $this->user_birthdate->Errors->Count());
$errors = ($errors || $this->Errors->Count());
$errors = ($errors || $this->DataSource->Errors->Count());
return $errors;
}
//End CheckErrors Method
//Operation Method #2-6BA9892D
function Operation()
{
if(!$this->Visible)
return;
global $Redirect;
global $FileName;
$this->DataSource->Prepare();
if(!$this->FormSubmitted) {
$this->EditMode = $this->DataSource->AllParametersSet;
return;
}
if($this->FormSubmitted) {
$this->PressedButton = "btn_register";
if($this->btn_register->Pressed) {
$this->PressedButton = "btn_register";
}
}
$Redirect = $FileName . "?" . CCGetQueryString("QueryString", array("ccsForm"));
if($this->Validate()) {
if($this->PressedButton == "btn_register") {
if(!CCGetEvent($this->btn_register->CCSEvents, "OnClick", $this->btn_register) || !$this->InsertRow()) {
$Redirect = "";
}
}
} else {
$Redirect = "";
}
if ($Redirect)
$this->DataSource->close();
}
//End Operation Method
//InsertRow Method #2-C62BC29D
function InsertRow()
{
$this->CCSEventResult = CCGetEvent($this->CCSEvents, "BeforeInsert", $this);
if(!$this->InsertAllowed) return false;
$this->DataSource->username->SetValue($this->username->GetValue(true));
$this->DataSource->user_email->SetValue($this->user_email->GetValue(true));
$this->DataSource->user_birthdate->SetValue($this->user_birthdate->GetValue(true));
$this->DataSource->Insert();
$this->CCSEventResult = CCGetEvent($this->CCSEvents, "AfterInsert", $this);
return (!$this->CheckErrors());
}
//End InsertRow Method
//Show Method #2-AE9867B3
function Show()
{
global $CCSUseAmp;
$Tpl = CCGetTemplate($this);
global $FileName;
global $CCSLocales;
$Error = "";
if(!$this->Visible)
return;
$this->CCSEventResult = CCGetEvent($this->CCSEvents, "BeforeSelect", $this);
$RecordBlock = "Record " . $this->ComponentName;
$ParentPath = $Tpl->block_path;
$Tpl->block_path = $ParentPath . "/" . $RecordBlock;
$this->EditMode = $this->EditMode && $this->ReadAllowed;
if($this->EditMode) {
if($this->DataSource->Errors->Count()){
$this->Errors->AddErrors($this->DataSource->Errors);
$this->DataSource->Errors->clear();
}
$this->DataSource->Open();
if($this->DataSource->Errors->Count() == 0 && $this->DataSource->next_record()) {
$this->DataSource->SetValues();
if(!$this->FormSubmitted){
$this->username->SetValue($this->DataSource->username->GetValue());
$this->user_email->SetValue($this->DataSource->user_email->GetValue());
$this->user_birthdate->SetValue($this->DataSource->user_birthdate->GetValue());
}
} else {
$this->EditMode = false;
}
}
if($this->FormSubmitted || $this->CheckErrors()) {
$Error = "";
$Error = ComposeStrings($Error, $this->username->Errors->ToString());
$Error = ComposeStrings($Error, $this->user_email->Errors->ToString());
$Error = ComposeStrings($Error, $this->user_birthdate->Errors->ToString());
$Error = ComposeStrings($Error, $this->Errors->ToString());
$Error = ComposeStrings($Error, $this->DataSource->Errors->ToString());
$Tpl->SetVar("Error", $Error);
$Tpl->Parse("Error", false);
}
$CCSForm = $this->EditMode ? $this->ComponentName . ":" . "Edit" : $this->ComponentName;
$this->HTMLFormAction = $FileName . "?" . CCAddParam(CCGetQueryString("QueryString", ""), "ccsForm", $CCSForm);
$Tpl->SetVar("Action", !$CCSUseAmp ? $this->HTMLFormAction : str_replace("&", "&", $this->HTMLFormAction));
$Tpl->SetVar("HTMLFormName", $this->ComponentName);
$Tpl->SetVar("HTMLFormEnctype", $this->FormEnctype);
$this->btn_register->Visible = !$this->EditMode && $this->InsertAllowed;
$this->CCSEventResult = CCGetEvent($this->CCSEvents, "BeforeShow", $this);
$this->Attributes->Show();
if(!$this->Visible) {
$Tpl->block_path = $ParentPath;
return;
}
$this->btn_register->Show();
$this->username->Show();
$this->user_email->Show();
$this->user_birthdate->Show();
$Tpl->parse();
$Tpl->block_path = $ParentPath;
$this->DataSource->close();
}
//End Show Method
} //End users Class #2-FCB6E20C
class clsusersDataSource extends clsDBlocalhost { //usersDataSource Class #2-5EDEDCFF
//DataSource Variables #2-8A9D7D42
public $Parent = "";
public $CCSEvents = "";
public $CCSEventResult;
public $ErrorBlock;
public $CmdExecution;
public $InsertParameters;
public $wp;
public $AllParametersSet;
public $InsertFields = array();
// Datasource fields
public $username;
public $user_email;
public $user_birthdate;
//End DataSource Variables
//DataSourceClass_Initialize Event #2-56B8B1F7
function clsusersDataSource(& $Parent)
{
$this->Parent = & $Parent;
$this->ErrorBlock = "Record users/Error";
$this->Initialize();
$this->username = new clsField("username", ccsText, "");
$this->user_email = new clsField("user_email", ccsText, "");
$this->user_birthdate = new clsField("user_birthdate", ccsText, "");
$this->InsertFields["soldier"] = array("Name" => "soldier", "Value" => "", "DataType" => ccsText, "OmitIfEmpty" => 1);
$this->InsertFields["user_email"] = array("Name" => "user_email", "Value" => "", "DataType" => ccsText, "OmitIfEmpty" => 1);
$this->InsertFields["user_birthdate"] = array("Name" => "user_birthdate", "Value" => "", "DataType" => ccsText, "OmitIfEmpty" => 1);
}
//End DataSourceClass_Initialize Event
//Prepare Method #2-DC2F5FB8
function Prepare()
{
global $CCSLocales;
global $DefaultDateFormat;
$this->wp = new clsSQLParameters($this->ErrorBlock);
$this->wp->AddParameter("1", "urluid", ccsInteger, "", "", $this->Parameters["urluid"], "", false);
$this->AllParametersSet = $this->wp->AllParamsSet();
$this->wp->Criterion[1] = $this->wp->Operation(opEqual, "uid", $this->wp->GetDBValue("1"), $this->ToSQL($this->wp->GetDBValue("1"), ccsInteger),false);
$this->Where =
$this->wp->Criterion[1];
}
//End Prepare Method
//Open Method #2-B071412E
function Open()
{
$this->CCSEventResult = CCGetEvent($this->CCSEvents, "BeforeBuildSelect", $this->Parent);
$this->SQL = "SELECT * \n\n" .
"FROM users {SQL_Where} {SQL_OrderBy}";
$this->CCSEventResult = CCGetEvent($this->CCSEvents, "BeforeExecuteSelect", $this->Parent);
$this->query(CCBuildSQL($this->SQL, $this->Where, $this->Order));
$this->CCSEventResult = CCGetEvent($this->CCSEvents, "AfterExecuteSelect", $this->Parent);
}
//End Open Method
//SetValues Method #2-1C83BB75
function SetValues()
{
$this->username->SetDBValue($this->f("soldier"));
$this->user_email->SetDBValue($this->f("user_email"));
$this->user_birthdate->SetDBValue($this->f("user_birthdate"));
}
//End SetValues Method
//Insert Method #2-D2F97CD9
function Insert()
{
global $CCSLocales;
global $DefaultDateFormat;
$this->CmdExecution = true;
$this->CCSEventResult = CCGetEvent($this->CCSEvents, "BeforeBuildInsert", $this->Parent);
$this->InsertFields["soldier"]["Value"] = $this->username->GetDBValue(true);
$this->InsertFields["user_email"]["Value"] = $this->user_email->GetDBValue(true);
$this->InsertFields["user_birthdate"]["Value"] = $this->user_birthdate->GetDBValue(true);
$this->SQL = CCBuildInsert("users", $this->InsertFields, $this);
$this->CCSEventResult = CCGetEvent($this->CCSEvents, "BeforeExecuteInsert", $this->Parent);
if($this->Errors->Count() == 0 && $this->CmdExecution) {
$this->query($this->SQL);
$this->CCSEventResult = CCGetEvent($this->CCSEvents, "AfterExecuteInsert", $this->Parent);
}
}
//End Insert Method
} //End usersDataSource Class #2-FCB6E20C
//Initialize Page #1-2A4101A9
// Variables
$FileName = "";
$Redirect = "";
$Tpl = "";
$TemplateFileName = "";
$BlockToParse = "";
$ComponentName = "";
$Attributes = "";
// Events;
$CCSEvents = "";
$CCSEventResult = "";
$TemplateSource = "";
$FileName = FileName;
$Redirect = "";
$TemplateFileName = "NewPage1.html";
$BlockToParse = "main";
$TemplateEncoding = "UTF-8";
$ContentType = "text/html";
$PathToRoot = "./";
$PathToRootOpt = "";
$Scripts = "|";
$Charset = $Charset ? $Charset : "utf-8";
//End Initialize Page
//Before Initialize #1-E870CEBC
$CCSEventResult = CCGetEvent($CCSEvents, "BeforeInitialize", $MainPage);
//End Before Initialize
//Initialize Objects #1-1F103AC9
$DBlocalhost = new clsDBlocalhost();
$MainPage->Connections["localhost"] = & $DBlocalhost;
$Attributes = new clsAttributes("page:");
$Attributes->SetValue("pathToRoot", $PathToRoot);
$MainPage->Attributes = & $Attributes;
// Controls
$users = new clsRecordusers("", $MainPage);
$MainPage->users = & $users;
$users->Initialize();
$ScriptIncludes = "";
$SList = explode("|", $Scripts);
foreach ($SList as $Script) {
if ($Script != "") $ScriptIncludes = $ScriptIncludes . "<script src=\"" . $PathToRoot . $Script . "\" type=\"text/javascript\"></script>\n";
}
$Attributes->SetValue("scriptIncludes", $ScriptIncludes);
$CCSEventResult = CCGetEvent($CCSEvents, "AfterInitialize", $MainPage);
if ($Charset) {
header("Content-Type: " . $ContentType . "; charset=" . $Charset);
} else {
header("Content-Type: " . $ContentType);
}
//End Initialize Objects
//Initialize HTML Template #1-28F2FDD6
$CCSEventResult = CCGetEvent($CCSEvents, "OnInitializeView", $MainPage);
$Tpl = new clsTemplate($FileEncoding, $TemplateEncoding);
if (strlen($TemplateSource)) {
$Tpl->LoadTemplateFromStr($TemplateSource, $BlockToParse, "UTF-8");
} else {
$Tpl->LoadTemplate(PathToCurrentPage . $TemplateFileName, $BlockToParse, "UTF-8");
}
$Tpl->SetVar("CCS_PathToRoot", $PathToRoot);
$Tpl->block_path = "/$BlockToParse";
$CCSEventResult = CCGetEvent($CCSEvents, "BeforeShow", $MainPage);
$Attributes->SetValue("pathToRoot", "");
$Attributes->Show();
//End Initialize HTML Template
//Execute Components #1-0C9864E9
$users->Operation();
//End Execute Components
//Go to destination page #1-810C207B
if($Redirect)
{
$CCSEventResult = CCGetEvent($CCSEvents, "BeforeUnload", $MainPage);
$DBlocalhost->close();
header("Location: " . $Redirect);
unset($users);
unset($Tpl);
exit;
}
//End Go to destination page
//Show Page #1-E3A8594F
$users->Show();
$Tpl->block_path = "";
$Tpl->Parse($BlockToParse, false);
if (!isset($main_block)) $main_block = $Tpl->GetVar($BlockToParse);
$main_block = CCConvertEncoding($main_block, $FileEncoding, $TemplateEncoding);
$CCSEventResult = CCGetEvent($CCSEvents, "BeforeOutput", $MainPage);
if ($CCSEventResult) echo $main_block;
//End Show Page
//Unload Page #1-4215F8E1
$CCSEventResult = CCGetEvent ($CCSEvents, "BeforeUnload", $MainPage);
$DBlocalhost->close();
unset($users);
unset($Tpl);
//End Unload Page
?>
You can submit the information via POST. The way you are submitting the data across is from a GET HTTP request. The best thing to do is submit it over via post data. I am assuming your frontend call is using ajax for the form submission? if not and using a simple form change method to POST. If it is using ajax, I would need to know if you are using something like jquery or crafting the XHR request yourself, but if you are doing it that way I would assume you would know the difference.
<form action="action_page.php" method="POST">
Here is the scenario, and let me start off saying any help would be a god-send, I have cloned the Article Category module inside Joomla! Basically changed all the articles_category to breed_articles (for my purpose). This worked fine, where I am stuck at is where in the module code can I define a specific category to pull articles from.
I know I can do this in the backend but I am working on a dynamic way to pull articles by categories and need to define the category in the module code. That being said, I will also need to pull the categoies by the slug not id.
Where I have been looking is the helper.php file in the module and I believe that I am on the right path there. I have tried replacing a few things and tracing the code but I am not very familiar with Joomla!
helper.php
$com_path = JPATH_SITE.'/components/com_content/';
require_once $com_path.'router.php';
require_once $com_path.'helpers/route.php';
JModelLegacy::addIncludePath($com_path . '/models', 'ContentModel');
abstract class modBreedArticlesHelper
{
public static function getList(&$params)
{
// Get an instance of the generic articles model
$articles = JModelLegacy::getInstance('Articles', 'ContentModel', array('ignore_request' => true));
// Set application parameters in model
$app = JFactory::getApplication();
$appParams = $app->getParams();
$articles->setState('params', $appParams);
// Set the filters based on the module params
$articles->setState('list.start', 0);
$articles->setState('list.limit', (int) $params->get('count', 0));
$articles->setState('filter.published', 1);
// Access filter
$access = !JComponentHelper::getParams('com_content')->get('show_noauth');
$authorised = JAccess::getAuthorisedViewLevels(JFactory::getUser()->get('id'));
$articles->setState('filter.access', $access);
// Prep for Normal or Dynamic Modes
$mode = $params->get('mode', 'normal');
switch ($mode)
{
case 'dynamic':
$option = $app->input->get('option');
$view = $app->input->get('view');
if ($option === 'com_content') {
switch($view)
{
case 'category':
$catids = array($app->input->getInt('id'));
break;
case 'categories':
$catids = array($app->input->getInt('id'));
break;
case 'article':
if ($params->get('show_on_article_page', 1)) {
$article_id = $app->input->getInt('id');
$catid = $app->input->getInt('catid');
if (!$catid) {
// Get an instance of the generic article model
$article = JModelLegacy::getInstance('Article', 'ContentModel', array('ignore_request' => true));
$article->setState('params', $appParams);
$article->setState('filter.published', 1);
$article->setState('article.id', (int) $article_id);
$item = $article->getItem();
$catids = array($item->catid);
}
else {
$catids = array($catid);
}
}
else {
// Return right away if show_on_article_page option is off
return;
}
break;
case 'featured':
default:
// Return right away if not on the category or article views
return;
}
}
else {
// Return right away if not on a com_content page
return;
}
break;
case 'normal':
default:
$catids = $params->get('catid');
$articles->setState('filter.category_id.include', (bool) $params->get('category_filtering_type', 1));
break;
}
// Category filter
if ($catids) {
if ($params->get('show_child_category_articles', 0) && (int) $params->get('levels', 0) > 0) {
// Get an instance of the generic categories model
$categories = JModelLegacy::getInstance('Categories', 'ContentModel', array('ignore_request' => true));
$categories->setState('params', $appParams);
$levels = $params->get('levels', 1) ? $params->get('levels', 1) : 9999;
$categories->setState('filter.get_children', $levels);
$categories->setState('filter.published', 1);
$categories->setState('filter.access', $access);
$additional_catids = array();
foreach($catids as $catid)
{
$categories->setState('filter.parentId', $catid);
$recursive = true;
$items = $categories->getItems($recursive);
if ($items)
{
foreach($items as $category)
{
$condition = (($category->level - $categories->getParent()->level) <= $levels);
if ($condition) {
$additional_catids[] = $category->id;
}
}
}
}
$catids = array_unique(array_merge($catids, $additional_catids));
}
$articles->setState('filter.category_id', $catids);
}
// Ordering
$articles->setState('list.ordering', $params->get('article_ordering', 'a.ordering'));
$articles->setState('list.direction', $params->get('article_ordering_direction', 'ASC'));
// New Parameters
$articles->setState('filter.featured', $params->get('show_front', 'show'));
$articles->setState('filter.author_id', $params->get('created_by', ""));
$articles->setState('filter.author_id.include', $params->get('author_filtering_type', 1));
$articles->setState('filter.author_alias', $params->get('created_by_alias', ""));
$articles->setState('filter.author_alias.include', $params->get('author_alias_filtering_type', 1));
$excluded_articles = $params->get('excluded_articles', '');
if ($excluded_articles) {
$excluded_articles = explode("\r\n", $excluded_articles);
$articles->setState('filter.article_id', $excluded_articles);
$articles->setState('filter.article_id.include', false); // Exclude
}
$date_filtering = $params->get('date_filtering', 'off');
if ($date_filtering !== 'off') {
$articles->setState('filter.date_filtering', $date_filtering);
$articles->setState('filter.date_field', $params->get('date_field', 'a.created'));
$articles->setState('filter.start_date_range', $params->get('start_date_range', '1000-01-01 00:00:00'));
$articles->setState('filter.end_date_range', $params->get('end_date_range', '9999-12-31 23:59:59'));
$articles->setState('filter.relative_date', $params->get('relative_date', 30));
}
// Filter by language
$articles->setState('filter.language', $app->getLanguageFilter());
$items = $articles->getItems();
// Display options
$show_date = $params->get('show_date', 0);
$show_date_field = $params->get('show_date_field', 'created');
$show_date_format = $params->get('show_date_format', 'Y-m-d H:i:s');
$show_category = $params->get('show_category', 0);
$show_hits = $params->get('show_hits', 0);
$show_author = $params->get('show_author', 0);
$show_introtext = $params->get('show_introtext', 0);
$introtext_limit = $params->get('introtext_limit', 100);
// Find current Article ID if on an article page
$option = $app->input->get('option');
$view = $app->input->get('view');
if ($option === 'com_content' && $view === 'article') {
$active_article_id = $app->input->getInt('id');
}
else {
$active_article_id = 0;
}
// Prepare data for display using display options
foreach ($items as &$item)
{
$item->slug = $item->id.':'.$item->alias;
$item->catslug = $item->catid ? $item->catid .':'.$item->category_alias : $item->catid;
if ($access || in_array($item->access, $authorised))
{
// We know that user has the privilege to view the article
$item->link = JRoute::_(ContentHelperRoute::getArticleRoute($item->slug, $item->catslug));
}
else
{
$app = JFactory::getApplication();
$menu = $app->getMenu();
$menuitems = $menu->getItems('link', 'index.php?option=com_users&view=login');
if (isset($menuitems[0]))
{
$Itemid = $menuitems[0]->id;
}
elseif ($app->input->getInt('Itemid') > 0)
{
// Use Itemid from requesting page only if there is no existing menu
$Itemid = $app->input->getInt('Itemid');
}
$item->link = JRoute::_('index.php?option=com_users&view=login&Itemid='.$Itemid);
}
// Used for styling the active article
$item->active = $item->id == $active_article_id ? 'active' : '';
$item->displayDate = '';
if ($show_date) {
$item->displayDate = JHTML::_('date', $item->$show_date_field, $show_date_format);
}
if ($item->catid) {
$item->displayCategoryLink = JRoute::_(ContentHelperRoute::getCategoryRoute($item->catid));
$item->displayCategoryTitle = $show_category ? ''.$item->category_title.'' : '';
}
else {
$item->displayCategoryTitle = $show_category ? $item->category_title : '';
}
$item->displayHits = $show_hits ? $item->hits : '';
$item->displayAuthorName = $show_author ? $item->author : '';
if ($show_introtext) {
$item->introtext = JHtml::_('content.prepare', $item->introtext, '', 'mod_articles_category.content');
$item->introtext = self::_cleanIntrotext($item->introtext);
}
$item->displayIntrotext = $show_introtext ? self::truncate($item->introtext, $introtext_limit) : '';
$item->displayReadmore = $item->alternative_readmore;
}
return $items;
}
public static function _cleanIntrotext($introtext)
{
$introtext = str_replace('<p>', ' ', $introtext);
$introtext = str_replace('</p>', ' ', $introtext);
$introtext = strip_tags($introtext, '<a><em><strong>');
$introtext = trim($introtext);
return $introtext;
}
/**
* Method to truncate introtext
*
* The goal is to get the proper length plain text string with as much of
* the html intact as possible with all tags properly closed.
*
* #param string $html The content of the introtext to be truncated
* #param integer $maxLength The maximum number of charactes to render
*
* #return string The truncated string
*/
public static function truncate($html, $maxLength = 0)
{
$baseLength = strlen($html);
$diffLength = 0;
// First get the plain text string. This is the rendered text we want to end up with.
$ptString = JHtml::_('string.truncate', $html, $maxLength, $noSplit = true, $allowHtml = false);
for ($maxLength; $maxLength < $baseLength;)
{
// Now get the string if we allow html.
$htmlString = JHtml::_('string.truncate', $html, $maxLength, $noSplit = true, $allowHtml = true);
// Now get the plain text from the html string.
$htmlStringToPtString = JHtml::_('string.truncate', $htmlString, $maxLength, $noSplit = true, $allowHtml = false);
// If the new plain text string matches the original plain text string we are done.
if ($ptString == $htmlStringToPtString)
{
return $htmlString;
}
// Get the number of html tag characters in the first $maxlength characters
$diffLength = strlen($ptString) - strlen($htmlStringToPtString);
// Set new $maxlength that adjusts for the html tags
$maxLength += $diffLength;
if ($baseLength <= $maxLength || $diffLength <= 0)
{
return $htmlString;
}
}
return $html;
}
public static function groupBy($list, $fieldName, $article_grouping_direction, $fieldNameToKeep = null)
{
$grouped = array();
if (!is_array($list)) {
if ($list == '') {
return $grouped;
}
$list = array($list);
}
foreach($list as $key => $item)
{
if (!isset($grouped[$item->$fieldName])) {
$grouped[$item->$fieldName] = array();
}
if (is_null($fieldNameToKeep)) {
$grouped[$item->$fieldName][$key] = $item;
}
else {
$grouped[$item->$fieldName][$key] = $item->$fieldNameToKeep;
}
unset($list[$key]);
}
$article_grouping_direction($grouped);
return $grouped;
}
public static function groupByDate($list, $type = 'year', $article_grouping_direction, $month_year_format = 'F Y')
{
$grouped = array();
if (!is_array($list)) {
if ($list == '') {
return $grouped;
}
$list = array($list);
}
foreach($list as $key => $item)
{
switch($type)
{
case 'month_year':
$month_year = JString::substr($item->created, 0, 7);
if (!isset($grouped[$month_year])) {
$grouped[$month_year] = array();
}
$grouped[$month_year][$key] = $item;
break;
case 'year':
default:
$year = JString::substr($item->created, 0, 4);
if (!isset($grouped[$year])) {
$grouped[$year] = array();
}
$grouped[$year][$key] = $item;
break;
}
unset($list[$key]);
}
$article_grouping_direction($grouped);
if ($type === 'month_year') {
foreach($grouped as $group => $items)
{
$date = new JDate($group);
$formatted_group = $date->format($month_year_format);
$grouped[$formatted_group] = $items;
unset($grouped[$group]);
}
}
return $grouped;
}
}
It looks like my issue was really specific to the project I am working on. If anyone happens to find this or wants to accomplish something similar, read on.
Decided to accomplish what I was doing using a JDatabase query. To retrieve the articles using the category alias, I queried the DB to match the alias I was giving the query to the category ID. Then joined the content table to get the article information.
All the information you need to make a proper JDatabase query can be found here: http://docs.joomla.org/Accessing_the_database_using_JDatabase
This question already has answers here:
Call to a member function on a non-object [duplicate]
(8 answers)
Closed 10 years ago.
The class below is my first attempt at writing my own OOP application. I've used procedural for a while and the OO techniques are not coming as easily as I'd hoped.
The class is designed to put together input elements for HTML forms, optionally using SQL table records. I'm starting with the select box and will add more when I get this much working.
So the problem is that I'm getting
"Call to a member function get_table() on a non-object" on the 'public function get_table()' line of the Class code below.
I'm not sure why this is happening. Help/tips would be GREATLY appreciated.
and now the code:
Application:
$_input = new html_form_input();
$_input->set_input_type('select');
$_input->set_table('stores');
$_input->set_fieldname_id('store_id');
$_input->set_fieldname_desc('store_name');
$_input->set_sql_order(' ORDER BY store_name ASC ');
$_input->set_select();
$html_select_facility = $_input->get_select();
Class:
class html_form_input
{
public $input_type;
public $table;
public $fieldname_id;
public $fieldname_desc;
public $passed_id;
public $sql_where;
public $sql_order;
public $array_input_options;
public function __construct()
{
// constructor method
}
/*
setters
*/
public function set_input_type($input_type)
{
$this->input_type = $input_type;
}
public function set_array_input_options($array_input_options)
{
$this->array_input_options = $array_input_options;
}
public function set_table($table)
{
$this->table = $table;
}
public function set_fieldname_id($fieldname_id)
{
$this->fieldname_id = $fieldname_id;
}
public function set_fieldname_desc($fieldname_desc)
{
$this->fieldname_desc = $fieldname_desc;
}
public function set_passed_id($passed_id)
{
$this->passed_id = $passed_id;
}
public function set_sql_where($sql_where)
{
$this->sql_where = $sql_where;
}
public function set_sql_order($sql_order)
{
$this->sql_order = $sql_order;
}
/*
getters
*/
public function get_input_type()
{
return $this->$input_type;
}
public function get_array_input_options()
{
return $this->$array_input_options;
}
public function get_table()
{
return $this->$table;
}
public function get_fieldname_id()
{
return $this->$fieldname_id;
}
public function get_fieldname_desc()
{
return $this->$fieldname_desc;
}
public function get_passed_id()
{
return $this->$passed_id;
}
public function get_sql_where()
{
return $this->$sql_where;
}
public function get_sql_order()
{
return $this->$sql_order;
}
/*
set_query_form_data() queries the database for records to be used in the input element.
*/
public function set_query_form_data()
{
global $dbx;
$debug = true;
$_debug_desc = "<span style='color:blue;'>function</span> <b>set_query_form_data</b>()";
if ($debug) { echo "<p>BEGIN $_debug_desc <blockquote>"; }
$table->get_table();
$fieldname_id->get_fieldname_id();
$fieldname_desc->get_fieldname_desc();
$passed_id->get_passed_id();
$sql_where->get_sql_where();
$sql_order->get_sql_order();
if ($passed_id)
{
if (!is_array($passed_id))
{
$passed_id[] = $passed_id;
}
}
if ($sql_where!='')
{
$sql_where = " WHERE $sql_where ";
}
$q = "
SELECT
$fieldname_id,
$fieldname_desc
FROM
$table
$sql_where
$sql_order
";
$res = $mdb2_dbx->query($q);
if (PEAR::isError($res)) { gor_error_handler($res, $q, __LINE__,__FILE__,'die'); }
while ( $r = $res->fetchRow(MDB2_FETCHMODE_ASSOC) )
{
$id = $r[$fieldname_id];
$desc = $r[$fieldname_desc];
$array_values[$id] = $desc;
}
$this->sql_array_values = $array_values;
if ($debug) { echo "<p></blockquote>END $_debug_desc "; }
}
/*
getter for set_query_form_data (above)
*/
public function get_query_form_data()
{
return $this->$array_values;
}
/*
set_select() pieces together a select input element using database derived records, or a passed array of values.
*/
public function set_select($flag_query_db=1, $array_static_values=null)
{
if ($flag_query_db==1)
{
$array_values = $this->set_query_form_data();
} else if (is_array($array_static_values)) {
$array_values = $array_static_values;
}
$array_values = $array_data['row_data'];
$fieldname_id = $array_data['fieldname_id'];
$fieldname_desc = $array_data['fieldname_desc'];
$passed_id = $array_data['passed_id'];
if (!is_array($passed_id))
{
$passed_id[] = $passed_id;
}
foreach ($array_values as $id=>$desc)
{
// handle passed values (multiple or single)
$sel = null;
if (in_array($id,$passed_id))
{
$sel = ' selected ';
}
// construct html
$html_options .= " <option value='$id' $sel>$desc</option>\n";
}
$disabled = null;
$multiple = null;
$size = null;
$style = null;
$class = null;
$element_id = null;
$javascript = null;
if (is_array($array_input_options))
{
$s_disabled = $array_input_options['disabled'];
$s_multiple = $array_input_options['multiple'];
$s_size = $array_input_options['size'];
$s_style = $array_input_options['style'];
$s_id = $array_input_options['id'];
$s_class = $array_input_options['class'];
$s_javascript = $array_input_options['javascript'];
if ($s_disabled!='') {$disabled = ' disabled '; }
if ($s_multiple!='') {$multiple = ' multiple '; }
if ($s_size!='') {$size = ' size="' . $s_size . '"'; }
if ($s_style!='') {$style = ' style = "' . $s_style . '"'; }
if ($s_id!='') {$element_id = ' id = "' . $s_id . '"'; }
if ($s_class!='') {$class = ' class = "' . $s_class . '"'; }
if ($s_javascript!='') {$javascript = $s_javascript; }
}
$html = "
<select name='$fieldname_id' $element_id $disabled $multiple $size $style $class $javascript>
$html_options
</select>
";
$this->select_html = $html;
}
/*
getter for set_select (above)
*/
public function get_select()
{
return $this->$select_html;
}
}
With your getters, instead of using $this->$var it should be $this->var, for example $this->table and not $this->$table.
In the following code, $table hasn't been initialised.
public function set_query_form_data()
{
global $dbx;
$debug = true;
$_debug_desc = "<span style='color:blue;'>function</span> <b>set_query_form_data</b>()";
if ($debug) { echo "<p>BEGIN $_debug_desc <blockquote>"; }
$table->get_table();
You probably intend it to be $this, i.e. "the object currently being used":
public function set_query_form_data()
{
global $dbx;
$debug = true;
$_debug_desc = "<span style='color:blue;'>function</span> <b>set_query_form_data</b>()";
if ($debug) { echo "<p>BEGIN $_debug_desc <blockquote>"; }
$this->get_table();
The problem is in your set_query_form_data method:
public function set_query_form_data() {
// $table is no object
$table->get_table();
// you should use this instead
$this->table
}
Note:
// Are you sure with this calls? Shouldn't it be $this->array_input_options ?
return $this->$array_input_options;
You're making use of variable functions/dereferencing, unintentionally. Example:
$foo = 'name';
echo $object->$foo; // same as echo $object->name
Object properties and methods do not need to be prefixed with $.
With the pointers from the other answers and some more RTM, I got the basic script working. In particular, I removed the "$" from property names and accessed the properties of $this instead of calling get_* methods.
Application:
$array_input_options = array(
'include_blank_option' => 1,
'disabled' => 0,
'multiple' => 0,
'size' => '',
'style' => '',
'id' => '',
'class' => '',
'javascript' => '',
);
$_input = new html_form_input();
$_input->set_input_type('select');
$_input->set_table('gor_facility');
$_input->set_fieldname_id('facilityid');
$_input->set_fieldname_desc('facilityname');
$_input->set_sql_where(' status = 1');
$_input->set_sql_order(' ORDER BY facilityname ASC ');
$_input->set_array_input_options($array_input_options);
// $_input->set_passed_id('');
$html_select_facility = $_input->create_select();
Class:
class html_form_input
{
public $input_type;
public $table;
public $fieldname_id;
public $fieldname_desc;
public $passed_id;
public $sql_where;
public $sql_order;
public $array_input_options;
public function __construct()
{
// constructor method
}
/*
setters
*/
public function set_input_type($input_type)
{
$this->input_type = $input_type;
}
public function set_array_input_options($array_input_options)
{
$this->array_input_options = $array_input_options;
}
public function set_table($table)
{
$this->table = $table;
}
public function set_fieldname_id($fieldname_id)
{
$this->fieldname_id = $fieldname_id;
}
public function set_fieldname_desc($fieldname_desc)
{
$this->fieldname_desc = $fieldname_desc;
}
public function set_passed_id($passed_id)
{
$this->passed_id = $passed_id;
}
public function set_sql_where($sql_where)
{
$this->sql_where = $sql_where;
}
public function set_sql_order($sql_order)
{
$this->sql_order = $sql_order;
}
/*
getters
*/
public function get_input_type()
{
return $this->input_type;
}
public function get_array_input_options()
{
return $this->array_input_options;
}
public function get_table()
{
return $this->table;
}
public function get_fieldname_id()
{
return $this->fieldname_id;
}
public function get_fieldname_desc()
{
return $this->fieldname_desc;
}
public function get_passed_id()
{
return $this->passed_id;
}
public function get_sql_where()
{
return $this->sql_where;
}
public function get_sql_order()
{
return $this->sql_order;
}
/*
set_query_form_data() queries the database for records to be used in the input element.
*/
public function set_query_form_data()
{
global $mdb2_dbx;
$debug = false;
$_debug_desc = "<span style='color:blue;'>function</span> <b>set_query_form_data</b>()";
if ($debug) { echo "<p>BEGIN $_debug_desc <blockquote>"; }
$table = $this->table;
$fieldname_id = $this->fieldname_id;
$fieldname_desc = $this->fieldname_desc;
$passed_id = $this->passed_id;
$sql_where = $this->sql_where;
$sql_order = $this->sql_order;
if ($passed_id)
{
if (!is_array($passed_id))
{
$passed_id[] = $passed_id;
}
}
if ($sql_where!='')
{
$sql_where = " WHERE $sql_where ";
}
$q = "
SELECT
$fieldname_id,
$fieldname_desc
FROM
$table
$sql_where
$sql_order
";
if ($debug) {echo "<p>$q<br>";}
$res = $mdb2_dbx->query($q);
if (PEAR::isError($res)) { gor_error_handler($res, $q, __LINE__,__FILE__,'die'); }
while ( $r = $res->fetchRow(MDB2_FETCHMODE_ASSOC) )
{
$id = $r[$fieldname_id];
$desc = $r[$fieldname_desc];
$array_values[$id] = $desc;
}
$this->sql_array_values = $array_values;
if ($debug) { echo "<p></blockquote>END $_debug_desc "; }
}
/*
getter for set_query_form_data (above)
*/
public function get_query_form_data()
{
return $this->sql_array_values;
}
/*
set_select() pieces together a select input element using database derived records, or a passed array of values.
*/
public function construct_select($flag_query_db=1, $array_static_values=null)
{
if ($flag_query_db==1)
{
$this->set_query_form_data();
$row_data = $this->sql_array_values;
} else if (is_array($array_static_values)) {
$row_data = $array_static_values;
}
$fieldname_id = $this->fieldname_id;
$fieldname_desc = $this->fieldname_desc;
$passed_id = $this->passed_id;
$array_input_options = $this->array_input_options;
if (!is_array($passed_id))
{
$passed_id[] = $passed_id;
}
$disabled = null;
$multiple = null;
$size = null;
$style = null;
$class = null;
$element_id = null;
$javascript = null;
$html_option_blank = null;
if (is_array($array_input_options))
{
$s_disabled = $array_input_options['disabled'];
$s_multiple = $array_input_options['multiple'];
$s_size = $array_input_options['size'];
$s_style = $array_input_options['style'];
$s_id = $array_input_options['id'];
$s_class = $array_input_options['class'];
$s_javascript = $array_input_options['javascript'];
$s_blank = $array_input_options['include_blank_option'];
if ($s_disabled!='') {$disabled = ' disabled '; }
if ($s_multiple!='') {$multiple = ' multiple '; }
if ($s_size!='') {$size = ' size="' . $s_size . '"'; }
if ($s_style!='') {$style = ' style = "' . $s_style . '"'; }
if ($s_id!='') {$element_id = ' id = "' . $s_id . '"'; }
if ($s_class!='') {$class = ' class = "' . $s_class . '"'; }
if ($s_javascript!='') {$javascript = $s_javascript; }
if ($s_blank==1) { $row_data = array(''=>'Select an option below:') + $row_data; }
}
if (is_array($row_data))
{
foreach ($row_data as $id=>$desc)
{
// handle passed values (multiple or single)
$sel = null;
if (in_array($id,$passed_id))
{
$sel = ' selected ';
}
// construct html
$html_options .= " <option value='$id' $sel>$desc</option>\n";
}
}
$html = "
<select name='$fieldname_id' $element_id $disabled $multiple $size $style $class $javascript>
$html_option_blank
$html_options
</select>
";
$this->select_html = $html;
}
/*
getter for set_select (above)
*/
public function create_select()
{
$this->construct_select();
return $this->select_html;
}
}