Show Joomla module only in specific articles? - templates

Is it possible to show modules in Joomla only in a specific article (not per menu item), but in standard module position?
For example somehow get the current article id in a template and insert the modules with according id suffix in the name?

I would advise you not to hardcode things like this in the template. My question is, why don't you want to use a menu item? You can create a hidden menu item for that article and use it, then assign the module to that menu item.
If you still want to do it without using a menu item, a possible workaround would be to use something like "mod_php" (some module that allows you to use php code) and do something more or less like this:
Create the module and assign it to a position that is not used anywhere (you can type whatever you want in the module position)
In your php module, put this code:
$option = JRequest::getVar( 'option', '' );
$view = JRequest::getVar( 'view', '' );
$id = JRequest::getInt( 'id', 0 );
if ( $option == "com_content" && $view == "article" && $id == YOUR_ARTICLE_ID ) {
$module = JModuleHelper::getModule('your_module_type', 'module_title');
if ( ! empty( $module ) ) {
$attribs = array( 'style' => 'xhtml' );
echo JModuleHelper::renderModule( $module, $attribs );
}
}
I'm sorry if the code snippet is not showing properly, but I hope you can read it ok. Just one thing, when you fill in the part saying 'your_module_type', don't include the "mod_" part of the name. For example, if you want to output a module of type "mod_article_list", you should write "article_list" in "your_module_type".
I hope it helps!

Related

How to get Joomla template style name?

I have a joomla template that has two styles. The name of the template is default, and the styles are cats and arts. is there a way to return the name of the current style in use.
the code below only return the name of the template
$template = $app->getTemplate();
if I do an echo $template; I get default. But what I would like to get, is whether I am using the style cats or the style arts
Thank you
The template object doesn't contain the name of the a templates style variations (as it's only really used for human administrators as a mnemonic).
The only way to tell which "style" is being used is to look at the id value of the template… this value will correspond to the one you see in the ID column of the "Template Manager - Styles" view.
// Get the Joomla Application
$app = JFactory::getApplication();
// Get the template
$template = $app->getTemplate(true);
// Echo the ID
echo $template->id;
If you really need the "name" I think you're probably making a design mistake, having said that you could try loading the style model for the $template->id and retrieving it that way. e.g. something like this (warning typed directly into SO, NOT TESTED!)
// Initialise some vars
$name = 'Style';
$prefix = 'TemplatesModel';
$config = array();
// Get the model
$templateStyleModel = JModelLegacy::getInstance($name, $prefix, $config);
// Load the specific style instance.
$templateStyleModel->load($template->id);
// Echo out the style name
echo $templateStyleModel->title;
$params = $app->getTemplate(true)->params;
Use $params->get() to get the particular style's params.
The solution look are looking for is:
$app = Factory::getApplication();
$template = $app->getTemplate(true);
$styleModel = new Joomla\Component\Templates\Administrator\Model\StyleModel();
$style = $styleModel->getItem($template->id);
$style->alias = Joomla\CMS\Filter\OutputFilter::stringURLSafe($style->title);

How to update module parameters in J2.5?

i am trying to update the value of parameter . I have a hidden field in xml file, i need to update its value , value is dynamic.
I got the parameters using
jimport('joomla.application.module.helper');
$module = JModuleHelper::getModule('mod_name');
I want to avoid the use database query method .
Is there joomla predefined function to achieve this task?
thanks in advance
-Neil
Unfortunately Joomla doesn't have an in-built API feature to set a parameter without using a database query. Try the following:
<?php
jimport( 'joomla.application.module.helper' );
$module = JModuleHelper::getModule( 'mod_name'); // change module name here
$params = new JRegistry();
$params->loadString($module->params);
$params->set('param_name', 'value'); // change parameter name and the value
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->update('#__extensions AS a')
->set('a.params = ' . $db->quote((string)$params))
->where('a.element = "mod_name"'); //change module name here
$db->setQuery($query);
$db->query();
?>
I have tested this code so let me know if it works

Zend Framework 2 Saving layout and template content in database

I want to save both layout and view template CONTENT in the database. Each view template will be associated to a layout_id. When a controller action loads, it will fetch the appropriate layout and view from database.
I've done fair amount of researching, looks like this hasn't been discussed before, at least not with ZF2. Not only I want different themes for the site, I also want version control on the design, user can work on a version of template, save it and when done publish the site. I've been looking into custom view strategy and renderer and could not find out how to piece everything together.
Please advice how to proceed with this problem. If there are any tutorials out there please let me know.
First, you have to decide your database structure. I would prefer a table where for each controller/action, depending on the version of the design, you have a file for the layout view, and another for the action view. I think it is a flexible way, since you can have for instance the same layout for all the controllers, but a a different view for the content of every action, or you can have a different layout for an specific controller.
It could be something like this.
CREATE TABLE `templates` (
`version` INT(5) NOT NULL,
`controller` VARCHAR(30) NOT NULL,
`action` VARCHAR(30) NOT NULL,
`layout_view` VARCHAR(30) DEFAULT NULL,
`action_view` VARCHAR(30) DEFAULT NULL,
PRIMARY KEY (`version`,`module`,`controller`,`action`)
)
remember that the template names has to be 'MODULE/CONTROLLER/ACTION' that is the format that the function ViewModel::setTemplate is expecting. So if in your Module Foo, you have the folder view, with a hierachy like this Foo/view/foo/controllerName/actionName.phtml in your database you should store: foo/controllerName/actionName
Then you have to set, somewhere in the config files, the current design version that has to be used. This version could be a different one in your local machine, and in the production server. For that, you leverage the /config/autoload/local.php that allows you to have different configuration in the different enviroments, just telling your git, subversion, or ftp, to ignore this file, so you can have a different one in every enviroment. Check this docs. It will be enough if you put something like this:
/config/autoload/local.php
return array(
'designVersion' => 1,
);
Then when the application loads, you have to check the current version of the design, and set the correct templates to be used. I would do it after the dispatch event, so the way would be to add a listener in the app bootstrarp. For that, in your main module (i.e. "App" or "Application" module), in the Module.php you overwrite the onBootstrap function, load the event manager, and add a callback to the MvcEvent::EVENT_DISPATCH event.
There, you can have access to the serviceManager, so you can retrieve your database adapter, also, you can know the current requested controller and action, the current viewmodel object, and from it, the action viewmodel. So you already have everything you need. So you can go like this:
public function onBootstrap(MvcEvent $e) {
//get the service manager
$sm = $e->getApplication ()->getServiceManager ();
//get your db adapter
$db=$sm->get("whatever is the service name of your database adapter, entity manager, or whatever you are using");
//get the config
$config = $sm->get ( 'config' );
$version = $config ['designVersion'];
//get the event manager, and attach a callback to the MvcEvent::EVENT_DISPATCH
$em = $e->getApplication ()->getEventManager ();
$em->attach ( MvcEvent::EVENT_DISPATCH, function ($e) use($sm) {
//you get the routeMath, so you can know the controller and action
$routeMatch = $e->getRouteMatch ();
$action=$routeMatch->getParam ( 'action' );
$controller=$routeMatch->getParam ( 'controller' );
//now, with $action, $controller, and $version
//you query your db to get the layout and view templates:
$views=$db->whetever..
$layout_template= $views->layout_view;
$action_template= $views->action_view;
//you get the current viewModel, it hasnt been rendered yet, so we can set the templates
$viewModel = $e->getViewModel ();
if (is_null ( $viewModel ))
return;
$viewModel->setTemplate ($layout_template);
//and now, we get the action view model, that we know that is set as a children of the layout viewmodel. So we can retrieve it like this:
$children = $viewModel->getCurrent()->getChildren();
$child = $children[0];
//if we are afraid the view could have more children, and you want to make sure that you rerieve the correct one, then you could iterate over $children and look for the child that has the correct captureTo name set. For the action’s view model, this defaults to content:
/*
$children = $viewModel->getCurrent()->getChildren();
$child=null;
foreach($children as $c) {
if ($c->captureTo() == 'content') {
$child=$c;
break;
}
}
*/
//and now, you set the template to the view:
$child->setTemplate ($action_template);
}, - 100 );
}

mediawiki: is there a way to automatically create redirect pages that redirect to the current page?

My hobby is writing up stuff on a personal wiki site: http://comp-arch.net.
Currently using mediawiki (although I often regret having chosen it, since I need per page access control.)
Often I create pages that define several terms or concepts on the same page. E.g. http://semipublic.comp-arch.net/wiki/Invalidate_before_writing_versus_write_through_is_the_invalidate.
Oftentimes such "A versus B" pages provide the only definitions of A and B. Or at least the only definitions that I have so far gotten around to writing.
Sometimes I will define many more that two topics on the same page.
If I create such an "A vs B" or other paging containing multiple definitions D1, D2, ... DN, I would like to automatically create redirect pages, so that I can say [[A]] or [[B]] or [[D1]] .. [[DN]] in other pages.
At the moment the only way I know of to create such pages is manually. It's hard to keep up.
Furthermore, at the time I create such a page, I would like to provide some page text - typicaly a category.
Here;s another example: variant page names. I often find that I want to create several variants of a page name, all linking to the same place. For example
[[multithreading]],
[[multithreading (MT)]],
[[MT (multithreading)]],
[[MT]]
Please don;t tell me to use piped links. That's NOT what I want!
TWiki has plugins such as
TOPICCREATE automatically create topics or attach files at topic save time
More than that, I remember a twiki plugin, whose name I cannot remember or google up, that included the text of certain subpages within your current opage. You could then edit all of these pages together, and save - and the text would be extracted and distributed as needed. (By the way, if you can remember the name of tghat package, please remind me. It had certain problems, particularly wrt file locking (IIRC it only locked the top file for editing, bot the sub-topics, so you could lose stuff.))
But this last, in combination with parameterized templtes, would be almost everything I need.
Q: does mediawiki have something similar? I can't find it.
I suppose that I can / could should wrote my own robot to perform such actions.
It's possible to do this, although I don't know whether such extensions exist already. If you're not averse to a bit of PHP coding, you could write your own using the ArticleSave and/or ArticleSaveComplete hooks.
Here's an example of an ArticleSaveComplete hook that will create redirects to the page being saved from all section titles on the page:
$wgHooks['ArticleSaveComplete'][] = 'createRedirectsFromSectionTitles';
function createRedirectsFromSectionTitles( &$page, &$user, $text ) {
// do nothing for pages outside the main namespace:
$title = $page->getTitle();
if ( $title->getNamespace() != 0 ) return true;
// extract section titles:
// XXX: this is a very quick and dirty implementation;
// it would be better to call the parser
preg_match_all( '/^(=+)\s*(.*?)\s*\1\s*$/m', $text, $matches );
// create a redirect for each title, unless they exist already:
// (invalid titles and titles outside ns 0 are also skipped)
foreach ( $matches[2] as $section ) {
$nt = Title::newFromText( $section );
if ( !$nt || $nt->getNamespace() != 0 || $nt->exists() ) continue;
$redirPage = WikiPage::factory( $nt );
if ( !$redirPage ) continue; // can't happen; check anyway
// initialize some variables that we can reuse:
if ( !isset( $redirPrefix ) ) {
$redirPrefix = MagicWord::get( 'redirect' )->getSynonym( 0 );
$redirPrefix .= '[[' . $title->getPrefixedText() . '#';
}
if ( !isset( $reason ) ) {
$reason = wfMsgForContent( 'editsummary-auto-redir-to-section' );
}
// create the page (if we can; errors are ignored):
$redirText = $redirPrefix . $section . "]]\n";
$flags = EDIT_NEW | EDIT_MINOR | EDIT_DEFER_UPDATES;
$redirPage->doEdit( $redirText, $reason, $flags, false, $user );
}
return true;
}
Note: Much of this code is based on bits and pieces of the pagemove redirect creating code from Title.php and the double redirect fixer code, as well as the documentation for WikiPage::doEdit(). I have not actually tested this code, but I think it has at least a decent chance of working as is. Note that you'll need to create the MediaWiki:editsummary-auto-redir-to-section page on your wiki to set a meaningful edit summary for the redirect edits.

Drupal preprocess function and session

I set a session var at template preprocess function in a theme I use, but the first time I open the site I cant read the session var, if I refresh the page it works fine, anybody know what can be the problem??
This is the code I use in the preprocess function:
function m_preprocess(&$vars, $hook) {
$default_location = array(
'country_code' => 'ec',
'province_code' => 'p',
'province' => 'Pichincha',
'city' => 'Quito',
'city_path' => 'lugares/u/ec/p/*'
);
if (isset($_COOKIE['proximity_path'])) $default_location['proximity_path'] = $_COOKIE['proximity_path'];
$default_location['path'] = isset($_COOKIE['sort-by']) && $_COOKIE['sort-by']=='proximity'? $_COOKIE['proximity_path'] : $default_location['city_path'];
$_SESSION['location'] = $default_location;
}
A couple of things:
Try dsm($_SESSION); to see what is the var content when the site first load.
I don't know where you create $_COOKIE['proximity_path'], but it is not in the code you show.
Check for typos
The template pre-process function is called before node.tpl.php (that's why it is called pre-process) and that is why the value of the $_SESSION variable is not available in the template preprocess function.
Like you pointed out, it works after the first page load. This happens when only after $_SESSION variable is set in the node body (using the PHP filter)