How to put an variable in a language file of Codeigniter? - variables

I'm using Codeigniter 2.0.1 and I'd like to put an variable in a language line. For example: if an user wants to register an account, and that username already exists I would like to put in my language line "This username $username is alrady in use". I saw in the validation error language lines that they used %s as variable. But if I put this in my custom authentication error lang file I just get a plain %s instead of a variable.

It doen't look like it is possible with the default Lang class. Personally I did it that way.
First a i18n_helper :
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
if ( ! function_exists('line_with_arguments'))
{
function line_with_arguments($line, $swap)
{
return str_replace('%s', $swap, $line);
}
}
and then I call it in my controller :
<?php
class Home extends CI_Controller
{
public function index()
{
$this->lang->load('test', 'english');
$this->load->helper('i18n');
echo line_with_arguments($this->lang->line('test'), 'Matt');
}
}
and my lang file :
<?php
$lang['test'] = 'Hello %s';

Related

Ho to call variables items on Joomla Component

I'm trying to create my first component in Joomla but I can't understand how it works really :D
I create a basic component with "Component Creator". (I saved a lot of time...).
Now, I have a table in my DB where I've put my data:
id = 1
name = Andrea
note = Ciao
Now, I want to call it from the page using Joomla Language.
On my models/component.php i wrote:
class Variabili extends JModelLegacy
{
function estraivariabili()
{
$db =& JFactory::getDBO();
$db->setQuery("SELECT * FROM #__table")->loadObjectList();
return $value;
}
}
and on my default.php I wrote
$model=$this->Variabili();
//call the method
$items=$model->estraivariabili();
//print
print_r($items);
But on the page I have this error:
0 Call to undefined method Calcolo_imposteViewCalcoloonline::Variabili()
Where is a mistake?
Please be gentle with me because I'm a beginner: D
Thanks in advance
Andrea
You have committed a few wrongs. I've rewritten your functions so that you can get it. Let's have a look-
The model, it looks almost okay. Just change it like-
class Variabili extends JModelLegacy
{
// Make the function public
public function estraivariabili()
{
$db = &JFactory::getDBO();
// Put the result into a variable first, then return it.
$value = $db->setQuery("SELECT * FROM #__table")->loadObjectList();
return $value;
}
}
And now call the model functions not from default.php, rather than write your code inside view.html.php file.
Inside the display function of view.html.php file first, get the model instance by using getModel() function.
$model = $this->getModel();
Now you can get the items by using this $model class instance.
$this->items = $model->estraivariabili();
This will bring you the data from the database table. And you can use the data at default.php file.
Just try at default.php file-
print_r($this->items);

Prestashop beforeRequest Middleware

I am trying to build a module for Prestashop 1.6 that would redirect the user if the targeted URL is present in a database.
What I'm going to do is the following:
public function checkRedirection ($url) {
$line = Db::getInstance()->executeS('SELECT * FROM ps_custom_redirection WHERE url = ' . pSQL($url));
if (!sizeof($line)) {
return null;
}
header('Location: ' . $line[0]['destination']);
http_response_code($line[0]['http_code']);
exit();
}
Now, I could run this function when the displayTop hook is fired. But I would rather launch this function at the beginning of the request's process.
Does Prestashop provide such a hook? If not, can I create one? Where should I write the code to fire it?
The fist hook executed is actionDispatcher – you can use it if you want.
You'll find this hook executed in /classes/Dispatcher.php. Search for the code Hook::exec('actionDispatcher', $params_hook_action_dispatcher);.
If you want to add this hook to your module, you need to use its name in the main module file like this:
public function install() {
return parent::install()
&& $this->registerHook('actionDispatcher');
}
public function hookActionDispatcher($params) {
// your code
Tools::redirect($url);
}
In Prestashop Tools::redirect($url); is used if redirecting.

How to create a page in a prestashop module such that the output is not wrapped in the site's template html AND using translation?

What I know to do:
1) Create a module controller that allows translation.
I can declare texts to translate either in the controller itself or in the template:
/modules/mymodule/controllers/front/list.php
class myModuleListModuleFrontController extends ModuleFrontController
{
public function initContent()
{
parent::initContent();
$this->l('Some text to translater');
$this->setTemplate('list.tpl');
}
}
/modules/mymodule/views/templates/front/list.tpl
{l s='Some other text' mod='mymodule'}
2) I know to create some output that is not embedded in html, like for instance some json object:
/modules/mymodule/json.php
include( '../../config/config.inc.php' );
echo json_encode(array('key' => 'Some text'));
What I need:
I need to be able to translate some text AND have the output sent to the browser without the surrounding html. I have to be able to do one of those:
use a standalone file and be able to declare text to translate, similar to this (does not work):
include( '../../config/config.inc.php' );
echo json_encode(array('key' => l('Some text')));
use a module controller and force raw output, similar to this (does not work either):
class myModuleListModuleFrontController extends ModuleFrontController
{
public function initContent()
{
parent::initContent();
$this->noHtml = true;
echo json_encode(array('key' => l('Some text')));
}
}
If you want to translate text in FrontController, you can only do it in two ways:
Translate the texts inside a template
// Inside module front controller
$template = '.../template.tpl'
$this->context->smarty->fetch($template)
// Inside template.tpl
{l s='Translateable text' mod='mymodule'}
Or use strings already translated inside main module file
// Inside module front controller
$this->module->l('My string');
// But it has to already exist inside mymodule.php
$this->l('My string'); // You don't have to use it, it just has to exist to get scanned by RegEx.
If you want to return something back to Ajax request in your module front controller
public function init() {
parent::init(); // If you need to
// Some code here
if (Tools::getValue('ajax'))
{
header('Content-Type: text/html');
die($this->context->smarty->fetch($template));
// Or
header('Content-Type: application/json');
die(Tools::jsonEncode($response_array));
}
There is also a function called
FrontControllerCore::getLayout # Line 1209
Which you can use to override the whole page template, however, it should be used to create unique display for products and other page (like full screen product presentation, etc.)
If you want to ouput a file yourself while not providing a full file path to the user:
public function init() {
parent::init(); // If you need to
if (ob_get_level() && ob_get_length() > 0)
ob_end_clean();
// Set download headers
header('Content-Transfer-Encoding: binary');
header('Content-Type: '.$mime_type);
header('Content-Length: '.filesize($file));
header('Content-Disposition: attachment; filename="'.$filename.'"');
// Prevents max execution timeout, when reading large files
set_time_limit(0);
$fp = fopen($file, 'rb');
while (!feof($fp))
echo fgets($fp, 16384);
exit;
Apart from that, I don't image what else would tou possibly need to build your app. Always send token to your controllers for security!

How to call a console command in web application action in Yii?

I have a console command to do a consumer time, AND I need to know how to call (execute) it in a web application action in YII.
class MyCommand extends CConsoleCommand{
public function actionIndex(){
$model = new Product();
$model->title = 'my product';
...
$model->save();
.
.
.
}
}
I want to execute this code.
try this:
Yii::import('application.commands.*');
$command = new MyCommand("test", "test");
$command->run(null);
The 2 parameters with value "test" must be set but do not have an impact, they are used for the --help option when using the console.
/**
* Constructor.
* #param string $name name of the command
* #param CConsoleCommandRunner $runner the command runner
*/
public function __construct($name,$runner)
{
$this->_name=$name;
$this->_runner=$runner;
$this->attachBehaviors($this->behaviors());
}
https://github.com/yiisoft/yii/blob/master/framework/console/CConsoleCommand.php#L65
Try this
Yii::import('application.commands.*');
$command = new GearmanCommand('start', Yii::app()->commandRunner);
$command->run(array('start', '--daemonize', '--initd'));
where array('start', '--daemonize', '--initd') is a action and action parameters
I had same problem - i need to call action from inside controller and from command
I said same problem because it actually same - you have action which you need to call from console, and call it from controller too.
If you need to call an action(command) as a part of controller action, then i think you need to modify this solution a little. Or is my solution is enough for you?
So here is my solution:
first create action as said in http://www.yiichina.net/doc/guide/1.1/en/basics.controller#action
class NotifyUnsharedItemsAction extends CAction
{
public function run()
{
echo "ok";
}
}
then in controller action is loaded as usuall:
class TestController extends Controller
{
public function actions() {
return array(
'notifyUnsharedItems'=>'application.controllers.actions.NotifyUnsharedItemsAction',
);
}
and in command i run action in such way:
class NotifyUnsharedItemsCommand extends CConsoleCommand
{
public function run($args)
{
$action = Yii::createComponent('application.controllers.actions.NotifyUnsharedItemsAction',$this,'notify');
$action->run();
}
}
Accepting that we are on linux server, for Yii 1.1 real life example would be:
$run = '/usr/bin/php ' . Yii::getPathOfAlias('root').'/yiic' [command]
exec(sprintf("%s > %s 2>&1 & echo $! >> %s", $run, '/dev/null', '/dev/null'));
This will run Yii console command in the background.
Yii is PHP -> you can use the standard php constructs specified at http://php.net/manual/en/function.exec.php and the related methods near the bottom of the page, depending on what exactly you want to achieve.
Also, another very clean solution from cebe on gist:
<?php
// ...
$runner=new CConsoleCommandRunner();
$runner->commands=array(
'commandName' => array(
'class' => 'application.commands.myCommand',
),
);
ob_start();
$runner->run(array(
'yiic',
'idbrights',
));
echo nl2br(htmlentities(ob_get_clean(), null, Yii::app()->charset));
Yii::app()->end();
Typically what you should do in these situations is refactor.
Move the "common" code out of the MyCommand and place it into a class located in the components folder.
Now you can place any head on top of the "common" code without altering your functionality. For example:
protected/components/Mywork.php:
<?php
class Mywork
{
public function doWork()
{
$model = new Product();
$model->title = 'my product';
...
$model->save();
...
}
}
protected/controller/MyworkController.php:
<?php
class MyworkController
{
public function actionDowork()
{
$mywork = new Mywork;
...
}
}
protected/commands/MyworkCommand.php:
<?php
class MyworkCommand extends CConsoleCommand
{
public function run($args)
{
$mywork = new Mywork;
...
}
}
This approach makes testing easier too as you can test Mywork as a single unit outside of the view you are using.

Accessing auth session data (Lithium + MongoDB)

Okay, so hopefully I am asking this question correctly:
I set up my user model & controller, as well as my session model and controller... but I want to render some of the session info onto a page.
for example
If I were to login to a page, it would read "Brian" (or whatever my username is that I used for my login)
I hope I am not asking a repeated question -- I have searched this question pretty extensively and haven't found a solution yet. Thanks a lot!
If your session (set in a config/bootstrap file) is called "default" then just run check ...
$user = Auth::check('default');
Then $user will have an array of the user data in the session, so if you have a first_name field in your database/session you could do:
echo $user["first_name"];
I created a helper to clean this up a little, I called it: extensions/helper/Login.php
<?php
namespace app\extensions\helper;
use lithium\security\Auth;
class Login extends \lithium\template\Helper {
public function user() {
$user = Auth::check('default');
return $user;
}
public function fullName() {
$user = self::user();
return $user["first_name"] . " " . $user["last_name"];
}
}
?>
Then in my Views I used it like ...
<?=$this->login->fullName(); ?>