translating the Time text to another language - cakephp

How can i translate the default Cake php time helper strings in my application, i'm using in Cake php a function called timeAgoInWords which from the time helper function, it give me a text like 5 hours, 52 minutes ago .
I want to translate this to another language, how can i do that ? i searched the documentation and i didn't get anything .
<?php echo $this->Time->timeAgoInWords($question['Question']['created']) ?>

You need a customized helper to get your stuff done. timeAgoInWords helper does not give the flexiblity of replacing words with your words.
Here, create a file called TimeagoHelper.php under your View/Helper
I am not sure which language you want translation in, I will write in English, you can replace your words.
<?php
App::uses('AppHelper', 'View/Helper');
class TimeagoHelper extends AppHelper {
public function __construct(View $view, $settings = array()) {
parent::__construct($view, $settings);
}
public function timeago($datetime) {
$datetime1 = new DateTime($datetime);
$datetime2 = new DateTime('now');
$obj = $datetime1->diff($datetime2);
if($obj->days == 1) {
$time = $obj->format('%a day'); // Replace your word
} elseif($obj->days == 0) {
if($obj->h == 0) {
if($obj->i == 0) {
$time = $obj->s . ' seconds'; // Replace your word
} else {
$time = $obj->i . ' minutes'; // Replace your word
}
} else {
$time = $obj->h . ' hours'; // Replace your word
}
} else {
$time = $obj->format('%a days'); // Replace your word
}
return $time.' ago'; // Replace your word
}
}
Load this helper in your action or controller.
I have been using php 5.5 since quite sometime, am not sure if it works on lesser versions, i.e. don't remember if concat is allowed as done for seconds and minutes. Incase, it doesn't work, assign them to variables and concat those.
Use it in View's .ctp file like so:
$this->Timeago->timeago($question['Question']['created']);
PS: CakeTime comes in handy too, check out the api for possibilities.
Cheers!

Related

php code not working in default.ctp page in Cakephp2.8.5

Thanks in advance, I am new to cakephp, i am using cakephp2.8.5 version. Actually i want to write a php code for counting number of records from the mysql database table comparing the ordered date column date values with the current date. I have written the code but my menus are in default.ctp page. In Order Check menu i have to show the count in numbers. default.ctp page lying in app/view/Layout/default.ctp so how to create a count value in php code without using controller.
My code will compare the current date with the table column date and calculates the count.How can i pass the variable $ordCounts into default.ctp page without creating controller page
Which is as below:
<?php
$a = 0;
for($j=0; $j<count($ordCounts) ;$j++)
{
$orderDate = $ordCounts[$j]['carts']['order_date'];
$currentDate = $dateTime;
$diff = strtotime($currentDate) - strtotime($orderDate);
$hour = $diff/(60*60);
if($hour>24)
{
$a++;
}
}
echo $a;
?>
Create beforeRender() method in AppController
public function beforeRender(){
parent::beforeRender();
//here your code
$this->set('a',$a);
}
$a variable will be available in templates
you can create a function of the above code which counts the occurences in AppController like this
function countOccurences(){
$a = 0;
for($j=0; $j<count($ordCounts) ;$j++)
{
$orderDate = $ordCounts[$j]['carts']['order_date'];
$currentDate = $dateTime;
$diff = strtotime($currentDate) - strtotime($orderDate);
$hour = $diff/(60*60);
if($hour>24)
{
$a++;
}
}
return $a;
}
and then call this function in your beforeFilterMethod in AppController
function beforeFilter(){
parent::beforeFilter();
$count = $this->countOccurences();
$this->set('count',$count);
}

how to set limit start in joomla from custom library

I have custom library and need to set limit start for list view records from this library.
Code is as follows:
$limitStart = $input->json->get('limit_start');
$model = JModelLegacy::getInstance('Articles', 'ContentModel', array('ignore_request' => true));
$model->setState("list.limit", $limitStart);
I did this but it's set default value to zero.
Can we override the limit start in joomla.
Thanks in advance.
I think you need to use following method to set the limitstart
$limitStart = 5;
$app = JFactory::getApplication();
$app->setUserState($this->context . '.limitstart', $limitStart);
Yes Can override the limitstart for your own library joomla framework
please flow this way
Open =>joomlaFile/configuration.php/for this code line no "7" default set 20
public $list_limit = '20'
Can you change to your Own PageLimit
public $list_limit = '5'
//simply read this
$config = JFactory::getConfig();
$limitStart = $config->get('list_limit');
you need system plugin to do this. see example for native tags component (the condition is needed to avoid rune code on wrong place )
public function onAfterRoute()
{
$app = JFactory::getApplication();
if ($app->input->getRaw('option') == 'com_tags' && $app->input->getRaw('view') == 'tag') {
$app->set('list_limit', 12);
}
}

Getter in a Behavior cakephp 3

I've just created a tag behavior to manage tags in an input text field (all keywords are separate by a comma). To do that I name my input "tag_string".
So I need to use a getter to handle the string.
I didn't understand how implement a _getTagString() method directly in the behavior.
If I use my getter (getTagString) in each entities file that use my behavior all my code works fine.
So to avoid write the same getter in each file I want to put it in my behavior file. But it doesn't work.
Here is my method:
public function _getTagString() {
if (isset($this->_properties['tag_string'])) {
return $this->_properties['tag_string'];
}
if (empty($entity->tags)) {
return '';
}
$tags = new Collection($entity->tags);
$str = $tags->reduce(function ($string, $tag) {
return $string . $tag->name . ', ';
}, '');
return trim($str, ', ');
}
Thanks for your help
After several searches I didn't find anything to implement accessors directly in the behavior.
I use trait, and It works fine.

CakePHP Shell Script Environment Setting

I am new to shell development in Cake. The problem I am facing is to setting datasource in the script itself. My database.php is;
function __construct()
{
if(getenv('ENVIRONMENT') == 'staging') {
$this->default = $this->staging;
} else {
$this->default = $this->production;
}
}
So, I am setting database based on the web server's environment setting. Naturally, php-cli can't access this variable. What I end up doing is to create a cakephp shell task.
class SelectEnvTask extends Shell {
public function execute()
{
App::Import('ConnectionManager', 'Model');
$configs = ConnectionManager::enumConnectionObjects();
if (!is_array($configs) || empty($configs)) {
$this->out('Error! No database configuration has been found.');
}
$connections = array_keys($configs);
if(!isset($this->args[0])) {
$this->out('Error! Please enter one of the environment settings as an argument: ' . implode('/', $connections) .
"\n\n" . 'eg. ./Console/cake *script_name* *environment*', 2);
exit(1);
}
if(!in_array($this->args[0], $connections)) {
$this->out($this->args[0] . ' environment could not be found!', 2);
exit(1);
}
//hacky solution until finding a better one
$models = App::objects('Model');
foreach($models as $model) {
ClassRegistry::init($model)->setDataSource($this->args[0]);
}
}
}
This works correctly, however as you see in the below of the task, I get all the model names and change their DB connection, which is not a good practice. I also don't want to set more variables into the database class and would like to handle these in shells/tasks.
Is there any more elegant way to achieve this?
Thanks,
Here is a far more elegant solution. Add the following method to your shell or task, and then execute it whenever you need to in order to change your data profile (listed in app/Config/database.php) on the fly:
function change_database_profile($database = 'default') {
$connected = ConnectionManager::getDataSource($database);
if($connected->isConnected()) {
return true;
}
return false;
}

CakePHP, GET Parameters and routing

I am fairly new to cakephp but I have a question relating to urls and parameters. I would like to be able to have a url that looks like a standard url e.g:
http://www.mysite.com/controller/myaction?arg=value&arg2=val
I would like that url to map to an action in my controller as follows:
function myaction($arg = null, $arg2 = null)
{
// do work
}
I realize that cakephp has routing as described here, however, honestly this seems over engineered and results in a url string that is nonstandard.
In my current situation the url is being generated and invoked by an external (billing) system that knows nothing about cake and doesn't support the cake url format.
You can have your URL in any form. It's just CakePHP allows you to retrieve the variable passed through GET from the variable $this->params['url']
function myaction()
{
if(isset($this->params['url']['arg']))
$arg = $this->params['url']['arg'];
if(isset($this->params['url']['arg2']))
$arg2 = $this->params['url']['arg2'];
}
Solution in AppController for CakePHP 2.x
class AppController extends Controller {
....
/***
* Recupera los Named envias por URL
* si es null $key emtraga el array completo de named
*
* #param String $key
*
* #return mixed
*/
protected function getNamed($key=null){
// Is null..?
if(is_string($key)==true){
// get key in array
return Hash::get($this->request->param('named'), $key);
}else{
// all key in array
return $this->request->param('named');
}
}
...
}
I have a similar problem. Not because I have an external system, but because I don't like to put all parameters into the URL-path. In my example, I have some search queries that are assembled and passed to the controller. IMHO, these queries should be GET parameters and not part of the URL-path.
One advantage of using GET parameters is that the order of the given parameters is not important, in contrast to passing params via the URL path.
To solve this problem in a generic way, I'm replacing all method arguments with the value of the GET-param, if one with the same name is given:
class MyController extends AppController
{
function test($var1 = null, $var2 = "content2")
{
foreach (get_defined_vars() as $key => $value) {
if (isset($this->params['url'][$key])) {
$getvalue = $this->params['url'][$key];
$$key = $getvalue;
CakeLog::write("debug", "Setting:$key to $getvalue");
}
}
CakeLog::write("debug", print_r(get_defined_vars(), true));
}
}
Now I can access this controller method and pass parameters via GET like this:
http://myapp/mycontroller/test?var1=foo&var2=bar

Resources