Zend Framework 2 invalidate translator cache - zend-framework

I have this code:
'translator' => array(
...
'cache' => array(
'adapter' => array(
'name' => 'Filesystem',
'options' => array(
'cache_dir' => __DIR__ . '/../../../data/cache',
'ttl' => '3600'
)
),
'plugins' => array(
array(
'name' => 'serializer',
'options' => array()
),
'exception_handler' => array(
'throw_exceptions' => true
)
)
)
The question is, how do I invalidate it not by TTL?
For example, I KNOW when the translation was changed so I want to invalidate in on demand but I have not found a way to do it.

The translator component does not utilize the TaggableInterface so you have to know the cacheId which the translator generates to clear the item from you storage adapter. You can use the following code to simply generate the same id and remove the item. Call this from your service or some event listener.
$translator = $sm->get('McvTranslator');
$textDomain = 'default';
$locale = 'en';
$cacheId = 'Zend_I18n_Translator_Messages_' . md5($textDomain . $locale);
$translator->getCache()->removeItem($cacheId);

I think you could set Ttl = 0 (always), and when the cache (file) is not valid anymore -- delete it.

Another way to do it:
Find a point in your code where you call addTranslation.
For example:
$translate = Zend_Registry::get('Zend_Translate');
$translate->addTranslation(array(
'content' => "$dir/$locale.mo",
'locale' => $locale
));
Change the addTranslation function to add reload => true , like this:
$translate->addTranslation(array(
'content' => "$dir/$locale.mo",
'locale' => $locale,
'reload' => true
));
Refresh your page.
Voila.
Remeber to remove reload after that, otherwise you will have no cache.

Related

Zend framework 2 form element normalization

I am migrating an application from Zend 1 to Zend 2 and starting to desperate with one issue. The application works with different locales and therefore, I need to store the data in a normalized way in the database. In Zend 1 I used this code:
public function normalizeNumber( $value )
{
// get the locale to change the date format
$this->_locale = Zend_Registry::get('Zend_Locale' );
return Zend_Locale_Format::getNumber($value, array('precision' => 2, 'locale' => $this->_locale));
}
Unfortunately Zend 2 does not has this Zend_Locale_Format::getNumber any more and I was not able to figure out what function did replace it. I have tried with NumberFormat, but I get only localized data not normalized. I need this function to normalize data I receive from a form via POST. Can someone give some advice?
thanks
Just to complete my question. The Form element definition I am using is the following:
namespace Profile\Form;
use Zend\Form\Form;
use Zend\InputFilter\InputFilterProviderInterface;
class Profile Extends Form implements InputFilterProviderInterface
{
protected $model;
public function __construct( $model, $name = 'assignmentprofile')
{
parent::__construct( $name );
$this->setAttribute( 'method', 'post');
$this->model = $model;
...
$this->add( array(
'name' =>'CommutingRate',
'type' =>'Zend\Form\Element\Text',
'options' => array( // list of options to add to the element
'label' => 'Commuting rate to be charged:',
'pattern' => '/[0-9.,]/',
),
'attributes' => array( // Attributes to be passed to the HTML lement
'type' =>'text',
'required' => 'required',
'placeholder' => '',
),
));
}
public function getInputFilterSpecification()
{
return array(
...
'CommutingRate' => array(
'required' => true,
'filters' => array(
array( 'name' => 'StripTags', ),
array( 'name' => 'StringTrim'),
array( 'name' => 'NumberFormat', 'options' => array('locale' => 'en_US', 'style' => 'NumberFormatter::DECIMAL', 'type' => 'NumberFormatter::TYPE_DOUBLE',
))
),
'validators' => array(
array( 'name' => 'Float',
'options' => array( 'messages' => array('notFloat' => 'A valid numeric entry is required')),
),
),),
...
);
}
}
As mentioned before, I am able to localized the data and validate it in the localized manner, but i am failing to convert it back to a normalized manner...

Prestashop helper form 'file' type

I m working on prestasshop and I created a helper form inside a controller (for back office). My question is how to upload a document by using the type:'file' from the helper form. Here is the code:
public function __construct()
{
$this->context = Context::getContext();
$this->table = 'games';
$this->className = 'Games';
$this->lang = true;
$this->addRowAction('edit');
$this->addRowAction('delete');
$this->bulk_actions = array('delete' => array('text' => $this->l('Delete selected'),
'confirm' => $this->l('Delete selected items?')));
$this->multishop_context = Shop::CONTEXT_ALL;
$this->fieldImageSettings = array(
'name' => 'image',
'dir' => 'games'
);
$this->fields_list = array(
'id_game' => array(
'title' => $this->l('ID'),
'width' => 25
)
);
$this->identifier = 'id_game';
parent::__construct();
}
public function renderForm()
{
if (!($obj = $this->loadObject(true)))
return;
$games_list = Activity::getGamesList();
$this->fields_form = array(
'tinymce' => true,
'legend' => array(
'title' => $this->l('Game'),
'image' => '../img/admin/tab-payment.gif'
),
'input' => array(
array(
'type' => 'select',
'label' => $this->l('Game:'),
'desc' => $this->l('Choose a Game'),
'name' => 'id_games',
'required' => true,
'options' => array(
'query' => $games_list,
'id' => 'id_game',
'name' => 'name'
)
),
array(
'type' => 'text',
'label' => $this->l('Game Title:'),
'name' => 'name',
'size' => 64,
'required' => true,
'lang' => true,
'hint' => $this->l('Invalid characters:').' <>;=#{}'
),
array(
'type' => 'file',
'label' => $this->l('Photo:'),
'name' => 'uploadedfile',
'id' => 'uploadedfile',
'display_image' => false,
'required' => false,
'desc' => $this->l('Upload your document')
)
)
);
$this->fields_form['submit'] = array(
'title' => $this->l(' Save '),
'class' => 'button'
);
return AdminController::renderForm();
}
Now how can I upload the document?
Do I have to create a column in the table of the db (games table) for storing the file or something related?
Thanks in advance
I assume this AdminController for your model. Now a model obviously can't hold a file in table column. What you can do is hold path to the uploaded file. That's what you can save.
You should look in AdminController class (which you extended). When you submit a form, one of two method are executed:
processAdd()
processUpdate()
Now investigate the flow logic in these methods. Other methods are called from within this methods, such as:
$this->beforeAdd($this->object); -> calls $this->_childValidation();
$this->validateRules();
$this->afterUpdate($object);
As you can see, there these are the methods where you can do you custom stuff. If you look up these functions in AdminController class, the're empty. They are purposely added so people can override them and put their custom logic there.
So, using these functions, you can validate your uploaded file fields (even though it isnt in the model itself), if it validates you can then assign path to the object; and then in beforeAdd method you can actually move the uploaded file to the desired location (because both child validation and default validation has passed).
The way I've done it:
protected function _childValidation()
{
// Check upload errors, file type, writing permissions
// Use $this->errors['file'] if there is an error;
protected function beforeAdd($object)
{
// create filename and filepath
// assign these fields to object;
protected function afterAdd($object)
{
// move the file
If you allow the file field to be updated, you'll need to to these steps for Update methods as well.
you can get uploaded file using $_FILES['uploadedfile'] in both the functions processAdd() and processUpdate(), you can check all the conditions there and before calling $this->object->save(); to save the form data you can write the code to upload the file in the desired location like
move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)
since you can't save the file in database you need to save only the name of the file or location on the database
Hope that helps

ZendFramework2 - Literal- or Segment-Routing and Parameters

I am using ZendFramework 2.x and trying to add a route to some existing ones. Moreover I want to put some parameters in die URL as well. If I use the segment-type for my new route ('showroom') I am able to call my new URL and will get forwarded to the corresponding view. Unfortunately I am not able to set some parameters in the URL. The other option is to use segment type in my module.config.php-file, but I will get some ZF-2-Exception, that my route is not configured correctly, this happens even before rendering my intro-view. Thanks in advance for showing me, how to combine segment and literal-type usage in route-child-route-combination or for telling me how to add parameters to literal type URLs.
Route-configuration in module.config.php of Module:
'router' => array(
'routes' => array(
'zfcuser' => array(
'type' => 'Literal',
'priority' => 1000,
'options' => array(
'route' => '/user',
'defaults' => array(
'controller' => 'zfcuser',
'action' => 'index',
),
),
'may_terminate' => true,
'child_routes' => array(
'showroom' => array(
'type' => 'Segment',
'options' => array(
'route' => '/:id',
'defaults' => array(
'controller' => 'zfcuser',
'action' => 'showRoom',
'id' => '1',
),
),
),
'login' => array(
'type' => 'Literal',
UPDATE: snippet which triggers the error (see comments)
<?php
$roomIndex = 1;
foreach($roomsPaginator->getCurrentItems() as $room){
$roomURL = 'zfcuser/showroom' . '/' . $roomIndex;
echo "<p>Name: " . $room['name'] . "; Luftfeuchtigkeit: " . $room['humidity'] . "; <a class='btn' href='" . $this->url($roomURL) . "'>Betreten »</a></p>";
$roomIndex++;
}
?>
I'm not sure if this is the cause of your error, but I don't think you're using the URL helper correctly. You don't build a URL and pass it to the helper, the idea is the helper builds the URL for you using the route name and params. You probably want something like this:
$roomIndex = 1;
foreach($roomsPaginator->getCurrentItems() as $room){
echo "<p>Name: " . $room['name'] . "; Luftfeuchtigkeit: " . $room['humidity'] . "; <a class='btn' href='" . $this->url('showroom', array('id' => $roomIndex)) . "'>Betreten »</a></p>";
$roomIndex++;
}

a link pass multiple parameter in zend framework

hi i am new in zend framework 2.2.0. i want to create the a link that go to delete page right now i am passing only id in the url so i want to pass another id in it.
Add to Trash
right now in this link message id is passing i also want to pass one more id named "did" in this link
Add to Trash
how can i get this ?
thanks in advance
You should use url view helper's third argument ($options) to pass your variables in the query string. Example:
$route = 'message';
$param = array('action' => 'delete');
$opts = array(
'query' => array(
'id' => $message->message_id,
'did' => $message->deliver_id
)
);
$this->url($route, $params, $opts);
You have to add "did" to your message route like this:
'router' => array(
'routes' => array(
'message' => array(
'type' => 'segment',
'options' => array(
'route' => '/:action/:id[/:did]',
'constraints' => array(
'action' => '[a-zA-Z][a-zA-Z0-9_-]+',
'id' => '[0-9]+',
'did' => '[0-9]+',
),
'defaults' => array(
'controller' => 'Application\Controller\Index',
),
),
),
),
),
echo $this->url('message',array('action'=>'delete', 'id' => $message->message_id,'did'=>$message->deliver_id);
// output: /delete/1/2

Zend Navigation, how can i use it with params in the url ? I tried it with params in navigation without changes :(

I have got a problem with the zend navigation.
I use the zend navigation, and its ok when i call something like this in the url:
www.website/article_new, www.website/article_list,
www.website/friends_new, ...
But I want to call the site with some params like this:
www.website/article_new/123452/2335/45633246,
www.website/friends_new/23453/3453524/34554
I try it about to set some params, but this doesnt function.
I put the navigation in the bootstrap and in the layout I use it. Its a Navigation with some breadcumps where display:true and display:false.
Here is a code from my bootstrap:
$navigation = new Zend_Navigation(array(
array(
'label' => 'Home',
'controller' => 'index',
'action' => 'index',
'class' => 'menuF'
),
array(
'label' => 'Article',
'controller' => 'Article_List',
'id' => 'article',
'action' => 'index',
'class' => 'menu',
'pages' => array(
array(
'label' => 'Neu',
'id' => 'article',
'controller' => 'Article_New',
'action' => 'index',
'class' => 'submenu'
)
)
).....
And the code from the layout.phtml. On this code I show if the breadcump is shown or not.
foreach($container as $page) {
$par = $active;
if ($page != $active && $page->getClass()!='menu' && $page->getClass()!='menuF' && $page->getID()!=$par->getID()) {
$page->setClass('submenu');
} else {
$found = $container->findAllBy('ID', $active->getID());
foreach($found AS $p){
if($p->getClass()!='menu'&&$p->getClass()!='menuF'){
$p->setClass('sub');
}
}
}
}
echo $this->navigation()->menu()->renderMenu($this->nav);
Hope anybody can help me!
Thanks for all!
Best regards
Tom
I found myself the mistake!
I want to call something like this:
www.website/article/344435/23452345
surely this throws a mistake, because there isnt any action like 344435
with something like this
www.website/article/show/var1/2435234/var2/2345234352
its ok.
the rest is something for routing!
Big sorry to all!
Greats Tom
Try to use the route name instead of the module, controler and action system.
array(
'label' => 'Article',
'route' => 'Article_List',
'id' => 'article',
'class' => 'menu',
...
)
The router will handle all the URL parsing and return the correct variables.