in my typo3 extension I want to add a second backend modul in navigation.
in ext_tables.php I have this:
if (TYPO3_MODE === 'BE') {
/**
* Creates a Backend Module Category
*/
$modulName = 'InstitutsShop';
//Legt die Position des Moduls fest, hier nach Modul "web"
if (!isset($TBE_MODULES[$modulName])) {
$temp_TBE_MODULES = array();
foreach ($TBE_MODULES as $key => $val) {
if ($key == 'web') {
$temp_TBE_MODULES[$key] = $val;
$temp_TBE_MODULES[$modulName] = '';
} else {
$temp_TBE_MODULES[$key] = $val;
}
}
$TBE_MODULES = $temp_TBE_MODULES;
}
// Hauptmodul erstellen
t3lib_extMgm::addModule($modulName, '', '', t3lib_extMgm::extPath($_EXTKEY) . 'Configuration/BackendModule/');
/**
* Registers a Backend Module
*/
\TYPO3\CMS\Extbase\Utility\ExtensionUtility::registerModule(
'TYPO3.' . $_EXTKEY, // $extensionName => vendor + extkey, seperated by a dot
'InstitutsShop', // $mainModuleName => Make module a submodule of 'Auditgarant'
'shopbackend', // $subModuleName => module name
'', // $position => position in the group
array( // Allowed controller -> action combinations
'ShopBackend' => 'list, showOrder',
),
array( // $moduleConfiguratione
'access' => 'user,group',
'icon' => 'EXT:' . $_EXTKEY . '/ext_icon_small.svg',
'labels' => 'LLL:EXT:' . $_EXTKEY . '/Resources/Private/Language/locallang_shop_backend.xlf',
)
);
/**
* Registers a Backend Module
*/
\TYPO3\CMS\Extbase\Utility\ExtensionUtility::registerModule(
'TYPO3.' . $_EXTKEY, // $extensionName => vendor + extkey, seperated by a dot
'InstitutsShop Produkte', // $mainModuleName => Make module a submodule of 'Auditgarant'
'shopbackendproducts', // $subModuleName => module name
'', // $position => position in the group
array( // Allowed controller -> action combinations
'ShopOrdProduct' => 'list',
),
array( // $moduleConfiguratione
'access' => 'user,group',
'icon' => 'EXT:' . $_EXTKEY . '/ext_icon_small.svg',
'labels' => 'LLL:EXT:' . $_EXTKEY . '/Resources/Private/Language/locallang_shop_backend.xlf',
)
);
}
The first one with controller ShopBackend is displayed ...
The second one not.
What could be the issue in this case?
Thanks in advance.
I'd say that the space is not allowed in the mainModuleName. And I don't think that your extension has the vendor TYPO3.
Related
Trying to load post ID (and then some ACF field) of the post, where the form is currently embedded. Using get_the_id() or global $post w/ $post->ID returns NULL.
Loading post ID works correctly when using the other Gravity Forms filters (e.g. gform_admin_pre_render), but I was told using the gform_form_post_get_meta is the better way to do ths. What is the right approach for this?
add_filter( 'gform_form_post_get_meta' , 'my_populate_cpt_as_choices' );
function my_populate_cpt_as_choices( $form ) {
$current_post_id = get_the_id();
$postargs = array(
'post_type' => 'suhlasy',
'post_status' => 'publish',
'posts_per_page' => '-1',
);
$posts = get_posts( $postargs );
$input_id = 1; // this makes sure the checkbox labels and inputs correspond
foreach ( $posts as $post ) {
//skipping index that are multiples of 10 (multiples of 10 create problems as the input IDs)
if ( $input_id % 10 == 0 ) {
$input_id++;
}
$post_id = $post->ID;
$id_souhlasu = 1200 + $input_id;
$title = get_the_title($post_id);
$checkbox_text = get_field('checkbox_text', $post_id);
$text_suhlasu = get_field('text_suhlasu', $post_id);
$kategoria = get_field('kategoria_suhlas', $post_id);
// getting other fields for this post to display as values or checkbox labels
$nazev_souhlasu = GF_Fields::create( array(
'type' => 'consent',
'id' => $id_souhlasu, // The Field ID must be unique on the form
'formId' => $form['id'],
'isRequired' => true,
'label' => $title,
'parameterName' => 'my_custom_parameter',
'checkboxLabel' => $checkbox_text,
'description' => '<h2>' . $current_post_id . $post_id . $kategoria . '</h2><br>' . $text_suhlasu,
'pageNumber' => 1, // Ensure this is correct
) );
$form['fields'][] = $nazev_souhlasu;
$input_id++;
}
return $form;
}
I receive an erro of Invalid parameter but it doesnt tell me which invalid parameter is. The error is:
Fatal error: Uncaught exception
'FacebookAds\Http\Exception\AuthorizationException' with message
'Invalid parameter' in
C:\AppServ\www\marketing\vendor\facebook\php-ads-sdk\src\FacebookAds\Http\Exception\RequestException.php:140
Stack trace: #0
C:\AppServ\www\marketing\vendor\facebook\php-ads-sdk\src\FacebookAds\Http\Client.php(215):
FacebookAds\Http\Exception\RequestException::create(Object(FacebookAds\Http\Response))
1 C:\AppServ\www\marketing\vendor\facebook\php-ads-sdk\src\FacebookAds\Http\Request.php(282):
FacebookAds\Http\Client->sendRequest(Object(FacebookAds\Http\Request))
2 C:\AppServ\www\marketing\vendor\facebook\php-ads-sdk\src\FacebookAds\Api.php(151):
FacebookAds\Http\Request->execute() #3
C:\AppServ\www\marketing\vendor\facebook\php-ads-sdk\src\FacebookAds\Api.php(193):
FacebookAds\Api->executeRequest(Object(FacebookAds\Http\Request)) #4
C:\AppServ\www\marketing\vendor\facebook\php-ads-sdk\src\FacebookAds\Object\AbstractCrudObject.php(208):
FacebookAds\Api->call('/act_XXXXXXXX...', 'POST', Array) #5 C:\A in
C:\AppServ\www\marketing\vendor\facebook\php-ads-sdk\src\FacebookAds\Http\Exception\RequestException.php
on line 140
This is my code and it seems that the error is in the last object $ad = new Ad, everything is created fine until the Ad, it shows me this error.
<?php
//date_default_timezone_set('America/Lima');
//require_once('vendor/autoload.php');
//$campaign_id = '6053849657204';
// Configurations
$access_token = 'MYTOKEN';
$app_id = 'MYAPPID';
$app_secret = 'MYAPPSECRET';
$account_id = 'act_MYACCOUNT';
define('SDK_DIR', __DIR__ . ''); // Path to the SDK directory
$loader = include SDK_DIR.'/vendor/autoload.php';
date_default_timezone_set('America/Los_Angeles');
// Configurations - End
if(is_null($access_token) || is_null($app_id) || is_null($app_secret)) {
throw new \Exception(
'You must set your access token, app id and app secret before executing'
);
}
if (is_null($account_id)) {
throw new \Exception(
'You must set your account id before executing');
}
use FacebookAds\Api;
Api::init($app_id, $app_secret, $access_token);
/**
* Step 1 Read the AdAccount (optional)
*/
use FacebookAds\Object\AdAccount;
use FacebookAds\Object\Fields\AdAccountFields;
$account = (new AdAccount($account_id))->read(array(
AdAccountFields::ID,
AdAccountFields::NAME,
AdAccountFields::ACCOUNT_STATUS,
));
echo "\nUsing this account: ";
echo $account->id."\n";
// Check the account is active
if($account->{AdAccountFields::ACCOUNT_STATUS} !== 1) {
throw new \Exception(
'This account is not active');
}
/**
* Step 2 Create the Campaign
*/
use FacebookAds\Object\Campaign;
use FacebookAds\Object\Fields\CampaignFields;
use FacebookAds\Object\Values\AdObjectives;
$campaign = new Campaign(null, $account->id);
$campaign->setData(array(
CampaignFields::NAME => 'Noticia 1',
CampaignFields::OBJECTIVE => AdObjectives::LINK_CLICKS,
));
$campaign->validate()->create(array(
Campaign::STATUS_PARAM_NAME => Campaign::STATUS_PAUSED,
));
echo "Campaign ID:" . $campaign->id . "\n";
/**
* Step 3 Search Targeting
*/
use FacebookAds\Object\TargetingSearch;
use FacebookAds\Object\Search\TargetingSearchTypes;
use FacebookAds\Object\TargetingSpecs;
use FacebookAds\Object\Fields\TargetingSpecsFields;
$results = TargetingSearch::search(
$type = TargetingSearchTypes::INTEREST,
$class = null,
$query = 'facebook');
// we'll take the top result for now
$target = (count($results)) ? $results->current() : null;
echo "Using target: ".$target->name."\n";
$targeting = new TargetingSpecs();
$targeting->{TargetingSpecsFields::GEO_LOCATIONS}
= array('countries' => array('PE'));
/*$targeting->{TargetingSpecsFields::INTERESTS} = array(
array(
'id' => $target->id,
'name' => $target->name,
),
);*/
/**
* Step 4 Create the AdSet
*/
use FacebookAds\Object\AdSet;
use FacebookAds\Object\Fields\AdSetFields;
use FacebookAds\Object\Values\OptimizationGoals;
use FacebookAds\Object\Values\BillingEvents;
$adset = new AdSet(null, $account->id);
$adset->setData(array(
AdSetFields::NAME => 'Latam 1',
AdSetFields::CAMPAIGN_ID => $campaign->id,
AdSetFields::DAILY_BUDGET => '150',
AdSetFields::TARGETING => $targeting,
AdSetFields::OPTIMIZATION_GOAL => OptimizationGoals::REACH,
AdSetFields::BILLING_EVENT => BillingEvents::IMPRESSIONS,
AdSetFields::BID_AMOUNT => '1',
AdSetFields::START_TIME =>
(new \DateTime("+1 week"))->format(\DateTime::ISO8601),
AdSetFields::END_TIME =>
(new \DateTime("+2 week"))->format(\DateTime::ISO8601),
));
$adset->validate()->create(array(
AdSet::STATUS_PARAM_NAME => AdSet::STATUS_ACTIVE,
));
echo 'AdSet ID: '. $adset->id . "\n";
/**
* Step 5 Create an AdImage
*/
use FacebookAds\Object\AdImage;
use FacebookAds\Object\Fields\AdImageFields;
$image = new AdImage(null, $account->id);
$image->{AdImageFields::FILENAME}
= dirname(__FILE__).'/image.jpg';
$image->create();
echo 'Image Hash: '.$image->hash . "\n";
/**
* Step 6 Create an AdCreative
*/
use FacebookAds\Object\AdCreative;
use FacebookAds\Object\AdCreativeLinkData;
use FacebookAds\Object\Fields\AdCreativeLinkDataFields;
use FacebookAds\Object\AdCreativeObjectStorySpec;
use FacebookAds\Object\Fields\AdCreativeObjectStorySpecFields;
use FacebookAds\Object\Fields\AdCreativeFields;
$link_data = new AdCreativeLinkData();
$link_data->setData(array(
AdCreativeLinkDataFields::MESSAGE => 'MY DESC',
AdCreativeLinkDataFields::LINK => 'MY WEB',
AdCreativeLinkDataFields::CAPTION => 'My caption',
AdCreativeLinkDataFields::IMAGE_HASH => $image->hash,
));
$object_story_spec = new AdCreativeObjectStorySpec();
$object_story_spec->setData(array(
AdCreativeObjectStorySpecFields::PAGE_ID => 'MY PAGE ID',
AdCreativeObjectStorySpecFields::LINK_DATA => $link_data,
));
$creative = new AdCreative(null, $account->id);
$creative->setData(array(
AdCreativeFields::NAME => 'Sample Creative',
AdCreativeFields::OBJECT_STORY_SPEC => $object_story_spec,
));
$creative->create();
echo 'Creative ID: '.$creative->id . "\n";
/**
* Step 7 Create an Ad
*/
use FacebookAds\Object\Ad;
use FacebookAds\Object\Fields\AdFields;
$datax = array(
AdFields::NAME => 'My Ad',
AdFields::ADSET_ID => $adset->id,
AdFields::CREATIVE => array(
'creative_id' => $creative->id,
),
);
$ad = new Ad(null, $account->id);
$ad->setData($datax);
$ad->create(array(
Ad::STATUS_PARAM_NAME => Ad::STATUS_PAUSED,
));
echo 'Ad ID:' . $ad->id . "\n";
The issue was that you needed to specify a valid Link and Page ID. I figured that out by adding more logging in the code below by adding this piece of code,
use FacebookAds\Logger\CurlLogger;
Api::init($app_id, $app_secret, $access_token);
// Create the CurlLogger
$logger = new CurlLogger();
// To write to a file pass in a file handler
// $logger = new CurlLogger(fopen('test','w'));
// Attach the logger to the Api instance
Api::instance()->setLogger($logger);
Once you've added the above code to your php project, it will console output the curl version of the API calls being executed by the SDK. You can make the API call that was failing in a terminal using curl and get the specific error that the API throws for debugging. (Currently in the PHP SDK the exact error doesn't get propagated up in the exceptions.)
You can check out the complete working code snippet here,
<?php
$access_token = '<ACCESS_TOKEN>';
$app_id = <APP_ID>;
$app_secret = '<APP_SECRET>';
// should begin with "act_" (eg: $account_id = 'act_1234567890';)
$account_id = 'act_<ACCOUNT_ID>';
$page_id = 0; // REPLACE THIS WITH VALID PAGE ID.
// Configurations - End
if (is_null($access_token) || is_null($app_id) || is_null($app_secret)) {
throw new \Exception(
'You must set your access token, app id and app secret before executing'
);
}
if (is_null($account_id)) {
throw new \Exception(
'You must set your account id before executing');
}
define('SDK_DIR', __DIR__ . '/..'); // Path to the SDK directory
$loader = include SDK_DIR.'/vendor/autoload.php';
use FacebookAds\Api;
use FacebookAds\Logger\CurlLogger;
Api::init($app_id, $app_secret, $access_token);
// Create the CurlLogger
$logger = new CurlLogger();
// To write to a file pass in a file handler
// $logger = new CurlLogger(fopen('test','w'));
// Attach the logger to the Api instance
Api::instance()->setLogger($logger);
/**
* Step 1 Read the AdAccount (optional)
*/
use FacebookAds\Object\AdAccount;
use FacebookAds\Object\Fields\AdAccountFields;
$account = (new AdAccount($account_id))->read(array(
AdAccountFields::ID,
AdAccountFields::NAME,
AdAccountFields::ACCOUNT_STATUS,
));
echo "\nUsing this account: ";
echo $account->id."\n";
// Check the account is active
if($account->{AdAccountFields::ACCOUNT_STATUS} !== 1) {
throw new \Exception(
'This account is not active');
}
/**
* Step 2 Create the Campaign
*/
use FacebookAds\Object\Campaign;
use FacebookAds\Object\Fields\CampaignFields;
use FacebookAds\Object\Values\AdObjectives;
$campaign = new Campaign(null, $account->id);
$campaign->setData(array(
CampaignFields::NAME => 'Noticia 1',
CampaignFields::OBJECTIVE => AdObjectives::LINK_CLICKS,
));
$campaign->validate()->create(array(
Campaign::STATUS_PARAM_NAME => Campaign::STATUS_PAUSED,
));
echo "Campaign ID:" . $campaign->id . "\n";
/**
* Step 3 Search Targeting
*/
use FacebookAds\Object\TargetingSearch;
use FacebookAds\Object\Search\TargetingSearchTypes;
use FacebookAds\Object\TargetingSpecs;
use FacebookAds\Object\Fields\TargetingSpecsFields;
$results = TargetingSearch::search(
$type = TargetingSearchTypes::INTEREST,
$class = null,
$query = 'facebook');
// we'll take the top result for now
$target = (count($results)) ? $results->current() : null;
echo "Using target: ".$target->name."\n";
$targeting = new TargetingSpecs();
$targeting->{TargetingSpecsFields::GEO_LOCATIONS}
= array('countries' => array('PE'));
/*$targeting->{TargetingSpecsFields::INTERESTS} = array(
array(
'id' => $target->id,
'name' => $target->name,
),
);*/
/**
* Step 4 Create the AdSet
*/
use FacebookAds\Object\AdSet;
use FacebookAds\Object\Fields\AdSetFields;
use FacebookAds\Object\Values\OptimizationGoals;
use FacebookAds\Object\Values\BillingEvents;
$adset = new AdSet(null, $account->id);
$adset->setData(array(
AdSetFields::NAME => 'Latam 1',
AdSetFields::CAMPAIGN_ID => $campaign->id,
AdSetFields::DAILY_BUDGET => '150',
AdSetFields::TARGETING => $targeting,
AdSetFields::OPTIMIZATION_GOAL => OptimizationGoals::REACH,
AdSetFields::BILLING_EVENT => BillingEvents::IMPRESSIONS,
AdSetFields::BID_AMOUNT => '1',
AdSetFields::START_TIME =>
(new \DateTime("+1 week"))->format(\DateTime::ISO8601),
AdSetFields::END_TIME =>
(new \DateTime("+2 week"))->format(\DateTime::ISO8601),
));
$adset->validate()->create(array(
AdSet::STATUS_PARAM_NAME => AdSet::STATUS_ACTIVE,
));
echo 'AdSet ID: '. $adset->id . "\n";
/**
* Step 5 Create an AdImage
*/
use FacebookAds\Object\AdImage;
use FacebookAds\Object\Fields\AdImageFields;
$image = new AdImage(null, $account->id);
$image->{AdImageFields::FILENAME}
= dirname(__FILE__).'/image.jpg';
$image->create();
echo 'Image Hash: '.$image->hash . "\n";
/**
* Step 6 Create an AdCreative
*/
use FacebookAds\Object\AdCreative;
use FacebookAds\Object\AdCreativeLinkData;
use FacebookAds\Object\Fields\AdCreativeLinkDataFields;
use FacebookAds\Object\AdCreativeObjectStorySpec;
use FacebookAds\Object\Fields\AdCreativeObjectStorySpecFields;
use FacebookAds\Object\Fields\AdCreativeFields;
$link_data = new AdCreativeLinkData();
$link_data->setData(array(
AdCreativeLinkDataFields::MESSAGE => 'MY DESC',
AdCreativeLinkDataFields::LINK => 'www.google.com',
AdCreativeLinkDataFields::CAPTION => 'My caption',
AdCreativeLinkDataFields::IMAGE_HASH => $image->hash,
));
$object_story_spec = new AdCreativeObjectStorySpec();
$object_story_spec->setData(array(
AdCreativeObjectStorySpecFields::PAGE_ID => $page_id,
AdCreativeObjectStorySpecFields::LINK_DATA => $link_data,
));
$creative = new AdCreative(null, $account->id);
$creative->setData(array(
AdCreativeFields::NAME => 'Sample Creative',
AdCreativeFields::OBJECT_STORY_SPEC => $object_story_spec,
));
$creative->create();
echo 'Creative ID: '.$creative->id . "\n";
/**
* Step 7 Create an Ad
*/
use FacebookAds\Object\Ad;
use FacebookAds\Object\Fields\AdFields;
$datax = array(
AdFields::NAME => 'My Ad',
AdFields::ADSET_ID => $adset->id,
AdFields::CREATIVE => array(
'creative_id' => $creative->id,
),
);
$ad = new Ad(null, $account->id);
$ad->setData($datax);
$ad->create(array(
Ad::STATUS_PARAM_NAME => Ad::STATUS_PAUSED,
));
echo 'Ad ID:' . $ad->id . "\n";
I'm can't get to work image preview on Drupal 7 Form managed file.
I have for code like this in template.php:
function testform($form, &$form_state) {
$form = array();
$form['con_image'] = array(
'#type' => 'managed_file',
'#title' => t('Image'),
'#required' => TRUE,
'#default_value' => variable_get('con_image', ''),
'#progress_indicator' => 'bar',
'#progress_message' => 'Uploading ...',
'#upload_location' => 'public://gallery/',
'#theme' => 'test',
'#upload_validators' => array(
'file_validate_is_image' => array(),
'file_validate_extensions' => array('jpg jpeg'),
'file_validate_image_resolution' => array('6000x4000','800x600'),
'file_validate_size' => array(6 * 1024 * 1024),
),
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Add to site'),
);
return $form;
}
I call testform after checking additional conditions (like userpoints) via code
$arr = drupal_get_form('testform');
print drupal_render($arr);
The form itself is working, I'm able to add image to node (programmatically) but cannot get the preview of image during upload process. I try to use #theme but it seems doesn't work at all.
My theme function looks like this:
function theme_test($variables) {
$element = $variables['element'];
$output = '';
$base = drupal_render_children($element); // renders element as usual
if($element['fid']['#value'] != 0) {
// if image is uploaded show its thumbnail to the output HTML
$output .= '<div class="multifield-thumbnail">';
$output .= theme('image_style', array('style_name' => 'thumbnail', 'path' => file_load($element['fid']['#value'])->uri, 'getsize' => FALSE));
$output .= '</div>';
}
Any ideas?
You need to declare your theme with a hook_theme in your module.
function yourmodule_theme() {
return array(
'test' => array(
'render element' => 'element',
)
);
}
Hello everyone please someone help me how to create a global variable in zend framework 2 to be use in table prefix that are accessible in controller and model.
Thanks and regards to all.
In your config/database.local.php you can define which you want globally
<?
return array(
'service_manager' => array(
'factories' => array(
//'Zend\Db\Adapter\Adapter' => 'Zend\Db\Adapter\AdapterServiceFactory',
'Zend\Db\Adapter\Adapter' => function ($serviceManager) {
$adapterFactory = new Zend\Db\Adapter\AdapterServiceFactory();
$adapter = $adapterFactory->createService($serviceManager);
\Zend\Db\TableGateway\Feature\GlobalAdapterFeature::setStaticAdapter($adapter);
return $adapter;
}
),
),
'db' => array(
'driver' => 'pdo',
'dsn' => 'mysql:dbname=testdb;host=localhost',
'username' => 'root',
'password' => '',
),
'msg' => array(
'add' => 'Data Inserted Successfully',
'edit' => 'Data Updated Successfully',
'delete' => 'Data Deleted Successfully',
),
);
?>
Controller File:
DemoController.php
<?php
namespace Demo\Controller;
use Zend\Mvc\Controller\AbstractActionController;
class DemoController extends AbstractActionController
{
public function indexAction($cms_page_name='whyus')
{
/*Call config file to fetch current cms page id-- fetch config file from database.local.php*/
$config = $this->getServiceLocator()->get('Config');
$all_msg = $config['msg'];
}
}
?>
I have to change the locale dynamically depending which language the user wants.
I can set the locale in the Application/Module.php like this :
public function onBootstrap(MvcEvent $e)
{
$translator = $e->getApplication()->getServiceManager()->get('translator');
$translator->setLocale('hu_HU');
}
But, how can I do this in the controller, if I want to change languages ? I tried this, but after this I can change the locale only for this one request and not global.
$translator = $this->getServiceLocator()->get('translator');
$translator->setLocale('srb_SRB');
Set up the default locale at configuration level! See #61 of module.config.php from ZendSkeletonApplications Application Module
'translator' => array(
'locale' => 'en_US',
)
I had the same issue. In my user login module, I registered for MvcEvent on bootstrap:
use Zend\Mvc\MvcEvent;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\Session\SessionManager;
use Zend\Session\Container as SessionContainer;
use \Zend\I18n\Translator\TranslatorInterface;
...
public function onBootstrap(MvcEvent $event)
{
// Get event manager.
$eventManager = $event->getApplication()->getEventManager();
$sharedEventManager = $eventManager->getSharedManager();
// Register the event listener method.
$sharedEventManager->attach(AbstractActionController::class,
MvcEvent::EVENT_DISPATCH, [$this, 'onDispatch'], 100);
}
Then when that event comes, I set the locale based on info from the URL:
public function onDispatch(MvcEvent $event)
{
$servicemanager = $event->getApplication()->getServiceManager();
$lang = $event->getRouteMatch()->getParam('lang','jp-JP');
$translator = $servicemanager->get(TranslatorInterface::class);
if( $translator != null )
{
$translator->setLocale($lang);
}
...
In the end, this does not really make the locale global - instead, it just sets it for every request. The net effect is the same, from the code point of view - i.e., I don't have to set the locale on every controller.
Hope that helps.
This work for me:
public function onBootstrap(MvcEvent $e)
{
$localeFromHttp = \Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']);
if (false === stripos($localeFromHttp, '-')) {
$locale = $localeFromHttp . '_' . strtoupper($localeFromHttp);
$e->getApplication()
->getServiceManager()
->get('MvcTranslator')
->setLocale($locale);
}
else {
$e->getApplication()->getServiceManager()->get('MvcTranslator')->setFallbackLocale('en_US');
}
}
And my modal.config.php:
'service_manager' => array(
'abstract_factories' => array(
'Zend\Cache\Service\StorageCacheAbstractServiceFactory',
'Zend\Log\LoggerAbstractServiceFactory',
),
'aliases' => array(
'translator' => 'MvcTranslator',
),
),
'service_manager' => array(
'factories' => array(
'translator' => 'Zend\I18n\Translator\TranslatorServiceFactory',
),
),
'translator' => array(
'translation_file_patterns' => array(
array(
'type' => 'gettext',
'base_dir' => __DIR__ . '/../language',
'pattern' => '%s.mo',
'text_domain' => __NAMESPACE__,
),
),
),
In the modal.config file, I do not think that the following is required as you have used the alias 'MvcTranslator' for translator.
'service_manager' => array(
'factories' => array(
'translator' => 'Zend\I18n\Translator\TranslatorServiceFactory',
),
In ZF2 locale is set always per request. You can do that on bootstrap:
$translator = $event->getApplication()->getServiceManager()->get('translator');
$translator->setLocale($locale);
$translator->addTranslationFile(
'phpArray', DATA_PATH . DIRECTORY_SEPARATOR . 'languages' . DIRECTORY_SEPARATOR . $locale . '.php', 'default', $locale
);
and later in controller, if You want to change:
$translator = $this->getServicelocator()->get('translator');
$translator->setLocale($locale);
if You change selected locale, You have to add translation file path again to make it works