Here's a list of Joomla code snippets so that I don't have to search the forums every time I need one!
General php
Included files
print 'Debug Line '.__LINE__.' $included <pre>'; print_r (get_included_files()); print "</pre> \n";
.......................................................
Paypal IPN History link
Link-> IPN History Link-> IPN Edit Link-> Seller preferences
Joomla 1.5
excellent post-> converting-old-extensions-to-joomla-15
Joomla 2.5
Find if on home page
$app = JFactory::getApplication(); $menu = $app->getMenu(); if ($menu->getActive() == $menu->getDefault()) { echo 'This is the front page'; }
or
$app = JFactory::getApplication(); $menu = $app->getMenu(); if ($menu->getActive() == $menu->getDefault( 'en-GB' )) { echo 'This is the front page'; } elseif ($menu->getActive() == $menu->getDefault( 'fr-FR' )) { echo 'Accueil'; } .......................................................
Find current page title
$mydoc =& JFactory::getDocument(); $title = $mydoc->getTitle(); .......................................................
Std DB call
// Get a db connection.
$db = JFactory::getDbo();
// Create a new query object.
$query = $db->getQuery(true);
// Select all records from the user profile table where key begins with "custom.".
// Order it by the ordering field.
$query->select($db->quoteName(array('user_id', 'profile_key', 'profile_value', 'ordering')));
$query->from($db->quoteName('#__user_profiles'));
$query->where($db->quoteName('profile_key') . ' LIKE '. $db->quote('\'custom.%\''));
$query->order($db->quoteName('order') . ' ASC');
// Reset the query using our newly populated query object.
$db->setQuery($query);
// Load the results as a list of stdClass objects (see later for more options on retrieving data).
$results = $db->loadObjectList();
AS query must be seperate
$query->select($db->quoteName('e.name', 'event'));// AS
JOIN
$query->join('LEFT', $db->quoteName('#__rseventspro_events', 'e') . ' ON (' . $db->quoteName('e.id') . ' = ' . $db->quoteName('u.id') . ')');
WHERE
$query->where($db->quoteName('SubmissionId') . ' = '.$db->quote($value->SubmissionId). ' AND ('.$db->quoteName('Fieldname') . ' = '.$db->quote('City'). ' OR '.$db->quoteName('Fieldname') . ' = '.$db->quote('State').')');
.......................................................
Find current menu text
$active = JFactory::getApplication()->getMenu()->getActive(); $title = $active->title; .......................................................
Find current menu link from Itemid
$menuitem is the Itemid
$item = JFactory::getApplication()->getMenu()->getItem( $menuitem ); $url = JRoute::_($item->link . '&Itemid=' . $item->id); .......................................................
Get a var
$success = JRequest::getVar('success'); .......................................................
Just show the component
&tmpl=component .......................................................
Show messages in component
$document = & JFactory::getDocument(); $renderer = $document->loadRenderer('message'); $msg=@$renderer->render(); .......................................................
Get the messages
$messages = JFactory::getApplication()->getMessageQueue(); //this is an array of queued messages - no html .......................................................
Clear joomla messages
$app = JFactory::getApplication(); $app->set( '_messageQueue', '' ); //clear messages .......................................................
Joomla session set
$session = JFactory::getSession(); $previousValue = $session->set('myValue', $value,'myNameSpace');
get
$session = JFactory::getSession(); $value = $session->get('myValue', myDefault,'myNameSpace'); .......................................................
Add module to component You can also pass prameters - form {"btuser":"83"}
$document = &JFactory::getDocument(); $renderer = $document->loadRenderer('modules'); $position = 'comuser'; $options = array('style' => 'raw','params' => '{"btuser":"'.$userid.'"}' ); echo $renderer->render($position, $options, null);
or
$modules =& JModuleHelper::getModules('position-4'); foreach ($modules as $module) { echo JModuleHelper::renderModule($module); } .......................................................
Add js & css
$document = JFactory::getDocument(); $document->addScript(Juri::base() .'components/com_musicbattle/assets/js/imageflow.js'); $document->addStyleSheet(Juri::base() .'components/com_musicbattle/assets/css/imageflow.css'); .......................................................
Get User etc
$user =& JFactory::getUser(); $userid = $user->get('id'); $groups = JAccess::getGroupsByUser($userid, false); if(in_array(7, $groups)){ echo 'only visible for admin'; }else{ echo 'only not an admin'; } .......................................................
Add a lang file
$lang = JFactory::getLanguage(); $extension = 'com_helloworld'; $base_dir = JPATH_SITE; $language_tag = 'en-GB'; $reload = true; $lang->load($extension, $base_dir, $language_tag, $reload); .......................................................
Joomla 3.0
Resources:
Constants: docs.joomla.org/Constants
Common upgrade problems
Controller errors
often the libraries/cms/controller & model folder is left behing from J2.5 - remove
Always remove all J1.7 etc com_admin sql files BEFORE beginning!
.......................................................
replace globals - J3
$mainframe ($app) $mainframe = JFactory::getApplication();
$database $database = JFactory::getDbo();
$option $option = JRequest::getCmd('option');
$limit $limit = $mainframe->getCfg('list_limit'); .......................................................
Add a redirect
$app = JFactory::getApplication(); $an_id = $app->input->get('id');
$url = JRoute::_('index.php?option=xxx&task=xxx&id=' . (int)$an_id, false); $app->redirect($url); .......................................................
Admin toolbar buttons do nothing - J3
replace JToolBarHelper::save(); with JToolbarHelper::save('event.save');
event is the subcontroller name .......................................................
authorisedLevels - J3
replace Juser::authorisedLevels() with JUser::getAuthorisedViewLevels()
.......................................................
JFactory::getXMLParser()
replace JFactory::getXMLParser($path) with JFactory::getXML($path)
and
$xmlparser->loadFile( $path ) with ( string)$xmlparser->version
.......................................................
$menu = &JSite::getMenu()
replace $menu = &JSite::getMenu() with $menu = JFactory::getApplication()->getMenu();
.......................................................
toMySQL() - J3
replace $date->toMySQL(); with $date->toSQL();
.......................................................
JHtml::core() - J3
replace JHtml::core(); with JHtml::_('behavior.framework');
.......................................................
JDate::toFormat() - J3
replace JDate::toFormat(); with JDate::format();
.......................................................
Call to undefined method Joomla\Registry\Registry::getValue() - J3
replace JRegistry::getValue() with JRegistry::get()
.......................................................
$params->loadJSON( $item->params )
replace $params->loadJSON( $item->params ) with $params->loadString($item->params, 'JSON')
.......................................................
Admin call subcontroller - J3
replace index.php?option=com_ccg&view=events&task=edit&cid[]='. $row->id; with 'index.php?option=com_ccg&task=events.edit&cid[]='. $row->id;
events is the subcontroller name .......................................................
JTable::getInstance('event','Jtable') returns nothing - J3
add JTable::addIncludePath(JPATH_COMPONENT_ADMINISTRATOR . '/tables'); .......................................................
Declaration of JxController::display() should be compatible with JControllerLegacy::display($cachable = false, $urlparams = Array) - J3
replace function display() with function display($cachable = false, $urlparams = false) .......................................................
Fatal error: Class 'JFolder' not found - J3
add jimport('joomla.filesystem.folder'); .......................................................
cannot extend from interface JController - J3
replace class JMainController extends JController with class JMainController extends JControllerLegacy .......................................................
admin com menu gives 404 (legacy J1.5->2.5 - J3
rename admin.com_mycom.php to com_mycom.php .......................................................
Call to undefined method Joomla\Registry\Registry::loadJSON() - J3
replace loadJSON with loadString .......................................................
Fatal error: Class 'JRegistry' - J3
old extension my not load the JRegistry class fix libraries - add // Get the framework. require_once JPATH_LIBRARIES . '/import.legacy.php'; // Bootstrap the CMS libraries. require_once JPATH_LIBRARIES . '/cms.php'; .......................................................
Use of undefined constant DS - J3
Use of undefined constant DS - add if(!defined('DS')) define('DS', DIRECTORY_SEPARATOR); or replace all 'DS' with / .......................................................
500 - Html: :jquery is not supported - J3
Replace JHtml::_('behavior.jquery'); with JHtml::_('jquery.framework'); .......................................................
500 - JHtmlBehavior::mootools not found or JHtml::core(); - J3
Replace JHtml::_('behavior.mootools'); with JHtml::_('behavior.framework'); .......................................................
500 - Class 'JParameter' not found - J3
Replace if(defined( '_JEXEC' )) return new JParameter($param, $path); with if(defined( '_JEXEC' )) return new JRegistry($param, $path); .......................................................
500 - Call to undefined method JModel::getInstance() or JModel::addIncludePath(); - J3
Replace JModel::addIncludePath; withJModelLegacy::addIncludePath; etc .......................................................
Joomla 3 snippets
Post about JDate .. some is J2.5! http://webamoeba.co.uk/blog/working-with-dates-in-joomla/ Post about fetching parameters: https://coderwall.com/p/iaouqw/getting-joomla-module-template-plugin-parameters
Load lang & css from plugin - J3
$language = JFactory::getLanguage();
$language->load('plg_vmcustom_stepbystep', JPATH_PLUGINS . DS . 'vmcustom' .DS . 'stepbystep');
$url= JURI::root(true).'/plugins/vmcustom/stepbystep/assets/css/stepbystep.css';
$document = JFactory::getDocument();
$document->addStyleSheet($url);
//$document->addScript($script);
.......................................................
Get plugin params anywhere - J3
$plugin = JPluginHelper::getPlugin('vmcustom', 'stepbystep');
if ($plugin){
$params_stepbystep = new JRegistry($plugin->params);
$sbsdebug = $params_stepbystep->get('sbsdebug', 0);
}
.......................................................
Bootstrap tooltips - J3
JHTML::_('bootstrap.tooltip');
<h5 class="hasTooltip" data-placement="right" title="This is the tooltip">
Stye with classes: .tooltip, .tooltip-inner, .tooltip-arrow Positional dependent: .tooltip.left .tooltip-arrow, .tooltip.top .tooltip-arrow etc .......................................................
Bootstrap modal - J3
JHTML::_("behavior.modal");
<a rel="size: {x: 900, y: 600}" onclick=" return false;" href="/component/content/17.html?tmpl=component" title="example popup" class="btn modal">Popup </a>
Stye with: media/system/css/modal.css .......................................................
ensure jquery is loaded first before your ext scripts - J3
just add before your script calls <?php JHtml::_('jquery.framework', true, true); ?> then $doc->addScript($pluginLivePath."/js/jquery.prettyPhoto.js"); .......................................................
call content plugin from template/ext - J3
<?php echo JHTML::_('content.prepare', '{gallery}tanz{/gallery}'); ?> .......................................................
Over-ride Chosen search box show threshold
To override it, change your chosen loading code to following:
JHtml::_('formbehavior.chosen', 'select', null, array('disable_search_threshold'=>1));
.......................................................
set html title from article
add the html title to the article metakey snippet in the com_content article default
$document= JFactory::getDocument(); if(!empty($this->item->metakey)){ $document->setTitle($this->item->metakey); } .......................................................
std DB SET query - J3
$user = JFactory::getUser();
$userid = $user->get('id');
$db = JFactory::getDbo();
$fields = array(
$db->quoteName('review') . '= '. $db->quote($review),
$db->quoteName('rating') . '= '. $db->quote($rating)
);
if($approve){
$fields[] = $db->quoteName('state') . '= 1';
}
$conditions = array (
$db->quoteName('id') . ' = '. $db->quote($id)
);
$query = $db->getQuery(true);
$query->update('#__virtuemart_ordersave');
$query->set($fields);
$query->where($conditions);
$db->setQuery($query);
try {
//stop reset******
$result = $db->query(); //stop reset*****
} catch (Exception $e) {
// Catch the error.
} .......................................................
std DB SELECT query - J3
$db = JFactory::getDbo();
$query = $db->getQuery(true);
// Select all records from the user profile table where key begins with "custom.".
// Order it by the ordering field.
$query->select($db->quoteName(array('user_id', 'profile_key', 'profile_value', 'ordering')));
$query->from($db->quoteName('#__user_profiles'));
$query->where($db->quoteName('profile_key') . ' LIKE '. $db->quote('\'custom.%\''));
$query->order($db->quoteName('order') . ' ASC');
// Reset the query using our newly populated query object.
$db->setQuery($query);
// Load the results as a list of stdClass objects
$results = $db->loadObjectList();
AS query must be seperate select - repeat as nesscesary
$query->select($db->quoteName('e.name', 'event'));// AS
JOIN
$query->join('LEFT', $db->quoteName('#__rseventspro_events', 'e') . ' ON (' . $db->quoteName('e.id') . ' = ' . $db->quoteName('u.id') . ')');
WHERE
$query->where($db->quoteName('SubmissionId') . ' = '.$db->quote($value->SubmissionId). ' AND ('.$db->quoteName('Fieldname') . ' = '.$db->quote('City'). ' OR '.$db->quoteName('Fieldname') . ' = '.$db->quote('State').')');
.......................................................
Increment Table field
$db = JFactory::getDbo(); $query = $db->getQuery(true); $query->clear() ->update('#__socialfactory_users') ->set('messages = (messages + 1)') ->where('user_id = '. $sfUser->user_id); $db->setQuery($query);
try { $db->execute(); } catch (JDatabaseExceptionExecuting $e) { JError::raiseError(500, $e->getMessage()); } .......................................................
Clean txt string
$field_id = preg_replace('/[^A-Za-z0-9\-]/', '', $field->name); .......................................................
Loading jquery
JHtml::_('jquery.framework');
For jQuery UI
JHtml::_('jquery.ui');
Loading BootStrap
JHtml::_('bootstrap.framework');
and for BootStrap css only
JHtml::_('bootstrap.loadCss');
JHtml::_('bootstrap.tooltip'); JHtml::_('behavior.multiselect'); JHtml::_('dropdown.init'); JHtml::_('formbehavior.chosen', 'select'); .......................................................
Loading mootools
To load just the MooTools Core library use:
JHtml::_('behavior.framework');
Or to load both the Core and More libraries:
JHtml::_('behavior.framework', true); .......................................................
Creating a php object
With PHP it is possible to use type casting to convert a simple array into a stdClass object.
$new_object = (object) [ 'test' => 'nelly', 'test2' => 'nelly2', 'test3' => 'nelly3', ]; .......................................................
Report db query error with query
Add the actual query to the error \libraries\joomla\database\driver\mysqli.php ~ line 648
$this->errorMsg = $this->errorMsg.' - '.$query; .......................................................
Call any plugin from public
public function onAfterInitialise() { $app = $this->app; $option = $app->input->get('option'); if ($option != "com_lscache") { return; }
if ($app->isAdmin()) { return; }
//can use other options }
called by https://xxx.com.index?option=com_lscache&.... .......................................................
Find what is calling Mootools tooltip
Add this debug to \libraries\cms\html\behavior.php ~ line 286
public static function tooltip($selector = '.hasTip', $params = array()) { print 'Debug Line '.__LINE__.' $this->guests <pre>'; print_r (debug_backtrace()); print "</pre><br />\n"; die(); .......................................................
Joomla 4.0
Add css from plugin or module not using asset manager
use Joomla\CMS\Factory;
use Joomla\CMS\HTML\HTMLHelper;
//load css
HTMLHelper::_('stylesheet', 'modules/mod_vm_hidesold/assets/css/default.css', ['version' => 'auto', 'relative' => true]);
.......................................................
Example Content Security Policy
content="default-src 'self';
frame-src youtube.com https://www.youtube.com;
font-src 'self' fonts.gstatic.com; style-src 'self' 'unsafe-inline' https://assets.mailerlite.com;
script-src 'self' 'unsafe-inline' https://*.googletagmanager.com
https://assets.mailerlite.com;
img-src 'self' https://* https://i.ytimg.com https://*.google-analytics.com https://*.googletagmanager.com https://www.google.be data:;
connect-src https://*.google-analytics.com https://*.analytics.google.com https://*.googletagmanager.com;
">
.......................................................
Debug Joomla Database errors
If no debugging only the Mysql error then enable debug, enable log everything in the debug plugin and add the snippet below to
\libraries\joomla\database\driver\mysqli.php around lines 656 and 668.
So just before the string with JLIB_DATABASE_QUERY_FAILED
query should be written in /logs/everything.php
JLog::add($query, JLog::ERROR, 'database-error');
.......................................................
|