Tuesday, February 24, 2009

Uh Oh

I realized yesterday that my site has been throwing an error for the past few days. The reason being was that the RSS feed url for Smashing Magazine had changed. I updated the footer feed display and now everything is all better.

Sunday, February 15, 2009

Internalization and Zend Form

One of the many growing requirements that I am experiencing at work is for internalization of our forms.  In this particular use case the languages available are limited to English and Spanish so I am not able to use Zend_Locale::BROWSER exclusively.  To make sure that correct form displays, in my form model class I created an array of allowed locales.  Before the form instantiated in the controller the language param is set the registry, and then that locale is checked against allowed locales.

References:
Translations - located in my models directory: Models/Languages/En.php and Es.php

// En.php

return array(
              'name'    => 'First Name',

              'address' => 'Address'
       );


// Es.php

return array (

         'name'     => 'nombre',         'address' => 'dirección'

       );



// Controller snippet
 /**
  * Add language to the registry
  */
  $locale = new Zend_Locale($this->_getParam('lang'));
  Zend_Registry::set('locale', $locale);

// Form snippet
  /**
   * Instance of Zend_Locale
   *
   * @var Zend_Locale
   */
  protected $_locale         = null;

  /**
   * Allowed locale regions
   *
   * @var array
   */
  protected $_allowedLocales = array('en', 'es');

  protected $_translations   = null;

    $this->addElement('note', 'quanityInstructions', array(
      'decorators'  => $this->_standardNoteDecorator,
      'description' => "{$this->_translations->_('quanityInstructions')}"
    ));

  /**
   * Prepare the form
   *
   * @return boolean
   */
  private function _prepare() {

    /**
     * Grab the browsers locale
     */
    $this->_locale = Zend_Registry::get('locale');

    /**
     * If the browser is locale isn't English or Spanish then default to
     * English
     */
    if (!$this->_checkForValidLocaleRegion($this->_locale)) {
      $this->_locale = new Zend_Locale('en_US');
    }

    $transFile = ucfirst($this->_locale->getLanguage()).'.php';

    $this->_translations = new Zend_Translate('array', realpath(dirname(__FILE__).'/../../Models/HemOnc/Languages/'.$transFile), $this->_locale);

    return true;
  }

  /**
   * Check to make sure that browser's locale is english or spanish.  The region
   * doesn't matter.
   *
   * @param Zend_Locale $zl
   * @return boolean
   */
  private function _checkForValidLocaleRegion(Zend_Locale $zl) {
    return in_array($zl->getLanguage(), $this->_allowedLocales) ? true : false;
  }


If locale is allowed then the form label translation is set.

For further info please contact me.