Date en français - Cake 3

Par Darkh62, il y a 9 ans


Bonjour,

Lorsque j'affiche les dates (jours, mois) celle-ci sont en anglais, pour les convertir en français j'ai ajouter une fonction dans mon AppController (getDate()).

Pour pouvoir utiliser cette fonction j'ai effectuer la convertion à l'aide d'un foreach, mais je doute que le foreach soit la meilleur solution, je me retrouve donc pour l'instant avec 2 foreach sur la même page.
EDIT: Cette façon ne converti que le premier élément.

Quel méthode serait la mieux adaptée dans mon cas ?

AccueilController.php

<?php namespace App\Controller; use Cake\ORM\TableRegistry; use Cake\I18n\Date; class AccueilController extends AppController { public function getDate($date) { return parent::getDate($date); } public function index() { // Récupération des dernières soirées $events = TableRegistry::get('Events'); $events = $events->find('all', [ 'conditions' => ['Events.active' => 1], 'limit' => 3, 'order' => 'Events.id DESC', 'fields' => ['Events.id','Events.name','Events.date','Events.img'] ]); $d = $events->toArray(); foreach ($d as $val) { $val->date = $this->getDate($val->date->format('l j F Y')); } // Récupération des dernièrs articles $articles = TableRegistry::get('Articles'); $articles = $articles->find('all', [ 'conditions' => ['Articles.active' => 1], 'limit' => 3, 'order' => 'Articles.id DESC' ]); $this->set('articles', $articles); $this->set('events', $events); $this->set('val', $val); } } ?>

AppController.php

<?php namespace App\Controller; use Cake\Controller\Controller; use Cake\Event\Event; use Cake\I18n\I18n; class AppController extends Controller { /** * Initialization hook method. * * Use this method to add common initialization code like loading components. * * e.g. `$this->loadComponent('Security');` * * @return void */ public function initialize() { parent::initialize(); $this->loadComponent('RequestHandler'); $this->loadComponent('Flash'); $this->loadComponent('Csrf'); } public function beforeFilter(Event $event) { return parent::beforeFilter($event); I18n::locale('fr_FR'); } public function getDate($date) { $search = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday', 'January','February','March','April','May','June','July','August','September', 'October','November','December']; $replace = ['Lundi','Mardi','Mercredi','Jeudi','Vendredi','Samedi','Dimanche','Janvier','Fevrier','Mars', 'Avril','Mai','Juin','Juillet','Août','Septembre','Novembre','Decembre']; return str_replace($search, $replace, $date); } public function beforeRender(Event $event) { if (!array_key_exists('_serialize', $this->viewVars) && in_array($this->response->type(), ['application/json', 'application/xml']) ) { $this->set('_serialize', true); } } }

index.ctp

<section class="evenements"> <?php foreach ($events AS $event): ?> <div class="eCible"> <?= $this->Html->link( '<img src="'.$event->img.'">', ['controller' => 'Events','action' => 'view','name' => $event->getNameUrl(),'id' => $event->id], ['escape' => false] ); ?> <?= $this->Html->link( '<span class="titre">'.$event->name.'</span>', ['controller' => 'Events','action' => 'view','name' => $event->getNameUrl(),'id' => $event->id], ['escape' => false] ); ?> <span class="date"><?= $val->date; ?></span> </div> <?php endforeach; ?> </section>

Merci !

10 réponses

alexyon, il y a 9 ans

Slt, tu dois configurer ton fichier bootstrap avec les locales

date_default_timezone_set('Europe/Paris'); DispatcherFactory::add('LocaleSelector', ['locales' => ['fr-FR']]); /** * Set the default locale. This controls how dates, number and currency is * formatted and sets the default language to use for translations. */ ini_set('intl.default_locale', 'fr_FR');
Darkh62, il y a 9 ans

J'avais déjà essayer mais ça n'a rien donnée, la date est toujours en anglais

date_default_timezone_set('Europe/Paris'); use Cake\Routing\DispatcherFactory; DispatcherFactory::add('LocaleSelector', ['locales' => ['fr-FR']]); ini_set('intl.default_locale', 'fr_FR');
alexyon, il y a 9 ans

OK as tu crée des flichiers POT dans le dossier locales ?

Darkh62, il y a 9 ans

J'avais également essayer, c'est la première méthode que j'ai essayer d'ailleurs, les seuls textes que j'ai du traduire c'est Error et Back...

J'ai peut être louper quelques chose ?

alexyon, il y a 9 ans

j'ai 1 fichier dans src/Locale/fr
cake.po

# LANGUAGE translation of CakePHP Application # Copyright YEAR NAME <EMAIL@ADDRESS> # msgid "" msgstr "" "Project-Id-Version: PROJECT VERSION\n" "POT-Creation-Date: 2015-02-25 13:32+0000\n" "PO-Revision-Date: 2015-02-25 15:32+0100\n" "Last-Translator: NAME <EMAIL@ADDRESS>\n" "Language-Team: <EMAIL@ADDRESS>\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=2; plural=(n > 1);\n" "X-Generator: Poedit 1.7.4\n" "Language: fr\n" #: Template/Error/error400.ctp:33 Template/Error/error500.ctp:35 msgid "Error" msgstr "Erreur" #: Template/Error/error400.ctp:35 msgid "The requested address %s was not found on this server." msgstr "L'adresse demandée %s n'a pas été trouvé sur ce serveur." #: Template/Error/error500.ctp:33 msgid "An Internal Error Has Occurred" msgstr "Une erreur interne s’est produite." #: Controller/Component/AuthComponent.php:435 msgid "You are not authorized to access that location." msgstr "Zone à accès restreint:" #: Controller/Component/CsrfComponent.php:148 msgid "Invalid CSRF token." msgstr "Jeton non valide CSRF." #: Error/ExceptionRenderer.php:225 msgid "Not Found" msgstr "Non trouvé" #: Error/ExceptionRenderer.php:227 msgid "An Internal Error Has Occurred." msgstr "Une erreur interne s’est produite." #: I18n/Number.php:75 msgid "{0,number,#,###.##} KB" msgstr "{0,number,#,###.##} KB" #: I18n/Number.php:77 msgid "{0,number,#,###.##} MB" msgstr "{0,number,#,###.##} MB" #: I18n/Number.php:79 msgid "{0,number,#,###.##} GB" msgstr "{0,number,#,###.##} GB" #: I18n/Number.php:81 msgid "{0,number,#,###.##} TB" msgstr "{0,number,#,###.##} TB" #: I18n/Number.php:73 msgid "{0,number,integer} Byte" msgid_plural "{0,number,integer} Bytes" msgstr[0] "{0,number,integer} Byte" msgstr[1] "" #: I18n/Time.php:251 msgid "%s ago" msgstr "il y a: %s" #: I18n/Time.php:252 msgid "on %s" msgstr "% s" #: I18n/Time.php:287 msgid "just now" msgstr "à l'instant" #: I18n/Time.php:403 msgid "about a second ago" msgstr "il y a environ une seconde" #: I18n/Time.php:404 msgid "about a minute ago" msgstr "Iil y a une minute" #: I18n/Time.php:405 msgid "about an hour ago" msgstr "il y a une heure" #: I18n/Time.php:406 msgid "about a day ago" msgstr "il y a un jour" #: I18n/Time.php:407 msgid "about a week ago" msgstr "il y a une semaine" #: I18n/Time.php:408 msgid "about a year ago" msgstr "il y a un an" #: I18n/Time.php:417 msgid "in about a second" msgstr "environ une seconde" #: I18n/Time.php:418 msgid "in about a minute" msgstr "environ une minute" #: I18n/Time.php:419 msgid "in about an hour" msgstr "environ une heure" #: I18n/Time.php:420 msgid "in about a day" msgstr "environ un jour" #: I18n/Time.php:421 msgid "in about a week" msgstr "environ une semaine" #: I18n/Time.php:422 msgid "in about a year" msgstr "environ un an" #: I18n/Time.php:376 msgid "{0} year" msgid_plural "{0} years" msgstr[0] "{0} an" msgstr[1] "{0} ans" #: I18n/Time.php:379 msgid "{0} month" msgid_plural "{0} months" msgstr[0] "{0} mois" msgstr[1] "{0} mois" #: I18n/Time.php:382 msgid "{0} week" msgid_plural "{0} weeks" msgstr[0] "{0} semaine" msgstr[1] "{0} semaines" #: I18n/Time.php:385 msgid "{0} day" msgid_plural "{0} days" msgstr[0] "{0} jour" msgstr[1] "{0} jours" #: I18n/Time.php:388 msgid "{0} hour" msgid_plural "{0} hours" msgstr[0] "{0} heures" msgstr[1] "{0} heures" #: I18n/Time.php:391 msgid "{0} minute" msgid_plural "{0} minutes" msgstr[0] "{0} minute" msgstr[1] "{0} minutes" #: I18n/Time.php:394 msgid "{0} second" msgid_plural "{0} seconds" msgstr[0] "{0} seconde" msgstr[1] "{0} secondes" #: Network/Response.php:1390 msgid "The requested file was not found" msgstr "Le fichier recherché est introuvable" #: ORM/RulesChecker.php:317 msgid "This value is already in use" msgstr "Cette valeur est déjà en cours d'utilisation" #: ORM/RulesChecker.php:351 msgid "This value does not exist" msgstr "Cette valeur n'existe pas" #: Utility/Text.php:658 msgid "and" msgstr "et" #: Validation/Validator.php:94 msgid "This field is required" msgstr "Ce champ est requis" #: Validation/Validator.php:95 msgid "This field cannot be left empty" msgstr "Ce champ ne peut être vide" #: Validation/Validator.php:560 msgid "The provided value is invalid" msgstr "La valeur donnée est invalide" #: View/Helper/FormHelper.php:906 msgid "New %s" msgstr "Nouveau %s" #: View/Helper/FormHelper.php:909 msgid "Edit %s" msgstr "Editer le %s" #: View/Helper/FormHelper.php:1677 msgid "Submit" msgstr "Envoyer" #: View/Helper/HtmlHelper.php:749 msgid "Home" msgstr "Accueil" #: View/Widget/DateTimeWidget.php:496 msgid "January" msgstr "Janvier" #: View/Widget/DateTimeWidget.php:497 msgid "February" msgstr "Février" #: View/Widget/DateTimeWidget.php:498 msgid "March" msgstr "Mars" #: View/Widget/DateTimeWidget.php:499 msgid "April" msgstr "Avril" #: View/Widget/DateTimeWidget.php:500 msgid "May" msgstr "Mai" #: View/Widget/DateTimeWidget.php:501 msgid "June" msgstr "Juin" #: View/Widget/DateTimeWidget.php:502 msgid "July" msgstr "Juillet" #: View/Widget/DateTimeWidget.php:503 msgid "August" msgstr "Août" #: View/Widget/DateTimeWidget.php:504 msgid "September" msgstr "Septembre" #: View/Widget/DateTimeWidget.php:505 msgid "October" msgstr "Octobre" #: View/Widget/DateTimeWidget.php:506 msgid "November" msgstr "Novembre" #: View/Widget/DateTimeWidget.php:507 msgid "December" msgstr "Décembre"
Darkh62, il y a 9 ans

J'ai le même fichier, sauf qu'il n'est pas encore traduit.
Juste pour essayer de trouver le problème, ça ne viens pas des fichiers po puisqu'il marche sur un simple error.

<span class="date"><?= __($event->date->format('l j F Y')); ?></span> (tester avec et sans __() )

Me renvoie Wednesday 5 October 2016 alors que ça devrais être Mercredi 5 Octobre 2016

<div class="date"><?= __('Error'); ?></div>

Me renvoie bien Erreur

Je me suis également retaper la docs mais rien qui ne marche...

alexyon, il y a 9 ans

as tu mis ca à la fin de ton ficher bootstrap ?

Type::build('datetime')->useLocaleParser();
Darkh62, il y a 9 ans

Je viens de l'ajouter, toujours aucun changement
Les autres traductions marche correctement

stephbf, il y a 9 ans

bonjour

Pour le problème de date , perso j'ai créé deux tableau ,$day et $month puis je convertis mes dates avec strtotime.
ensuite il reste plus qu'à reconvertir dans le format FR.

Xeta, il y a 9 ans

Hello,
Sa parait compliqué à première vue à faire, mais en faite c'est assez simple.
Il faut déjà que ton champ date dans ta base de donnée, soit de type datetime.
Puis, il faut que tu définisses la langue en français I18n::locale('fr_FR'); dans le beforeFilter de ton AppController.
Dans ta vue, il faut que tu affiches cette date sous ce format :

<?= $article->created->i18nFormat([\IntlDateFormatter::FULL, \IntlDateFormatter::SHORT]) ?>

Plus d'info sur cette fonction ici : http://api.cakephp.org/3.0/class-Cake.I18n.Time.html#_i18nFormat

Enfin, il faut que tu extraies les phrases de ton application avec la commande bin/cake i18n extract et que tu traduises le fichier cake.pot en français (Avec un logiciel de type PoEdit) et que tu place les fichiers traduit cake.po et cake.mo dans src/Locale/fr_FR.