How set localization for Zend_Dojo_Form elements? - php

Lets say I have a simple form:
class Form_Simple extends Zend_Dojo_Form
{
public function init() {
$this->addElements(array(
new Zend_Dojo_Form_Element_ValidationTextBox('name', array(
'required' => true,
'label' => 'Name:'
))
}
}
"name" element is required so error message will be "this field is required". How change this message?

You can localize the form labels just like in any other part of your application.
In your bootstrap file you have to setup the Zend_Locale and Zend_Translate object. It will be avialable in your entire application.
E.g in your boostrap:
//init locale
$translate = new Zend_Translate('gettext',
APPLICATION_PATH.'/languages',null,
array('scan' => Zend_Translate::LOCALE_FILENAME));
$locale = new Zend_Locale();
$locale->setLocale(Zend_Locale::BROWSER);
$requestedLanguage = key($locale->getBrowser());
if(in_array($requestedLanguage, $translate->getList())){
$language = $requestedLanguage;
}else{
$language = 'en';
}
$translate->setLocale($language);
$view->translate = $translate;
Since the setup is really detailed and maybe complex I recommend you to watch this tutorial http://www.youtube.com/watch?v=FwPgqla-cRk

Related

Yii2 create multilingual site for ajax search fields

I'm using Yii2 and I want to create a web application with the ability to perform fast searches.
For example, when I type characters in a textbox, results displayed.
It's easy with ajax when we have only one language but how about in multilingual mode?
First set up multi language for your site there is doc for this.
Best way of auto support multi language for your site is using cookies variable for language. You can set up language cookies from any action as
public function actionLanguage()
{
if (isset($_POST['lang'])) {
$language = $_POST['lang'];
if (($langaugeModel = \app\models\Langauge::findOne(['name' => $language])) !== null) {
$varLang = [
'id' => $langaugeModel->id,
'name' => $langaugeModel->name,
'iso1' => $langaugeModel->iso1,
'iso2' => $langaugeModel->iso2
];
$cookies = new Cookie([
'name' => 'lang',
'value' => json_encode($varLang),
]);
yii::$app->getResponse()->getCookies()->add($cookies);
return $this->goBack((!empty(Yii::$app->request->referrer) ? Yii::$app->request->referrer : null));
} else {
throw new NotFoundHttpException('The requested langauge does not exist.');
}
} else {
return $this->goBack((!empty(Yii::$app->request->referrer) ? Yii::$app->request->referrer : null));
}
}
Here what I did was i placed all the language support of site in database and generate necessary cookies variable and placed it on client browser.
Next set up be before request event of your yii2 site in config/web.php file as
'as beforeRequest' => [
'class' => 'app\components\MyBehavior',
],
then create components\Mybehaviou.php file and place this code
namespace app\components;
use yii;
use yii\base\Behavior;
class MyBehavior extends Behavior
{
public function events(){
return [
\yii\web\Application::EVENT_BEFORE_REQUEST => 'myBehavior',
];
}
public function myBehavior(){
if (\yii::$app->getRequest()->getCookies()->has('lang')) {
$langIso = 'sdn';
\yii::$app->language = $langIso;
$langaugeVar = \yii::$app->getRequest()->getCookies()->getValue('lang');
$langauge = json_decode($langaugeVar);
$langIso = $langauge->iso2;
\yii::$app->language = $langIso;
}
}
}
This create your site language which depends on client because it depends on cookies of client.
Then create your search controller according to site language(\yii::$app->language)
for ajax search you can use select2 Widget. you can find demo and configuration on this link

PrestaShop 1.7 Add new resources and class

I created new resources with this code:
class WebserviceRequest extends WebserviceRequestCore {
public static function getResources(){
$resources = parent::getResources();
// if you do not have class for your table
$resources['test'] = array('description' => 'Manage My API', 'specific_management' => true);
$resources['categoryecommerce'] = array('description' => 'o jacie marcin', 'class' => 'CategoryEcommerce');
$mp_resource = Hook::exec('addMobikulResources', array('resources' => $resources), null, true, false);
if (is_array($mp_resource) && count($mp_resource)) {
foreach ($mp_resource as $new_resources) {
if (is_array($new_resources) && count($new_resources)) {
$resources = array_merge($resources, $new_resources);
}
}
}
ksort($resources);
return $resources;
}
}
And new class:
class CategoryEcommerceCore extends ObjectModelCore {
public $category_id;
public $category_core_id;
public static $definition = array(
'table' => "category_ecommerce",
'primary' => 'category_id',
'fields' => array(
'category_core_id' => array('type' => self::TYPE_INT),
)
);
protected $webserviceParameters = array();
}
Webservice is override properly. My class WebserviceRequest is copying to
/override/classes/webservice/WebserviceRequest
but class isn't copying to /override/classes/ when i installing my module.
How to add new resourcess with own logic ? I want to add categories within relation to my table.
Regards
Martin
As soon as there is literally nothing regarding the API except Webkul tutorial... I tried to implement the "Webkul's" tutorial, but also failed. However seems that it's better to use hooks instead of overrides. I used my "reverse engineering skills" to determine the way to create that API, so-o-o-o, BEHOLD! :D
Let's assume you have a custom PrestaShop 1.7 module. Your file is mymodule.php and here are several steps.
This is an install method wich allows you to register the hook within database (you can uninstall and reinstall the module for this method to be executed):
public function install() {
parent::install();
$this->registerHook('addWebserviceResources');
return true;
}
Add the hook listener:
public function hookAddWebserviceResources($resources) {
$added_resources['test'] = [
'description' => 'Test',
'specific_management' => true,
];
return $added_resources;
}
That specific_management option shows you are going to use WebsiteSpecificManagement file instead of database model file.
Create WebsiteSpecificManagement file, called WebsiteSpecificManagementTest (Test - is CamelCased name of your endpoint). You can take the skeleton for this file from /classes/webservice/WebserviceSpecificManagementSearch.php. Remove everything except:
setObjectOutput
setWsObject
getWsObject
getObjectOutput
setUrlSegment
getUrlSegment
getContent (should return $this->output; and nothing more)
manage - you should rewrite it to return/process the data you want.
Add
include_once(_PS_MODULE_DIR_.'YOURMODULENAME/classes/WebserviceSpecificManagementTest.php');
to your module file (haven't figured out how to include automatically).
Go to /Backoffice/index.php?controller=AdminWebservice and setup the new "Auth" key for your application, selecting the test endpoint from the permissions list. Remember the key.
Visit /api/test?ws_key=YOUR_KEY_GENERATED_ON_STEP_4 and see the XML response.
Add &output_format=JSON to your URL to see the response in JSON.
You have to use something like $this->output = json_encode(['blah' => 'world']) within manage method at WebsiteSpecificManagementTest.

Add a language parameter in url in zend framework

I have a site in zend framework . Now I am making site in multiple language. For it I need to modify the url.
For example if sitename is www.example.com then i want to make it like
www.example.com/ch
www.example.com/fr
There can be some work around it that you can ask me to create a folder name ch and put a copy of code inside it. But for it I have to manage multiple folder when updating files on server.
What is the best or correct way to do it ?
My routs code is
public function _initRouter() {
$frontController = Zend_Controller_Front::getInstance();
$router = $frontController->getRouter();
$routes = array(
'page' => new Zend_Controller_Router_Route('page/:slug', array('controller' => 'staticpage', 'action' => 'page', 'slug' => ''))
);
$router->addRoutes($routes);
}
Thanks
You have to add the language as parameter in your route(s). Here is an example: http://devzone.zend.com/1765/chaining-language-with-default-route/
You need a function to get a user choice of a language and a default language used if a user just starts with example.com.
You may want to get the current browser and Language Header from the users HTTP request.
Take a look at Zend_Locale and Zend_Translate.
You can use something like $locale = new Zend_Locale('browser'); to detect the users browser language.
Then look if Zend_Translate or your translation engine has the language available and set it to a cookie or session to store the date.
If the user then navigate to some language change site like example.com/?language=en you may want to set the locale based on the user choice and recheck if available in your translations.
If not, get back to original default language and present an error page or something like that.
If you want to get your Zend_Router urls to be language dependent, which might be a bad choice because of copy paste, backlinks or forum posts of your links, you need to add something before each route.
In my Applications i use something like the following in my main bootstrap.php file. I've cut some parts of to keep it simple.
protected function _initTranslate() {
$session = new Zend_Session_Namespace("globals");
// Get current registry
$registry = Zend_Registry::getInstance();
/**
* Set application wide source string language
* i.e. $this->translate('Hallo ich bin ein deutscher String!');
*/
if(!$session->current_language) {
try {
$locale = new Zend_Locale('browser'); //detect browser language
}
catch (Zend_Locale_Exception $e) {
//FIXME: get from db or application.ini
$locale = new Zend_Locale('en_GB'); //use the default language
}
}
else {
$locale = new Zend_Locale($session->current_language);
}
$translate = new Zend_Translate(
array(
'adapter' => 'array',
'content' => realpath(APPLICATION_PATH . '/../data/i18n/'),
'locale' => $locale,
'scan' => Zend_Translate::LOCALE_DIRECTORY,
'reload' => false,
'disableNotices' => true, //dont get exception if language is not available
'logUntranslated' => false //log untranslated values
)
);
if(!$translate->isAvailable($locale->getLanguage())) {
$locale = new Zend_Locale('en_GB'); //default
}
$translate->setLocale($locale);
$session->current_language = $locale->getLanguage();
//Set validation messages
Zend_Validate_Abstract::setDefaultTranslator($translate);
//Max lenght of Zend_Form Error Messages (truncated with ... ending)
Zend_Validate::setMessageLength(100);
//Zend_Form Validation messages get translated into the user language
Zend_Form::setDefaultTranslator($translate);
/**
* Both of these registry keys are magical and makes do automagical things.
*/
$registry->set('Zend_Locale', $locale);
$registry->set('Zend_Translate', $translate);
return $translate;
}
This is for the default translation setup of each visitor.
To set a user language depending on some HTTP parameters, I decided to create a Plugin, which will run on each request, see if the global language parameter is set (key=_language) and try setting the new language.
I then redirect the user to the new route, depending on his choice.
So, if the user click on the link for english language (example.com/de/test/123?_language=en) he will get redirected to example.com/en/test/123.
class Application_Plugin_Translate extends Core_Controller_Plugin_Abstract {
public function preDispatch(Zend_Controller_Request_Abstract $request) {
$frontController = Zend_Controller_Front::getInstance();
// Get the registry object (global vars)
$registry = Zend_Registry::getInstance();
// Get our translate object from registry (set in bootstrap)
$translate = $registry->get('Zend_Translate');
// Get our locale object from registry (set in bootstrap)
$locale = $registry->get('Zend_Locale');
// Create Session block and save the current_language
$session = new Zend_Session_Namespace('globals');
//get the current language param from request object ($_REQUEST)
$language = $request->getParam('_language',$session->current_language);
// see if a language file is available for translate (scan auto)
if($translate->isAvailable($language)) {
//update global locale
$locale = $registry->get('Zend_Locale');
$locale->setLocale($language);
$registry->set('Zend_Locale', $locale);
//update global translate
$translate = $registry->get('Zend_Translate');
$translate->setLocale($locale);
$registry->set('Zend_Translate', $translate);
//language changed
if($language!=$session->current_language) {
//update session
$session->current_language = $language;
$redirector = new Zend_Controller_Action_Helper_Redirector;
$redirector->gotoRouteAndExit(array());
}
}
else {
$request->setParam('_language', '');
unset($session->current_language);
$redirector = new Zend_Controller_Action_Helper_Redirector;
$redirector->gotoRouteAndExit(array());
}
}
}
And finally, to prepare your router with the new language routes, you need to setup a base language route and chain your other language depending routes.
public function _initRouter() {
$frontController = Zend_Controller_Front::getInstance();
$router = $frontController->getRouter();
$languageRoute = new Zend_Controller_Router_Route(
':language',
array(
'language' => "de"
),
array('language' => '[a-z]{2}')
);
$defaultRoute = new Zend_Controller_Router_Route(
':#controller/:#action/*',
array(
'module' => 'default',
'controller' => 'index',
'action' => 'index'
)
);
$router->addRoute(
'default',
$defaultRoute
);
$languageDefaultRoute = $languageRoute->chain($defaultRoute);
$router->addRoute(
'language',
$languageDefaultRoute
);
}
Good luck with your project, hope it will help you and others!

PHP ZF2 translator language switch

Using Zend Framework 2 and Zend\I18n\Translator\Translator, I would like to define the language of the translation dynamically in the same action.
Why ? I need to send email to every customers where the content translation language depends of the language defined in the customer profile. This will be executed by a CRON.
I tried this code for example :
/** #var \Zend\I18n\Translator\Translator $translator */
$translator = $this->getServiceLocator()->get('translator');
$translator->setLocale('fr_FR');
AbstractValidator::setDefaultTranslator($translator);
/** #var \Zend\View\Renderer\PhpRenderer $renderer */
$renderer = $this->getServiceLocator()->get('Zend\View\Renderer\PhpRenderer');
$view = new ViewModel();
$view->setTemplate('templatename')->setVariables($data);
var_dump($renderer->render($view));
/** #var \Zend\I18n\Translator\Translator $translator */
$translator = $this->getServiceLocator()->get('translator');
$translator->setLocale('en_EN');
AbstractValidator::setDefaultTranslator($translator);
/** #var \Zend\View\Renderer\PhpRenderer $renderer */
$renderer = $this->getServiceLocator()->get('Zend\View\Renderer\PhpRenderer');
$view = new ViewModel();
$view->setTemplate('templatename')->setVariables($data);
var_dump($renderer->render($view));
But both var_dump show the same content in the same language (in this case fr_FR).
Any idea ?
the problem with that is the dependency injection in zf2. in normal cases you define/init your locale in an zf2 event at the beginning of a dispatch event on every request over the module.php and onBootstrap method.
after the module initiation the Zend\View\HelperPluginManager class are loaded through the ServiceManager and inject into every ViewHelper ($this->translate is a ViewHelper too) instance the translator in the following order.
has the ServiceManager a MvcTranslator instance inject into viewhelper
has the ServiceManager a Zend\I18n\Translator\TranslatorInterface inject into viewhelper
has the ServiceManager a Translator inject into viewhelper
you change the last instance Translator but the viewhelper has a instance of the MvcTranslator
use
$translator = $this->getServiceLocator()->get('MvcTranslator');
and every viewhelper calling internal getTranslator getLocale return the new locale and use it to translate the given string from $this->translate('someString');
I haven't done this yet with zend framework 2 but i found a tutorial that should help you with what you want to achieve.
tutorial
update:
Okay i did not understand correctly. Nonetheless i tried what you are doing and i get the current locale to be en_EN
$translator = $this->getServiceLocator()->get('translator');
$translator->setLocale('fr_FR');
$translator->setLocale('en_EN');
echo $translator->getLocale();die;
so could it be failing to load the English translation and gets the fallback locale(assuming fr_FR) ?
Update 2.
I wanted to try and work something on this since i will soon need it so i tried to create a small test in order to help you with your problem and also learn something about it. But my approach is somewhat different that yours. I hope i understood correctly what you are trying to do.
Controller:
$translator = $this->getServiceLocator()->get('translator');
$translator->setLocale('fr_FR');
$locale = $translator->getLocale('fr_FR');
$textDomain = 'Users\Controller';
$view = new ViewModel(array(
'locale' => $locale,
'textDomain' => $textDomain,
'translator' => $translator,
));
return $view;
View:
<?php echo $translator->translate('Home', $textDomain, $locale); ?>
module.config.php:
'translator' => array(
'locale' => 'en_US',
'translation_file_patterns' => array(
array(
'type' => 'gettext',
'base_dir' => __DIR__ . '/../language',
'pattern' => '%s.mo',
'text_domain' => __NAMESPACE__,
),
),
),
From the instructions i was reading it was stated that text_domain should be unique so i am using NAMESPACE but i am hard coding that in my controller example above because the test was done on a different namespace so ignore the part just keep in mind that you need it.
So from what i was testing i was able to use the locale i set and translate the word HOME to Accueil. Is this what you where looking for?

ding integration with zend framework

We're using ZendFramework at my workplace for our webapps. It's ok, but it lacks some of the best modern practices (like dependency injection and inversion of control, aop, etc).
For a couple of months, I've been (on my own) using Ding framework as a container for DI and AOP as a test drive. I really like it, so I'd like to bring it into our projects.
But how? So there's the question: how to properly integrate Ding in Zend Framework applications? considering ZF controllers cant be beans (as they are instantiated right from the dispatcher), how to propertly inject all dependencies in them?
P.s: Not using Zend Framework is not an option (at least in the middle term).
P.P.S: Anyone care to add "ding" as a new tag?
I'm glad Ding is helping you.
I contributed on this project and also needed to integrate with a Zend Framework application. I used Zend's application resources and plugin system to achieve this.
An application resource (you can reuse among projects)
<?php
class Application_Resource_Ding extends Zend_Application_Resource_ResourceAbstract
{
protected $_options = array(
'factory' => array(
'bdef' => array(
'xml' => array(
'filename' => array('beans.xml')
),
),
),
'cache' => array(
'proxy' => array('impl' => 'dummy'),
'bdef' => array('impl' => 'dummy'),
'beans' => array('impl' => 'dummy')
)
);
public function init()
{
// set default config dir before mergin options (cant be set statically)
$this->_options['factory']['bdef']['xml']['directories'] = array(APPLICATION_PATH .'/configs');
$options = $this->getOptions();
// parse factory properties (if set)
if (isset($options['factory']['properties'])) {
$options['factory']['properties'] = parse_ini_file(
$options['factory']['properties']
);
}
// change log4php_properties for log4php.properties (if exists)
if (isset($options['log4php_properties'])) {
$options['log4php.properties'] = $options['log4php_properties'];
unset($options['log4php_properties']);
}
$properties = array(
'ding' => $options
);
return Ding\Container\Impl\ContainerImpl::getInstance($properties);
}
}
An action helper to use inside the controllers:
<?php
class Application_Action_Helper_Ding extends Zend_Controller_Action_Helper_Abstract
{
protected $ding = null;
public function init()
{
// just once...
if (null !== $this->ding) {
return;
}
// get ding bootstrapped resource
$bootstrap = $this->getActionController()->getInvokeArg('bootstrap');
$ding = $bootstrap->getResource('ding');
if (!$ding) {
throw new Zend_Controller_Action_Exception(
'Ding resource not bootstrapped'
);
}
$this->ding = $ding;
}
public function getBean($bean)
{
return $this->ding->getBean($bean);
}
public function direct($bean)
{
return $this->getBean($bean);
}
}
In your application.ini you should add something like this (plus any extra configuration you need)
resources.frontController.actionHelperPaths.Application_Action_Helper = "Application/Action/Helper"
resources.ding.factory.properties = APPLICATION_PATH "/configs/ding.properties"
resources.ding.log4php_properties = APPLICATION_PATH "/configs/log4php.properties"
And then in your controllers, to request a bean:
$service = $this->_helper->ding('someService');
Hope this helps!

Categories