I was working on my CakePHP 2.0 and wanted to make a language helper so I don't have to pass a few language based things in my views. For this I created a LanguageHelper.
My first task was to include the language in all links.
<?php
class LanguageHelper extends AppHelper{
public $helpers = array(
'Html'
);
public function link($title, $url = null, $options = array(), $confirmMessage = false){
if(!isset($options['lang']) || !$options['lang']){
$options['lang'] = Configure::read('Language.default');
}
return $this->Html->link($title, $url, $options, $confirmMessage);
}
}
?>
Now in my view I use the following:
<?php echo $this->Language->link('Link', array('controller' => 'pages', 'action' => 'home')); ?>
Expected result:
<a href="/nl-be/admin/pages/home">Link</a>
Actual result:
<a lang="nl-be" href="/admin/pages/home">Link</a>
Even using the following:
<?php echo $this->Language->link('Link', array('controller' => 'pages', 'action' => 'home', 'lang' => Configure::read('Language.default'))); ?>
Gives me a wrong result:
<a lang="nl-be" href="/nl-be/admin/pages/home">Link</a>
The following is in my routes:
Router::connect('/', array('controller' => 'app', 'action' => 'defineLanguage'), array('lang' => '[a-zA-Z]{2}[-]{1}[a-zA-Z]{2}'));
Router::connect('/:lang', array('controller' => 'pages', 'action' => 'home'), array('lang' => '[a-zA-Z]{2}[-]{1}[a-zA-Z]{2}'));
$prefixes = Configure::read('Routing.prefixes');
foreach($prefixes as $prefix){
Router::connect('/:lang/' . $prefix, array('prefix' => $prefix, $prefix => true, 'controller' => 'pages', 'action' => 'index'), array('lang' => '[a-zA-Z]{2}[-]{1}[a-zA-Z]{2}'));
Router::connect('/:lang/' . $prefix . '/:controller', array('prefix' => $prefix, $prefix => true), array('lang' => '[a-zA-Z]{2}[-]{1}[a-zA-Z]{2}'));
Router::connect('/:lang/' . $prefix . '/:controller/:action', array('prefix' => $prefix, $prefix => true), array('lang' => '[a-zA-Z]{2}[-]{1}[a-zA-Z]{2}'));
}
Anyone know a way to get the expected result?
EDIT:
I Should also mention that the following does give me the expected result:
<?php echo $this->Html->link('Link', array('controller' => 'pages', 'action' => 'home', 'lang' => Configure::read('Language.default'))); ?>
SOLUTION:
class LanguageHelper extends AppHelper{
public $helpers = array(
'Html'
);
public function link($title, $url = null, $options = array(), $confirmMessage = false){
if(!isset($url['lang']) || !$url['lang']){
$url['lang'] = Configure::read('Language.default');
}
return $this->Html->link($title, $url, $options, $confirmMessage);
}
}
I'm still working on 1.3 but I assume that did not changed: you have to put 'lang' parameter into $url array in your helper, not into $options array.
Last line of your helper should be:
$this->Html->link($title, array_merge($url, array('lang' => $options['lang']), $options, $confirmMessage);
Additionally you should use other variable to avoid unnecessary attribute in your link.