How to access $this->request->data
passed in by controller inside Views? e.g. variable defined by $this->set('sample')
inside controller can be accessed by $sample
inside view and .ctp files. How can I access values stored inside $this->request->data
through view files?
Asked
Active
Viewed 1.3k times
4
-
2I'd suggest that you read the docs before asking such questions. **http://book.cakephp.org/2.0/en/views.html#View::$request** – ndm Jul 20 '14 at 14:37
-
For a cakePHP 3 solution check http://stackoverflow.com/a/31679836/22470 – powtac Sep 05 '16 at 16:38
1 Answers
9
The CakePHP book says that $this->request
is available within Controllers, Views, and Helpers. So you can access it using $this->request->data
in your view. If you wanted to give it a shorter name, you could set it to something in your controller:
$this->set('requestData', $this->request->data);
If tyour view only needs a couple of variables, it may be clearer to unpack the request data in your controller and pass them in directly. This would also be better separation of concerns; if you refactor your application later, you won't have to update the view as long as you pass in those parameters too:
$this->set('name', $this->request->data('name'));
$this->set('age', $this->request->data('age'));
(Note that I'm using the CakePHP data()
method to access these properties; you don't have to treat it as an array).

Alex P
- 5,942
- 2
- 23
- 30