How to get an array of values for the router "segment"? - zend-framework2

I use a form with a multiupload. My addAction save information regarding the downloaded files in the database, and obtains an array lastInsrtId() values. If the upload was successful, I need to be redirected to editAction, where a user can see a list of downloaded files and user can edit file attributes such as title, description and alt attribute for images for each downloaded file using this files list. How do I pass an array of values ​​in the route? Here is my code addAction:
// upload success
$fileIds = $this->getContentService()->makeFiles($parent, $data);
return $this->redirect()->toRoute('sc-admin/file/edit', array('ids' => $fileIds));
Here is the definition for a route that should display a list of files for editing:
'edit' => array(
'type' => 'segment',
'options' => array(
'route' => '/edit[/:ids]',
'defaults' => array(
'controller' => 'sc-file',
'action' => 'edit',
),
),
),
But it generates an error for editAction
rawurlencode() expects parameter 1 to be string, array given
I do not want to use the session whenever the parameters necessary to pass an array of values, because it is a matter solely routing.

Ever seen this url?
http://foo.bar/baz?array(1=>2,3=>4)
Probably not. You got an error message so do as the error message says. This has nothing to do with Zend Framework, this is basic PHP (too many people often forget what's the core...).
array('ids' => serialize($data))
See php:serialize() and php:unserialize()

Related

ZF2 - Formatting Routes

I typically format my routes in ZF2 like so: /name/to/route
Now I have been doing the same thing with my api routes however I am finding that I am struggling to include data such as encoded urls or arrays.
Here is an example of such a route:
http://example.com/api/register/access/code/c102dea422fa4bb6958d77a29d9873d2/http%3A%2F%2Frouter-local.example.com%2Fapi%2Fdirectory
The following represents forward slashes and thus causes the route not to work: %3A%2F%2
I am thinking I should encode my route as such:
http://example.com/api/register/access/code/?access_code=c102dea422fa4bb6958d77a29d9873d2&route=http%3A%2F%example.com%2Fapi%2Fdirectory
How do you configure the module.config file to deal with this?
Currently it is set as such in apigility:
'api.rpc.register-access-code' => array(
'type' => 'Segment',
'options' => array(
'route' => '/api/register/access/code/:access_code/:route',
'defaults' => array(
'controller' => 'Api\\V1\\Rpc\\RegisterAccessCode\\Controller',
'action' => 'registerAccessCode',
),
),
),
EDIT
I have encoded my routes to include GET parameters by doing the following:
$url = "http://example.com/api/register/access/code/";
$params = [
'access_code' => 'c102dea422fa4bb6958d77a29d9873d2',
'route' => 'http://example.com/api/directory'
];
$final = $url . "?" . http_build_query($params);
Which gives this:
http://example.com/api/register/access/code/?access_code=c102dea422fa4bb6958d77a29d9873d2&route=http%3A%2F%2Fexample.com%2Fapi%2Fdirectory
However this breaks due to a "The requested URL could not be matched by routing." error.
The route is unidentified due to the interpretation of the slashes in the included URL.
Perhaps the issue is to do with how the URL is formatted and included as a parameter?
You don't define query variables in the segment route option; only the path.
You may append ?query=vars to any url, regardless of route configuration. ZF2's url helpers should encode the query vars for you, you just have to create an array of query vars and give it to the helper function when creating a url.
<?php echo $this->url('api.rpc.register-access-code', array(), array('query' => array(
'access_code' => 'c102dea422fa4bb6958d77a29d9873d2',
'route' => 'http://router-local.example.com/api/directory',
))); ?>`
In this case, it would seem the problem is to do with htaccess or apache. The simplest solution has been to encode the url using: base64_encode($url) which can be de-coded at the other end.

zf2 translate validators messages with variables

I have custom message like this:
'options' => array(
'min' => $min,
'max' => $date->format('Y-m-d'),
'inclusive' => true,
'messages' => array(
Between::NOT_BETWEEN => "The input is not between '%min%' and '%max%', inclusively",
),
),
I put this string in .po file and generate .mo, but message won't translate. For all other messages without variables it's working fine.
You can read in the ZF2 official documentation on how to do this.
The translation files for validators are located at /resources/languages. You should simply attach a translator to Zend\Validator\AbstractValidator using these resource files or in your case your own file for your custom messages.
$validator->setDefaultTranslator($translator);
EDIT
I misinterpreted your question, here an edit
Can you not translate the message before binding the variables like this:
$translator = ...translator...
'options' => array(
'min' => $min,
'max' => $date->format('Y-m-d'),
'inclusive' => true,
'messages' => array(
Between::NOT_BETWEEN => $translator->translate(
"The input is not between '%min%' and '%max%', inclusively"
),
),
),
It would have been nice, if you had given more explanation.
Generally If string contains variables , You have to replace them with string formatters.
In your case msgid "The input is not between %s and %s"
I hope it should solve your problem.

zf2 website with a single entry-point, no routes/paths in URL

Is it be possible to make a website that doesn't reveal any relative URL's at all?
Say for example, I have a domain name "somedomain.xyz" and I want to route everything through the default route, and I want not to reveal any paths or route structures to the end user.
The end user shall only see the domain name in the browser's address bar, like:
http://somedomain.xyz
or
https://somedomain.xyz.
Any path like
http://somedomain.xyz/index.php
or
http://somedomain.xyz/index or
http://somedomain.xyz/index/index
shall show a 404.
And I don't care about SEO stuff and static pages.
Is that possible with ZF2, and if yes, then how?
similar question: hide module and action name from zf2 routing
Just create a hostname route for subdomain.xyz like so:
'my-route' => array(
'type' => 'Hostname',
'options' => array(
'route' => 'subdomain.xyz',
'defaults' => array(
'controller' => 'MyApp\Controller\TheController',
'action' => 'whatever-action',
),
),
),
see here for a complete solution, with using HTTP POST vars for the routing:
ZF2 routing via post vars

How to put translator in Zend2 form

Iam new guy to Zend framework and currently Iam working on Zend2...I want to ask about Translator usage in Zend forms....If i want to use translator i directly using for labels in form view i.e.form_view.php like
$this->formLabel()->setTranslator($translator, 'date_of_birth');
But I want to add the translator at the form only i.e.in src/my_module/Form/UserForm.php
like
$this->add(array(
'name' => 'date_of_birth',
'attributes' => array(
'type' => 'text',
'id' => 'date_of_birth',
),
'options' => array(
'label' => 'DateOfBirth',
), //Here there is any option to put translator
));
Please help me...any answer would be help for me like I asked
Thanks in advance
You don't really need to do that. Since the the Translator that is set up using the factory-key translator will automatically be injected into the Form.
The best approach (in my opinion) is to make extensive use of the translator text_domain:
'translator' => array(
'locale' => 'de_DE',
'translation_file_patterns' => array(
array(
'type' => 'phparray',
'base_dir' => __DIR__ . '/../language',
'pattern' => '%s.php',
'text_domain' => 'MyModuleTextDomain'
),
),
),
With this setup, the Files of your Module will automatically be inserted into the default TranslatorService which every Zend\Form knows of.
So ultimately all you have to do is make the ViewHelpers know of the TextDomain that you are using. And this is done in the following manner:
$this->formLabel()->setTranslatorTextDomain('MyModuleTextDomain');
$this->formButton()->setTranslatorTextDomain('MyModuleTextDomain');
$this->formElementErrors()->setTranslatorTextDomain('MyModuleTextDomain');
You need to do this once inside your respective view.phtml before(!) using the ViewHelpers like $this->formElement($element) or $this->formCollection($form)
And that's really all there is to it. I recall having seen a discussion somewhere about making it easier to pass along Text-Domain-Data, but i can't find it right now. So things may get a little easier in the future ;) For now, 3 lines are all that's needed though!
above answer is quite unnecessary ... as your translator was added automatically to zend form for rendering form labels and ....
only use this code in your module config :
'translator' => array(
'locale' => 'en_US',
'translation_file_patterns' => array(
array(
'type' => 'phparray',
'base_dir' => __DIR__ . '/../language',
'pattern' => '%s.php',
),
),
),
if u use the correct view helpers for rendering form elements (or whole form) it will automatically translated
This is not a recommended approach because forms are translated automatically if you have a translator configured (which you do if you are using the Skeleton Application). However, since you asked how to use the translator directly within your form, I will show you how you can do it. Please carefully consider if you really want to do this, as I cannot imagine a use case where it would be necessary.
To do exactly what you were asking, you can inject the translator into your form. You can do this either in your controller or in a factory. I will be using a factory in this example because it is more DRY.
// In your module's config file
'service_manager' => array(
'factories' => array(
'YourModule\Form\YourForm' => function($sm) {
$translator = $sm->get('Translator');
return new \YourModule\Form\YourForm($translator);
},
),
),
Then in your form class, you can do like this:
namespace YourModule\Form;
class RegisterForm extends \Zend\Form\Form {
public function __construct($translator) {
// Do something
$translated_string = $translator->translate('string to translate');
}
}
Then in your controller, you can do like this:
$your_form = $this->servicelocator->get('YourModule\Form\YourForm');
Or if you don't want to use the factory, you can choose to not add it and do like this instead:
$your_form = new \YourModule\Form\YourForm($this->servicelocator->get('Translator'));
I would recommend going with the factory, though.

Zend Framework 2 (ZF2) dynamic locale

I am looking for a way to add translations to my ZF2 application, using globals in my URL.
Is there anyway to do this for the whole application at once?
A typpical URL would look like this: http://domain.com/en_GB/user/index
The first part (en_GB) should be used to show the correct translation.
Besides that, it would be nice, if it is possible to set this router part optional.
So, if I should go to http://domain.com/user/index (without the locale part) to my application, it should automatically take the browser locale.
I hope I am clear enough, if any additions are needed to this question, feel free to ask.
Thanx in advance
#DrBeza,
Thank you for your answer. I don't know if this is the correct way, but I created the next solution:
in /config/global.php I added this part
'translator' => array(
'locale' => 'nl_NL',
'translation_file_patterns' => array(
array(
'type' => 'phpArray',
'base_dir' => __DIR__ . '/../../language',
'pattern' => '%s.php',
),
),
),
in /module/[modulename]/config/module.config.php I added this part to set the first part of the URL containing the locale
'router' => array(
'routes' => array(
'user' => array(
'options' => array(
'route' => '[/:lang]/user[/:action][/:id]',
'constraints' => array(
'lang' => '([a-z]{2})+(_)+([A-Z]{2})',
),
),
),
),
),
in /config/local.php I added this code to fetch the locale from the URL:
http://domain.com/[locale][module][controller]
$_SERVER['REQUEST_URI_PATH'] = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$segment = explode('/', $_SERVER['REQUEST_URI_PATH']);
And I added this part to load the locale dynamicly:
return array(
'translator' => array(
'locale' => $segment[1],
);
I would suggest extending the Segment route class and adding in the optional locale constraint and segment part if missing. Call the optional variable something application wide such as 'locale'.
Then create a 'route' event in the main module bootstrap, this event will fire once a route has been matched. The callback function that is fired will have access to the RouteMatch object through the passed event, letting you gain access to the 'locale' value. Then you can do some checks and set the application locale.

Resources