[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 this entry