Joomla: know the section [SOLVED]

Lets suppose you are developing a joomla module and want to know the section in which you are.

The following code might help 🙂

<?php
function getSection($iId) {
    $database = &JFactory::getDBO();
    if(Jrequest::getCmd('view',0) == "section") {
        return JRequest::getInt('id');
    }
    elseif(Jrequest::getCmd('view',0) == "category") {
        $sql = "SELECT section FROM #__categories WHERE id = $iId ";
        $database->setQuery( $sql );
        $row=$database->loadResult();
        return $row;
    }
    elseif(Jrequest::getCmd('view',0) == "article") {
        $temp=explode(":",JRequest::getInt('id'));
        $sql = "SELECT sectionid FROM #__content WHERE id = ".$temp[0];
        $database->setQuery( $sql );
        $row=$database->loadResult();
        return $row;
    }
}
 
// use it like:
$sectionId=getSection(JRequest::getInt('id'));
?>

Joomla: know the section of an article [SOLVED]

Lets suppose you are developing a joomla module which displays some “share to facebook and twitter” links. That module should not display those links if the article’s section id is equals to 10.

We will be bulding a new function called getSection which will return the section of an article.

<?php
function getSection($iId) {
    $database = &JFactory::getDBO();
    if(Jrequest::getCmd('view',0) == "section") {
        return JRequest::getInt('id');
    }
    elseif(Jrequest::getCmd('view',0) == "category") {
        $sql = "SELECT section FROM #__categories WHERE id = $iId ";
        $database->setQuery( $sql );
        $row=$database->loadResult();
        return $row;
    }
    elseif(Jrequest::getCmd('view',0) == "article") {
        $temp=explode(":",JRequest::getInt('id'));
        $sql = "SELECT sectionid FROM #__content WHERE id = ".$temp[0];
        $database->setQuery( $sql );
        $row=$database->loadResult();
        return $row;
    }
}
 
// use it like:
$sectionId=getSection(JRequest::getInt('id'));
?>

For instance, you can rewrite the joomla addthis plugin. Notice lines 57-58 (the call to the new function) and lines 54-55 (remember the know where you are in joomla posts? ) 😉

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
<?php
/**
 * @version		$Id: example.php 10714 2008-08-21 10:10:14Z eddieajau $
 * @package		Joomla
 * @subpackage	Content
 * @copyright	Copyright (C) 2005 - 2008 Open Source Matters. All rights reserved.
 * @license		GNU/GPL, see LICENSE.php
 * Joomla! is free software. This version may have been modified pursuant
 * to the GNU General Public License, and as distributed it includes or
 * is derivative of works licensed under the GNU General Public License or
 * other free or open source software licenses.
 * See COPYRIGHT.php for copyright notices and details.
 * ------------------------------------------
 * MODIFIED By Miguel Martín 2011-07-22
 * ------------------------------------------
 */
 
// Check to ensure this file is included in Joomla!
defined( '_JEXEC' ) or die( 'Restricted access' );
 
jimport( 'joomla.plugin.plugin' );
 
 
function getSection($iId) {
  $database = &JFactory::getDBO();
  if(Jrequest::getCmd('view',0) == "section") {
      return JRequest::getInt('id');
  }
  elseif(Jrequest::getCmd('view',0) == "category") {
      $sql = "SELECT section FROM #__categories WHERE id = $iId ";
      $database->setQuery( $sql );
      $row=$database->loadResult();
      return $row;
  }
  elseif(Jrequest::getCmd('view',0) == "article") {
      $temp=explode(":",JRequest::getInt('id'));
      $sql = "SELECT sectionid FROM #__content WHERE id = ".$temp[0];
      $database->setQuery( $sql );
      $row=$database->loadResult();
      return $row;
  }
}
 
/**
 * Example Content Plugin
 *
 * @package		Joomla
 * @subpackage	Content
 * @since 		1.5
 */
class plgContentAddThisPlugin extends JPlugin
{
    function getButtonCode(&$params) {
	if($_REQUEST['view']=="frontpage") return ''; 
        //do not show the buttons in frontpage, no matter which is the section of the article
 
        if (JRequest::getVar('view')!='article') return ''; 
        // do not show if we are not on a full-view of the article
 
	$sectionId=getSection(JRequest::getInt('id'));
	if ($sectionId == '10') //the article category is equals to '10', so do not show the buttons...
		  	return '';
 
        $code = $this->params->get('code');
        if( empty($code) )
            $code = '<br/><a href="http://www.addthis.com/bookmark.php?v=250" onmouseover="return addthis_open(this, \'\', \'[URL]\', \'[TITLE]\')" onmouseout="addthis_close()" onclick="return addthis_sendto()"><img src="http://s7.addthis.com/static/btn/lg-share-en.gif" width="125" height="16" alt="Bookmark and Share" style="border:0"/></a><script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js?pub=xa-4a3f0b283a364b52"></script><br/>';
      return '<!-- section id='.$sectionId.' -->'.$code;
    }
 
	function onBeforeDisplayContent( &$article, &$params, $limitstart )
	{
		global $mainframe;
 
        if( $this->params->get('position')==1 )
            return $this->getButtonCode($params);
		return '';
	}
 
	function onAfterDisplayContent( &$article, &$params, $limitstart )
	{
		global $mainframe;
        if( $this->params->get('position')==2 )
            return $this->getButtonCode($params);
 
		return '';
	}
}

Joomla: crear un menú horizontal con extended menu [RESUELTO]

La mayoría de templates para Joomla vienen preparados con un menú vertical. Vamos a ver cómo añadir un menú horizontal en Joomla de una forma correcta y rápida.

Modificando el template (theme) para contener la zona del menú

Para mostrar las zonas preparadas para módulos en tu sitio joomla, puedes usar el parámetro ?tp=1. Por ejemplo, si tu sitio web es http://www.joomlaspanish.org puedes consultar la dirección http://www.joomlaspanish.org/?tp=1 y verás las zonas marcadas en tu theme. Algo asi:
joomla mostrar zonas para módulos con parámetro ?tp=1

Quizá nos sirva alguna de las zonas que ya tenemos predefinida. Si no nos sirve ninguna, habrá que añadirla.

Añadir una nueva zona a tu template de Joomla

Añadir una zona nueva es realmente sencillo. Por ejemplo os enseño cómo añadí la zona llamada headermiguel que podéis ver en la anterior imagen:

Empezamos editando el fichero /templates/tu-template/templateDetails.xml y añadiendo la información para definir la nueva zona. Algunos templates ya tienen definida la zona positions. Otros no. Si no la tiene, habrá que definirla:

<positions>
	<position>headermiguel</position>
</positions>

Después editamos el fichero /templates/tu-template/index.php para añadir la nueva zona para incluir el módulo headermiguel:

<div id="bajo_header_miguel">
     <jdoc:include type="modules" name="headermiguel" />
</div>

Ahora podremos colocar cualquier módulo en la nueva zona headermiguel. Para ello, nos vamos al menú de Administración, Extensiones -> Gestor de módulos. Allí podremos indicar, para cada módulo, en qué posición aparece. Veremos que en el listado aparece una nueva posición llamada headermiguel. Vamos bien.

Instalar extensión/componente Joomla Extended Menu

Esta extensión nos va a facilitar bastante el trabajo de creación de un menú horizontal, pues nos proporciona un marcado HTML correcto y nos facilita el camino para darle estilo con CSS.

Empezamos descargando Extended Menu, lo instalamos, lo habilitamos (Extensiones->Gestor de módulos), lo colocamos en la nueva zona headermiguel que hemos definido en el apartado anterior, le damos un nombre y marcamos que se despliegue como “flat list”. Atención a las tres flechas rojas y al Menu class suffix (donde he introducido _listamiguel, que nos facilitará la creación de un estilo para ese menú).

joomla extended menu

Guardamos y si recargamos la web y nos fijamos en el fuente, veremos una lista desordenada (ul), algo del tipo:

<div id="bajo_header_miguel">
  <ul  id="mainlevel_listamiguel">
      <li><a href="/" class="mainlevel_listamiguel" id="active_menu_listamiguel">Inicio</a></li>
      <li><a href="http://www.hyips.es/forum" class="mainlevel_listamiguel">FORO</a></li>
      <li><a href="/Partners" class="mainlevel_listamiguel">Partners</a></li>
      <li><a href="/banners-hyips" class="mainlevel_listamiguel">Banners</a></li>
      <li><a href="/Contacto" class="mainlevel_listamiguel">Contacto</a></li>
  </ul>
</div>

Dando estilo (CSS) a nuestro menú horizontal

Ya tenemos la zona, tenemos el código de la lista… lo único que falta es darle estilo, para que todos los elementos (li) aparezcan en una misma línea. Os dejo los estilos que he aplicado yo (editando el fichero template.css o el fichero CSS que corresponda a vuestro template):

/* horizontal menu by miguel
 * apoyado en extended menu (plugin)
 */
 
 #bajo_header_miguel{
 background-attachment: scroll;
    background-clip: border-box;
    background-color: transparent;
    background-image: url("../images/miguel_bg.png");
    background-origin: padding-box;
    background-position: center top;
    background-repeat: repeat-y;
    background-size: auto auto;
    margin-bottom: 0;
    margin-left: auto;
    margin-right: auto;
    margin-top: 0px;
    padding-bottom: 0;
    padding-left: 0;
    padding-right: 0;
    padding-top: 3px;
    text-align: left;
    width: 940px;
    height:25px;
 
}
 
 ul#mainlevel_listamiguel {
      margin:0px;
      padding-top: 5px;
      margin-left: 10px;
      margin-right: 10px;
      height: 20px;
      /*background-color: #002B89;*/
      /*background: #002B89 url("../images/miguel_a_medias1.png");*/
      background: url("http://www.hyips.es/templates/siteground-j15-54/images/h3.png");
      padding-left:0px;
  }
 
  ul#mainlevel_listamiguel li {
      display: inline; /* Shows each item side-by-side */
      list-style-type: none; /* Gets rid of the bullet points */
  }
 
  ul#mainlevel_listamiguel a {
      display: block;
      float: left;
      padding: 0 2em; /* separación entre items --> anchura total de todos los elementos */
      text-transform:uppercase;
      font-size: 1.4em;
      text-decoration: none;
      font-weight:bold;
      color: #BBB;
  }
 
  ul#mainlevel_listamiguel a:hover {
      display: block;
      float: left;
      padding: 0 2em; /* separación entre items --> anchura total de todos los elementos */
      text-transform:uppercase;
      font-size: 1.4em;
      text-decoration: none;
      font-weight:bold;
      color: #FFF;
  }
 
 /* ******************* fin de horizontal menu *************************/

Joomla templating – know where you are (full article view or article-listing) [SOLVED]

Some time ago I talked about how to know if you are in the frontpage or not

But you might want to know (for instance, for plugin displaying) if you are viewing a full article or just a listing of articles (with just a preview of the articles’ content).

How do you do this? You must use the JRequest::getVar function as in:

if (JRequest::getVar('view')=='article'){
    // then you are displaying a full article
    // do whatever you want in full article visualization...
}
else{
  // stuff to be displayed in the rest of the pages...
}

You could also use JRequest::getvar('option', '') or JRequest::getCmd( 'option' )to know if you are, for instance, in com_content or in any other module as in:

   <?php if((JRequest::getCmd( 'view' ) == 'article') or (JRequest::getCmd( 'option' ) == 'com_twc4j')) :?>

With this lines you could hack some plugins (like, for example, addthis plugin for joomla) to display just as you want. Take a look at this self-explained code:

function getButtonCode(&$params) {
	if($_REQUEST['view']=="frontpage") return ''; //we are in the frontpage, so return an empty string
	if (JRequest::getVar('view')!='article') return ''; //we are not showing an article, so return an empty string
 
        // Here we know that we are displaying an article... so I want to show addthis code.
        $code = $this->params->get('code');
        if( empty($code) )
            $code = '<br/><a href="http://www.addthis.com/bookmark.php?v=250" onmouseover="return addthis_open(this, \'\', \'[URL]\', \'[TITLE]\')" onmouseout="addthis_close()" onclick="return addthis_sendto()"><img src="http://s7.addthis.com/static/btn/lg-share-en.gif" width="125" height="16" alt="Bookmark and Share" style="border:0"/></a><script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js?pub=xa-4a3f0b283a364b52"></script><br/>';
        return $code;
}

Thanks a lot to shockM user of joomlaspanish.org forums for the explanation! (Read full post in spanish here).

Joomla plugin and templating: how to know if you are in the frontpage

There are many situations in which a joomla developer needs to know if the code is being shown / executed in the main page. This is, the “context” in which the code is executed. For instance, if you want to use a different template for the frontpage and another for other visualizations (custom frontpage). Or if you only want a plugin to be shown if the page is not frontpage.

How is this done?

Joomla 1.0.*

<?php if($_REQUEST['option']=="com_frontpage" || !isset($_REQUEST['option'])){?>
Have the HTML code for the homepage layout
<? }
else{?>
Have HTML code for the rest of the pages
<?php } ?>

Joomla 1.5.*

<?php if($_REQUEST['view']=="frontpage") {?>
Have the HTML code for the homepage layout
<? }
else{?>
Have HTML code for the rest of the pages
<?php } ?>

Personalizar la página de “El sitio está desactivado por tareas de mantenimiento”

Cuando instalas Joomla! y decides poner el sitio en mantenimiento hasta que termines de configurar la web, aparece una pantalla que permite identificarse al admin únicamente para que él, y sólo él, vaya viendo las evoluciones del sitio web.

Para modificar la apariencia de esa página (por ejemplo modificando el logo que aparece, que por defecto es joomla_logo_black.jpg), sólo tienes que editar /templates/system/offline.php.

En mi caso cambié la línea 28 para tocar el logo:

...
<!--<img src="images/joomla_logo_black.jpg" alt="Joomla! Logo" align="middle" />-->
<img src="images/el_logo_del_cliente.jpg" alt="Joomla! Logo" align="middle" />
...

joomla 1.5, ampersands and W3C validator

If you use joomla 1.5 and try to validate your DTD against W3C it is likely to have some errors related to ampersands.

This is due to a ¿bug? in default’s Joomla WYSIWYG editor (TinyMCE 2.0). By default this editor does not code the ampersands (&) to (&). If you try to write HTML using this editor and include a “&” you will notice it automatically changes “&” to “&”.

Getting rid of these annoying errors is quite simple. Just intall JCE (Joomla! Content Editor) plugin.

After the instalation is complete:

1. Log in to your administrator panel.
2. Click Site->Global Configuration.
3. Under the first tab (“Site”), find the parameter labelled “Default WYSIWYG Editor:”.
4. Select your JCE Editor 154 from the drop-down list (most likely the default editor was Tiny MCE 2.0.
5. Click the “Save” button in the toolbar.

Now validate your website again. You will get rid of those errors 😉