Is it possible to add parameters to response
$response = $this->render('AcmeSiteBundle:Page:home.html.twig', array(
'name' => 'tom',
));
And latter add some more parameters. Something like:
$response->addParameters(array(
'lastname' => 'cruise'
));
...
return $response;
Is there a way that would work?
No, the render method executes the twig templating engine and renders the template, which gets returned as text in a response. The response don't even know that the string was build by twig with some parameters/variables.
What you can do is having a $params variable containing the parameters, add some parameters to that array and use it in the end to generate the template:
$params = array(
'firstname' => 'Joe'
);
// ...
$params['lastname'] = 'Doe';
return $this->render(..., $params);
Related
I have a private function to return an array of options, those options indicate a callback and other options such as template, form, etc. Here the code:
/**
* #return array
*/
private function options()
{
$options = [
'general' => [
'form' => GeneralConfigType::class,
'template' => 'general.html.twig',
'title' => 'Configuración General',
'ignoreFields' => ['slider', 'social'],
'uploadedFields' => [],
'callbacks' => ['generalData']
],
'business' => [
'form' => ConfigurationType::class,
'template' => 'business.html.twig',
'title' => 'Configuración de Empresa',
'ignoreFields' => [],
'uploadedFields' => ['image','favicon','login_icon','sidebar_icon'],
'callbacks' => ['businessImage']
],
];
return $options;
}
Now here is my doubt, in addition to indicate the function you have to execute in the key callback, Can I pass on the variables I'm going to need in that callback? I've tried several ways and they haven't worked.
Example:
Before:
'callbacks' => ['generalData']
After:
In this example I'm assigning the '$', but I could do it if the only string, I'm just looking for a way to pass to the callback the variables it needs and no more.
'callbacks' => ['generalData' => '$configurationData, $configuration, $form, $request']
And this code would be where everything would be executed in other method:
if (!empty($options[ 'callbacks' ])) {
foreach ($options[ 'callbacks' ] as $callback => $variables) {
$this->$callback($variables);
}
}
If I understand you correctly, you want to store the name of the variable in the array of options and then use that variable in the callback function.
When I've done this type of thing, I find it easier to just store the variable name as text and leave out the $ from the name stored in the array. I then use a variable variable when retrieving it.
Either way, I think you need a little more code on the execution side. One more loop:
if (!empty($options[ 'callbacks' ])) {
foreach ($options[ 'callbacks' ] as $callback => $variables) {
foreach($variables as $variable){ // extra loop to get the variables
$this->$callback[$$variable];
// This is where it gets tricky, and depends on how you wish to format.
// The variables are currently part of an array, thus the array notation
// above. By using the stored name only, and a variable variable, you
// should be able to get to the var you need
}
}
}
#jcarlosweb, what you need to do is very simple. The short answer is that it can be done using the [call_user_func_array()][1] method.
In the context of your example, the callbacks could be rearranges in the following way ...
'callbacks' => ['generalData' => [$configurationData, $configuration, $form, $request]
Basically, the array keys will be the name of the function to call, and the corresponding array values will be a array of the values of each parameter that is accepted but the callback function. Doing it this way is important because you need to capture the value of the parameters while they are in scope. And this will avoid using eval().
Using the callbacks can be as simple as ...
$options = options();
foreach ($options['callbacks'] as $callback => $params) {
$result = call_user_func_array($callback, $params);
// Do something with $result if necessary
}
I finally got it with the function compact http://php.net/manual/en/function.compact.php
Here's the code:
First I select the variables I need in my options:
'callbacks' => ['businessImage' => ['configurationData', 'configuration', 'form', 'request']]
Second I call the variables with compact, but I had to use extract here because if I didn't configurationData variable wasn't modified, which I don't understand since I had previously referenced it.
if (!empty($options[ 'callbacks' ])) {
foreach ($options[ 'callbacks' ] as $callback => $variables) {
$variables = compact($variables);
$this->$callback($variables);
extract($variables);
}
}
Third callback applied and referenced:
/**
* #param array $params
* #return array $configurationData
*/
private function businessImage(&$params)
{
extract($params,EXTR_REFS);
// more code here ......
$configurationData[ "image" ] = $originalImageName;
$configurationData[ "favicon" ] = $originalFaviconName;
$configurationData[ "login_icon" ] = $originalLoginIconName;
$configurationData[ "sidebar_icon" ] = $originalSidebarIconName;
return $configurationData;
}
This works correctly in my website, but as I said before I do not understand why I have to call back the function extract, if I have already passed it referenced in the same callback as you see in my last code.
I am having the hardest time figuring out how to properly format a graphql api mutation POST request in php.
If I hard code the string and use it as the data in my POST request it works like this:
'{"query":"mutation{addPlay(input: {title: \"two\"}){ properties { title } } }"}'
But if I have a php array of the input values:
$test_data = array(
'title' => 'two'
);
I can't seem to format it correctly. json_encode also puts double quotes around the keys which graphql is rejecting with the error Syntax Error GraphQL request (1:26) Expected Name, found String.
I ultimately need a solution that will convert a larger more complex array to something usable.
Reformatting the query allowed me to use JSON directly.
So my new query looks like this:
$test_data = array(
'title' => 'two'
);
$request_data = array(
'query' => 'mutation ($input: PlayInput) { addPlay(input: $input) { properties { title } }}',
'variables' => array(
'input' => $test_data,
),
);
$request_data_json = json_encode($request_data);
Then the $request_data_json is used in a POST http request.
Purpose: to redirect a specific route with an array value. I am not able to use View::make in my situation, which causes problem.
$value = 'Sarah';
$array_param = array(
'1' => 'a',
'2' => 'b'
);
return Redirect::route('myroute', array(
'name' => $value
));
Above is cool. But i cannot use $array_param with redirect route, which expects a string parameter, but i'm sending an array variable. Alternative way?
return Redirect::route('myroute', array(
'name' => $value,
'parameter' => $array_param
));
--update--
Route::post('myroute/{name}/{array_param}', array(
'as' => 'myroute',
'uses' => 'mycontroller#mymethod'
));
What the version of Laravel do you have?
The code below works for me correctly on laravel 5.1. Maybe it'll help you.
public function store(Request $request)
{
$item = Item::find(1); // an example
return redirect()->route('item.show', ['id' => $item->id]);
}
and yes, the redirect to the post route looks very incorrect. Please try to use the redirect only to the GET routes.
I've the page, which loads content by click on the button from user database via jquery ajax.
File, which handles ajax request, has this code:
return $modx->runSnippet('pdoPage',array(
'class' => 'LibraryContent',
'tpl' => 'tpl.lib-main',
'element' => 'Ajax_test'
));
Sender of request receives answer, snippet works ok, I see data, which snippet returns. But, what about placeholders? For example, I want use pagination by this snippet(pdoPage). I cannot send placeholders via ajax, because modx parser have been worked and placeholder will be a plain text. Other path is paste placeholder to resource, which send ajax request, but no way — there is placeholder, but there is no results of pdoPage's work. Finally, placeholder is empty.
So, my question is how to "alive" placeholder for snippet, which loads by ajax request?
thanks.
1'st way:
$output = $modx->runSnippet('pdoPage',array(
'class' => 'LibraryContent',
'tpl' => 'tpl.lib-main',
'element' => 'Ajax_test'
));
$pagination = $modx->getPlaceholder('page.nav');
return $output.$pagination;
2'nd way:
$content = $modx->runSnippet('pdoPage',array(
'class' => 'LibraryContent',
'tpl' => 'tpl.lib-main',
'element' => 'Ajax_test'
));
$pagination = $modx->getPlaceholder('page.nav');
$output = array(
'content' => $content,
'pagination' => $pagination
);
return $modx->toJSON($output);
I have an Action method in Foo Controller which requires parameters:
public function fooAction($one, $two) {
$a = one;
$b = $two;
}
And I need to forward to that method from the other method of some Boo Controller. And one of those parameters has to be by reference parameter. The only example that the manual has is this:
$result = $this->forward()->dispatch('Boo\Controller\Boo', array('action' => 'boo'));
No any additional parameters. But they write:
$params is an optional array of parameters with which to see a
RouteMatch object for purposes of this specific request.
So, I tried:
$result = $this->forward()->dispatch('Boo\Controller\Boo', array(
'action' => 'boo',
'one' => &$one,
'two' => $two,
));
But it doesn't work.
Is there any way to pass additional parameters to forward controller?
UPD:
These do not work too:
$result = $this->forward()->dispatch('Boo\Controller\Boo', array(
'action' => 'boo',
'params' => array(
'one' => &$one,
'two' => $two,
)));
$result = $this->forward()->dispatch('Boo\Controller\Boo', array(
'action' => 'boo',
'options' => array(
'one' => &$one,
'two' => $two,
)));
UPD 2:
I still can't get the functionality I want (to pass parameters with the forward plugin) but I found other solutions. Before calling the forward plugin I set the variables to the Request object and after the forward I get them from the Request in my boo Action of my Boo\Controller\BooController:
// in Foo::fooAction
$this->getRequest()->one = &$one;
$this->getRequest()->two = $two;
$result = $this->forward()->dispatch('Boo\Controller\Boo', array('action' => 'boo'));
// in Boo::booAction
$a = $this->getRequest()->one;
$b = $this->getRequest()->two;
Stupid solution, it will not work with Ajax requests. Still interested how to pass parameters with the forward plugin. OR MAYBE how to get them in the booAction. Because there in no anything in the Request if I pass them with the forward.
UPD 3 and Final:
I finally found where they've decided to hide parameters I pass with the forward plugin. They put them in the RouteMatch object.
- Tryyyy to guess where we've hidden your params... Oh yeeah, they are in the RouteMatch, of course they are there, didn't you think smth else?
And NO ANY info in the forward plugin section of the manual!
To get params, I have to do this in my BooController::booAction:
$param = $this->getEvent()->getRouteMatch()->getParam('nameOfParam');
Why not to use the params plugin?
This works for me:
public function indexAction() {
$object = new SomeObject();
return $this->forward()->dispatch('Application\Controller\Index', [
'action' => 'show',
'myObject' => $object,
]);
}
public function showAction() {
$object = $this->params('myObject');
var_dump($object);
return [];
}
You can create a container class and use it in both controllers
in module.conf
public function getServiceConfig()
{
return array(
'invokables' => array(
'my_handy_container' => 'path\container_class_name',
)
);
}
Create a getter in both controllers:
public function getMyHandyContainer()
{
if (!$this->myHandyContainer) {
$this->myHandyContainer = $this->getServiceLocator()->get('my_handy_container');
}
return $this->myHandyContainer;
}
And call it using:
$myContainer = $this->getMyHandyContainer()->myHandyContainer;
$myContainer->foo = 5; // set something
ZF2 way to pass vars using forward
In the passing method do:
return $this->forward()->dispatch('controller_name', [
'action' => 'whatever',
'varname' => $value,
'varname2' => $value2
]);
In the invoked controller method, do:
$param2 = $this->params()->fromRoute('varname2',false);
Thought I would add another option that works for me.
You can simply pass the params straight through the forward function and use the routeMatch function to access them at the other end.
return $this->forward()
->dispatch('Module\Controller\Foo', array(
'action' => 'bas',
'id' => 6)
);
Passes to Foo Controller, basAction in this method you can then use the following code to access the id param
$myParam = (int) $this->getEvent()->getRouteMatch()->getParam('id');
Not sure if this meets your requirements - but works for me.
Thanks for the question, helped me a lot. Found an easy way for getting all params passed to forward()->dispatch(...). In the controller's action method:
$params = $this->params()->fromRoute();
returns array $data as passed as $data into forward()->dispatch($controllerName, $data).
Here in the official ZF2 documentation is written exactly how it works:
$params is an optional array of parameters with which to seed a RouteMatch object for purposes of this specific request. Meaning the parameters will be matched by their key to the routing identifiers in the config (otherwise non-matching keys are ignored).
So pass like this:
$params = array(
'foo' => 'foo',
'bar' => 'bar'
);
$this->forward()->dispatch('My\Controller', $params)
And then you can get your route match params in your My\Controller like normally:
$foo = $this->params()->fromRoute('foo');
$bar = $this->params()->fromRoute('bar');
For people struggling with accessing parameters within their controller here a nice overview from this CheatSheet.
$this->params()->fromPost('foo'); //POST
$this->params()->fromQuery('foo'); //GET
$this->params()->fromRoute('foo'); //RouteMatch
$this->params()->fromHeader('foo');//Header
$this->params()->fromFiles('foo'); //Uploaded file