This is a real newbie question, but I have not used PHP and Phalcon very long and I am
sort of learning by studying examples, reading on internet and a bit of trial and error.
One thing that I got stuck on is how to pass variables to views that belongs to another controller.
If I want to pass a variable to a view in the same controller, lets call it showRoomController, then I simply use.
$this->view->setVar("id", $cars->id);
However, if I want to open the cars view from catalogueController, but from a page that belongs to showRoomController I use this:
return $this->forward("catalogue/cars");
How can I pass the cars id variable in the second example? Or do I need to use global variables?
I apologize if this is a very basic question that I probably should know.
Dispatcher's forward() method accepts params as well:
$this->dispatcher->forward(array(
"controller" => "myController",
"action" => "myAction",
"params" => array('name' => 'hello', 'surname' => 'world')
));
By default your view is a shared service in the DI. You can simply set parameters as you do in one controller, and when it did forward to another all of those parameters would still be there.
When you do $this->view in your controller it uses a magic method to get the view service from the DI, so if you do that in both controllers you will be referencing the same view.
Related
I am using a module called Facebook which has a view helper called shareUrl. This view helper gets the Facebook share URL for any URL.
However, I have recently added another module called Twitter which also has a view helper called shareUrl.
In Zend Framework version 2 or 3, within views, how can I call one shareUrl view helper versus the other?
Just to clarify, the code in my view looks like the following:
$facebookShareUrl = $this->shareUrl('https://www.example.com/');
$twitterShareUrl = $this->shareUrl('https://www.example.com/');
I would like $facebookShareUrl and $twitterShareUrl to store the return values of two different view helpers.
If you've got two helpers with the same name, only one is available as it is registered under the given name within the servicemanager (viewhelpermanager). If you switch them around with loading the modules in your application.config.php you can change the default. But that is not a real solution to your problem.
So there are multiple ways to get the right viewhelper you need.
1) The best way is to setup an alias for the registered viewhelpers using their FQCN. See some example code where we create aliases that can be used in the viewherlpers like $this->facebookShareUrl('exmaple.com')
return [
'view_helpers' => [
'aliases' => [
'facebookShareUrl' => FacebookModule\Helper\ShareUrlHelper::class,
'twitterShareUrl' => TwitterModule\Helper\ShareUrlHelper::class,
],
]
]
2) Get the helper by its FQCN using the viewhelpermanager in the view itself, using the PhpRenderer instance. Within a view.phtml file
$viewHelperManager = $this->getHelperPluginManager();
$facebookShareUrlHelper = $viewHelperManager->get(FacebookModule\Helper\ShareUrl::class);
$twitterShareUrlHelper = $viewHelperManager->get(TwitterModule\Helper\ShareUrl::class);
I'm currently using Laravel 5.3 and i have a number of routes similar to.
Route::get('/news/create/{product}', 'NewsController#create')->name('news::create');
So in my blade template im using the route() function like so:
{{route('news::create','car')}}
But the url generated is
/news/create?car
not the required
/news/create/car
The same thing happens if i put it in an array:
{{route('news::create',['car'])}}
And if i give it a key like so:
{{route('news::create',['product'=>'car'])}}
I get:
/news/create?product=car
How do I get the correct url so it is passed to the 'create' function as a parameter?
Firstly, take a look at your route naming. I don't think there's anything specifically wrong with naming a route like 'news::create' apart from it being ugly and quite probably considered bad practice. I like to go with camel casing, which means I'd use a name like createNews. It's much easier when going back to work on old sections of code and will stop other programmers from stabbing you if/when they work on a project with you.
The reason we can name routes is so that the name stays static even if we change the route URI or controller endpoint. We can pass variables to it using route parameters.
Route::get('/news/create/{product}', array('as' => 'createNews', 'uses' => 'NewsController#create'));
route('createNews', ['product' => 'car']);
{{route('news::create',['product => 'car'])}}
Should fix your problem. Laravel uses named routes and expects an array with the keys as names with values.
Read all about it here: https://laravel.com/docs/5.3/redirects#redirecting-named-routes
In CakePHP have a bunch of unique URL names redirected in routes.php file.
Similar to this:
$beautiful_urls[0] = '/view/location-name/image-name.html';
Router::connect($beautiful_urls[0],
array('controller' => 'Foo','action' => 'bar',3,60));
I want to create facebook like buttons based on the beautified names. In order to do that I need the $beautiful_urls variable I use in the routes.php in the Foo controller.
How can I reach a variable in routes.php from a controller?
So far I tried to link it with App::use('routes','Config'); but it's not working. I also thought about sending the values as action parameters, but that doesn't seem like good practice... I know it's not a great idea to mix the config file with a controller's logic but I don't have any better idea so far.
I'm not cakephp user but simple search shows that there is class called ClassRegistry.
You can create class BeautifulUrls and store it there. According to docs it's singleton and It can be accessed from everywhere.
Also you can make BeautifulUrls implement ArrayAccess interface so you don't have to change your routes
I don't know if it's a good practice or not but my solution was to use the Configure class of CakePHP. It was straightforward to use and accessible everywhere in the code and the config files.
You can save key-value pairs with
Configure::write('key','value');
and read it again with
Configure::read('key');
It would be nice to be able to format a url in a portable way inside of a controller, for example for a JSON response. Is there an easy way to do this without creating an instance of Zend_View first?
Several thoughts here:
Even if you are generating a JSON response, you can still use the view object and view-scripts via the ContextSwitch and AjaxContext action helpers.
Even if you don't use a view-script for your response, you have probably already instantiated the view back at Bootstrap. So in the controller you wouldn't actually be creating the view as much as accessing it. So no additional overhead there.
If by "portable" you mean "cross-project", then maybe an action-helper? Drop it into another project, configure helper paths, and you're good to go. If by "portable" you mean "more aware of your application's routing", then you're probably stuck using the view object.
If saying "format URL" you meaning create an url from params, url view helper is you answer. You use it in controller the same way as in view and don't need to create new Zend_View instance - if you're using view renderer you have your helper in $this->view. So
//in view
$this->url(array('controller' => 'index', 'action' => 'default'));
//in controller
$this->view->url(array('controller' => 'index', 'action' => 'default'));
But if you look into code of url view helper, you'll see, that it's using router object to assemble routes/url/. So all you need is router object, which you can obtain in several ways, some of them:
//in controller
$router = $this->getFrontController()->getRouter();
//anywhere
$router = Zend_Controller_Front::getInstance()->getRouter();
//and then
$router->assemble(array('controller' => 'index', 'action' => 'default'));
You can also use HelperBroker, retrieve viewRenderer from there, retrieve a view and run helper method.
is there an easy way to access the url helpers from the models like the ones available in the controllers
i mean in the controllers there is an easy way to generate urls like this :
$this->_helper->url(controller,action,null,params);
now what i need is an easy way to pass urls direclty from the model to the views , for now what i am doing is to pass the CONTROLLER,ACTION AND PARAM as an array to controller then replace the text in the controller with with the helper url in the controller but i want a better way is there one?
You can access the url helper by calling it directly:
$urlHelper = new Zend_View_Helper_Url();
$urlHelper->url(array(),'',true);
The Model should not access the View, nor having to know about it.
If you have to do work that is related to the presentation layer, either use an Action Helper or a View Helper. The data you are processing is fully available in the Controller, so there should be no need to pass it from model.
actually it's a bit specific to my problem but i made work it this way
$check['msg'] == will contain the error or success message
from the models i pass the link that causes the problem
$messages['link'] = array('action'=>'index','controller'=>'trip','params'=>$tripid );
an on the controllers
$check['msg'] = str_replace('%link%',$this->_helper->url($check['link']['action'],$check['link']['controller'],null,array('id' => $check['link']['params'])),
$check['msg']);
$this->_flashMessenger->addMessage($check['msg']);
I found the following code snippet in a book, it maybe of help to someone:
$urlHelper = $this->_helper->getHelper('url');
$urlHelper->url(array(
'controller' => 'customer' ,
'action' => 'save'
),
'default'
);