Hippyjim
Hippyjim

Reputation: 2522

Yii - Using i18n with CJuiDatePicker

I'm trying to make an internationalised Yii application.

I have a behaviour that translates dates to and from the users chosen locale date format so that's all handled fine.

When I try to set the language and date format for CJuiDatepicker from the locale settings, I end up with Chinese month names (no matter what locale format I pick), and US formatted dates.

The format that CJuiDatePicker wants for its dates and languages doesn't match what Yii provides - how do I make the picker work?

Upvotes: 2

Views: 1981

Answers (1)

Jon
Jon

Reputation: 437424

The problem with jQuery and Yii is that they don't both use the same locale names. For example Yii has locale names such as en and en_gb while jQuery does not have an en locale at all and calls the "English (United Kingdom)" locale en-GB (dash instead of underscore).

There's also the matter that Yii's and jQuery's date format specifiers differ.

To bridge the two worlds you 'll have to write some manual code; this is an excerpt from my own code that I 've used in a past project:

class LocaleExtensions {
    private static $yiiTojQueryFormatConversion = array(
        'yyyy' => 'yy',
        'yy' => 'y',
        'MMMM' => 'MM',
        'MMM' => 'M',
        'MM' => 'mm',
        'M' => 'm',
    );

    private static $yiiTojQueryLanguageConversion = array(
        'en' => 'en-GB',
    );

    public static function getJQueryDateFormat($width='medium') {
        return strtr(Yii::app()->getLocale()->getDateFormat($width),
                     self::$yiiTojQueryFormatConversion);
    }

    public static function getJQueryLanguageFromYii($language = null) {
        if ($language == null) {
            $language = Yii::app()->getLanguage();
        }

        if (isset(self::$yiiTojQueryLanguageConversion[$language])) {
            return self::$yiiTojQueryLanguageConversion[$language];
        }

        return $language;
    }
}

To fix the locale issue, you can subclass Yii's widgets to do this at an opportune time (or just do it manually):

$this->language = LocaleExtensions::getJQueryLanguageFromYii($this->language);

You can also retrieve a jQuery-compatible date format from your Yii settings and use it in Javascript code like this:

var format = <?php echo json_encode(LocaleExtensions::getJQueryDateFormat('long'));?>
var locale = <?php echo json_encode(LocaleExtensions::getJQueryLanguageFromYii());?>
var now = new Date();
alert($.datepicker.formatDate(format, now, $.datepicker.regional[locale]));

Upvotes: 3

Related Questions