[CakePHP] How to fallback to default language while using Translate behavior

For one of my projects, I had a requirement from a client to fallback to default language if a phrase in chosen language was not found. This had to be done using CakePHP's Translate behavior.

Following is the step by step guide to modify Translate behavior so that it will fallback to default language for such situation.

1. If you need to only use the fallback for find('all') or find('first'), then do following
- Modify beforeFind() and add one more condition

PHP:
  1. 'I18n__'.$field.'.locale' => $locale

to $query['joins'] for else part of if (is_array($locale)). Also remove the

PHP:
  1. if (is_string($query['conditions'])) { ... } else { ... }

part just below it, as we have added needed condition to join conditions already.
- Modify afterFind() and replace $value = ''; with

PHP:
  1. $value = (isset($row[$model->alias][$field]) ? $row[$model->alias][$field] : '');

.

2. If you need to use the fallback for find('count') only, then do following
- Modify beforeFind() and remove code in

PHP:
  1. if (is_string($query['fields']) && 'COUNT(*) AS '.$db->name('count') == $query['fields'])

block except return $query;.

3. If you need to use fallback for find('list') only, then do following alongwith option #1 above
- Modify beforeFind() and remove

PHP:
  1. foreach (array($field, $model->alias.'.'.$field) as $_field) { ... }

loop.

Note :- This hack works with CakePHP-1.2 as well as CakePHP-1.3

About Amit Badkas

Amit Badkas is Zend certified PHP5 and Zend Framework engineer, and has been working in SANIsoft for past 9 years, his present designation is 'Technical Manager'

2 Responses to [CakePHP] How to fallback to default language while using Translate behavior

  1. Josef July 24, 2011 at 4:50 pm #

    This worked like a charm but unfortunately when I save a row for a specific language, the default row is also updated! Any idea how to prevent this?

Trackbacks/Pingbacks

  1. [CakePHP] Tweak translate behavior get belongsTo translations at SANIsoft - August 29, 2011

    [...] on August 29, 2011 in CakePHP, HowTo, PHP TweetIn one of my earlier posts, I had written about How to fallback to default language while using Translate behavior. This is one more Translate behavior tweak (in continuation with the previous) to get belongsTo [...]

Leave a Reply