Cakephp multiple views per controller - cakephp

I have a controller which has 3 functions. I wish to show 3 different views and layouts in each function depending on whether the user comes from mobile, website or facebook. I am passing in already where the user is coming from.
I am unsure how I would then show a particular view and layout for each. Here is some code that I started to do to change the layout. I have the views in a folder called res.
function availability() {
if ($_REQUEST['from'] == 'facebook') {
$this->layout = 'facebook';
print_r ('face');
}elseif ($_REQUEST['from'] == 'website'){
$this->layout = 'website';
print_r ('web');
}elseif ($_REQUEST['from'] == 'mobile'){
$this->layout = 'mobile';
print_r ('mobile');
};
}

Use $this->render() to change the view.
$this->layout = 'facebook';
$this->render( 'res/facebook' );
You could also put all the views for different layouts to their own folders and set the viewpath so that you don't have to choose the views manually in each function:
function beforeFilter() {
parent::beforeFilter();
$this->viewPath = $_REQUEST[ 'from' ];
}
Now the view for action "availability" for the Facebook layout is fetched from facebook/availability.ctp.

Related

CakePHP3 Render View to a Variable

I want to render the view to a variable without directly sending it to the browser. I used to do it with cakephp2.*. But, I cannot figure out how to do it in CakePHP3. Could you please tell me how to do it?
ViewBuilder was introduced in CakePHP 3.1 and handles the rendering of views. When ever I want to render to a variable I always go look at how send email works.
From a controller:
function index() {
// you can have view variables.
$data = 'A view variable';
// create a builder (hint: new ViewBuilder() constructor works too)
$builder = $this->viewBuilder();
// configure as needed
$builder->layout('default');
$builder->template('index');
$builder->helpers(['Html']);
// create a view instance
$view = $builder->build(compact('data'));
// render to a variable
$output = $view->render();
}
For Ajax request/response, I use this:
public function print(){
if ($this->request->is('ajax')) {
$data = $this->request->getData();
$builder = $this->viewBuilder()
->setTemplatePath('ControllerName')
->setTemplate('print');
->setLayout('ajax');
->enableAutoLayout(false);
$view = $builder->build(compact('data'));
$html = $view->render();
$res = ['html' => $html];
$this->set('response',$res);
$this->set("_serialize",'response');
}
}
And the print.ctp is under Template/ControllerName

Cakephp 3.x Exception render - different layout

This document shows how to assign layout for error:
$this->layout = 'my_error';
http://book.cakephp.org/3.0/en/development/errors.html#exception-renderer
But i've 2 different layouts for frontend and backend. When NotFoundException is thrown, i want to assign different layout accordingly.
How can i do that? Please help me.
Just check appropriate criteria and set layout accordingly in your template. For e.g.
if ($this->request->param('prefix') === 'admin') {
$this->layout = 'admin';
} else {
$this->layout = 'default';
}
As #ADmad suggest.
Do check the request to identify frontend or backend inside error400.ctp file (you may have another error file, just is a example).
In my case use admin prefix, i did like this:
if (!empty($this->request->params['prefix']) && $this->request->params['prefix'] == 'admin') {
$this->layout = 'Admin/default';
$app = [
'App.imageBaseUrl' => 'admin/img/',
'App.cssBaseUrl' => 'admin/css/',
'App.jsBaseUrl' => 'admin/js/'];
Configure::write($app);
} else {
$this->layout = 'Frontend/default';
}
If you want to re-set layout you have to re-render the action, a redirect would be the most easy solution here. You could also use an AppView.
$view = new AppView();
$view->set($variables);
$view->render();
http://book.cakephp.org/3.0/en/views.html#the-app-view

Cakephp - Pagination with JSON API

I am developing (with a partner) a CakePHP application which will use Backbone.js.
So, basically, my cake application largely behaves like a JSON API. After the controller action loads a certain view (no data is rendered yet), Backbone makes an AJAX call to another controller action to fetch the data. The controller return JSON.
(The routes.php file has the mapResources and parseExtensions line in place)
Controller code
public function index(){
$company_id = $this->Session->read('Company.id');
$channel_ids = $this->Order->Channel->find('all', array('conditions' => array('Channel.company_id' => $company_id), 'fields' => array('Channel.id')));
$channel_ids = Set::extract('/Channel/id', $channel_ids);
$data = $this->paginate('Order', array('Order.fulfillment_status_id' => 1, 'Order.channel_id' => $channel_ids));
$this->set('orders', $data);
//In case of a JSON request
if($this->RequestHandler->ext == 'json') {
$this->autoRender = false;
echo json_encode($data);
}
}
This worked fine, but we hit a wall when we tried to implement pagination with this.
How do we generate the Pagination links? (If we do it via Backbone, it does not know the total records in the database and hence does not know how many links to generate)
How should the "page number" be burnt into the AJAX call? How should it be deciphered in the controller?
Really stuck here, we will really appreciate your help.
In Your Controller
$this->layout = false;
$this->RequestHandler->respondAs('json');
$recipes = $this->paginate('Recipe');
$this->set(compact('recipes'));
In your View
echo json_encode($recipes);
echo json_encode($this->Paginator->params());

CakePHP website mobile version

I have developed a full website with CakePHP framework and we'd like to make a very light version of the website for mobile devices (mainly iPhone/iPad).
Is there a way to use the existing website with a new sub domain (for instance mobile.mywebsite.com) which will render specific views? I would like to avoid copying and simplifying the current one to match the new one requirements. I do not want to have to "re-develop" a new CakePHP website and do the changes twice every time I need to change a controller action.
I've done this using a quick addition to the beforeFilter() in my app_controller.php file.
function beforeFilter() {
if ($this->RequestHandler->isMobile()) {
$this->is_mobile = true;
$this->set('is_mobile', true );
$this->autoRender = false;
}
}
This uses the CakePHP RequestHandler to sense if it's a mobile device visiting my site. It sets a property and view variable to allow actions an views to adjust themselves based on the new layout. Also turns off the autoRender because we'll take care of that in an afterFilter.
In the afterFilter() it looks for and uses a mobile view file if one exists. Mobile versions are stored in a 'mobile' folder inside the controller's view folder and are named exactly the same as the normal non-mobile versions. (ie. add.ctp becomes mobile/add.ctp)
function afterFilter() {
// if in mobile mode, check for a valid view and use it
if (isset($this->is_mobile) && $this->is_mobile) {
$view_file = new File( VIEWS . $this->name . DS . 'mobile/' . $this->action . '.ctp' );
$this->render($this->action, 'mobile', ($view_file->exists()?'mobile/':'').$this->action);
}
}
Dan's answer worked for me. However, I used file_exists instead of the File constructor and added the ability to use mobile layouts. The before filter was the same, but the afterFilter looked like this:
function afterFilter() {
// if in mobile mode, check for a valid view and use it
if (isset($this->is_mobile) && $this->is_mobile) {
$view_file = file_exists( VIEWS . $this->name . DS . 'mobile/' . $this->action . '.ctp' );
$layout_file = file_exists( LAYOUTS . 'mobile/' . $this->layout . '.ctp' );
$this->render($this->action, ($layout_file?'mobile/':'').$this->layout, ($view_file?'mobile/':'').$this->action);
}
}
You can use Theme feature in CakePHP 2.x for mobile layout.
Simply do:
if($this->RequestHandler->isMobile())
$this->theme = 'mobile';
I found this better, as you can share View file on mobile and desktop theme easily.
I modified this technique for a CakePHP 2.1 app. Here is my beforeFilter():
public function beforeFilter() {
if ($this->request->isMobile()){
$this->is_mobile = true;
$this->set('is_mobile', true );
$this->autoRender = false;
}
}
And here is my afterFilter():
function afterFilter() {
// if in mobile mode, check for a valid view and use it
if (isset($this->is_mobile) && $this->is_mobile) {
$view_file = file_exists( 'Views' . $this->name . DS . 'mobile/' . $this->action . '.ctp' );
$layout_file = file_exists( 'Layouts' . 'mobile/' . $this->layout . '.ctp' );
if($view_file || $layout_file){
$this->render($this->action, ($layout_file?'mobile/':'').$this->layout, ($view_file?'mobile/':'').$this->action);
}
}
}
This helps account for deprecated verbiage and constants in CakePHP 2.
The simple solution is to create a new 'mobile' layout with respective stylesheet(s) and turn it on in AppController:
public $components = array('RequestHandler');
public function beforeRender() {
parent::beforeRender();
if ($this->RequestHandler->isMobile()) {
$this->layout = 'mobile';
}
}
It is important to do that in beforeRender() in case if you change $this->layout in your controllers' methods.
CakePHP v2.2.1 Solution (+ Cookies to persist mobile/desktop/other layout)
This solution is based on answers by #Dan Berlyoung, #deewilcox and #Chris K.
Parts of those answers failed to work (for me) in CakePHP 2.2.1.
I also extended the solution to support "forcing" a mobile/desktop/other layout from the frontend - useful for debugging and for users that don't want to be stuck on a "mobile" themed layout.
/app/Controller/AppController.php
class AppController extends Controller {
public $components = array('Cookie');
public $is_mobile = false;
public $layouts = array('desktop', 'mobile');
// executed before every action in the controller
function beforeFilter()
{
// Using "rijndael" encryption because the default "cipher" type of encryption fails to decrypt when PHP has the Suhosin patch installed.
// See: http://cakephp.lighthouseapp.com/projects/42648/tickets/471-securitycipher-function-cannot-decrypt
$this->Cookie->type('rijndael');
// When using "rijndael" encryption the "key" value must be longer than 32 bytes.
$this->Cookie->key = 'qSI242342432qs*&sXOw!adre#34SasdadAWQEAv!#*(XSL#$%)asGb$#11~_+!##HKis~#^'; // When using rijndael encryption this value must be longer than 32 bytes.
// Flag whether the layout is being "forced" i.e overwritten/controlled by the user (true or false)
$forceLayout = $this->Cookie->read('Options.forceLayout');
// Identify the layout the user wishes to "force" (mobile or desktop)
$forcedLayout = $this->Cookie->read('Options.forcedLayout');
// Check URL paramaters for ?forcedLayout=desktop or ?forcedLayout=mobile and persist this decision in a COOKIE
if( isset($this->params->query['forcedLayout']) && in_array($this->params->query['forcedLayout'], $this->layouts) )
{
$forceLayout = true;
$forcedLayout = $this->params->query['forcedLayout'];
$this->Cookie->write('Options.forceLayout', $forceLayout);
$this->Cookie->write('Options.forcedLayout', $forcedLayout);
}
// We use CakePHP's built in "mobile" User-Agent detection (a pretty basic list of UA's see: /lib/Cake/Network/CakeRequest.php)
// Note: For more robust detection consider using "Mobile Detect" (https://github.com/serbanghita/Mobile-Detect) or WURL (http://wurfl.sourceforge.net/)
if( ( $forceLayout && $forcedLayout == 'mobile' ) || ( !$forceLayout && $this->request->is('mobile') ) ) {
$this->is_mobile = true;
$this->autoRender = false; // take care of rendering in the afterFilter()
}
$this->set('is_mobile', $this->is_mobile);
}
// executed after all controller logic, including the view render.
function afterFilter() {
// if in mobile mode, check for a vaild layout and/or view and use it
if( $this->is_mobile ) {
$has_mobile_view_file = file_exists( ROOT . DS . APP_DIR . DS . 'View' . DS . $this->name . DS . 'mobile' . DS . $this->action . '.ctp' );
$has_mobile_layout_file = file_exists( ROOT . DS . APP_DIR . DS . 'View' . DS . 'Layouts' . DS . 'mobile' . DS . $this->layout . '.ctp' );
$view_file = ( $has_mobile_view_file ? 'mobile' . DS : '' ) . $this->action;
$layout_file = ( $has_mobile_layout_file ? 'mobile' . DS : '' ) . $this->layout;
$this->render( $view_file, $layout_file );
}
}
}
/app/View/Elements/default_footer.ctp
<ul>
<?php
$paramsQuery = $this->params->query;
if(!is_array($paramsQuery))
{
$paramsQuery = array();
}
$paramsQuery['url'] = ( isset($paramsQuery['url']) ) ? $paramsQuery['url'] : '';
$url = $paramsQuery['url'];
unset($paramsQuery['url']);
$params = $paramsQuery;
$mobile_url = '/' . $url . '?' . http_build_query( array_merge( $params, array( 'forcedLayout' => 'mobile' ) ) );
$desktop_url = '/' . $url . '?' . http_build_query( array_merge( $params, array( 'forcedLayout' => 'desktop' ) ) );
?>
<?php if($is_mobile): ?>
<li><?= $this->Html->link('Desktop Site', $desktop_url, array('target' => '', 'class' => '')) ?></li>
<?php else: ?>
<li><?= $this->Html->link('Mobile Site', $mobile_url, array('target' => '', 'class' => '')) ?></li>
<?php endif; ?>
</ul>
/app/View/Layouts/default.ctp
<h1>Desktop Site Layout</h1>
<?= $this->fetch('content') ?>
/app/View/Layouts/mobile/default.ctp
<h1>Mobile Site Layout</h1>
<?= $this->fetch('content') ?>
/app/View/Pages/home.ctp
<h2>Home - on Desktop</h2>
<?= $this->element('default_footer') ?>
/app/View/Pages/mobile/home.ctp
<h2>Home - on Mobile</h2>
<?= $this->element('default_footer') ?>
Usage
Use the default_footer links to change layout - or these direct urls
http://example.com/pages/home?forcedLayout=desktop
http://example.com/pages/home?forcedLayout=mobile
A session COOKIE persists the option you've chosen... e.g. try setting to "mobile" and then visit a url without the forcedLayout= param.
http://example.com/pages/home
The default_footer links persist existing params (except for the "fragment" #gohere)
http://example.com/pages/home/a/b/c:d?this=that&foo=bar#gohere
Desktop Site url is:
http://example.com/pages/home/a/b/c:d?this=that&foo=bar&forcedLayout=desktop
For more robust device User-Agent detection consider using the Mobile Detect PHP Library ... you could then target Tablets, and even specific devise OS versions.... Oh what fun! ^_^
The solution I went with was a lightweight modification based on a few of the answers here, for CakePHP 2.5.5. The handling is all done in the beforeRender (note that beforeRender is only run on controller actions that will actually render a page, so this saves overhead as opposed to beforeFilter/afterFilter for private methods):
$mobile = $this->request->is('mobile');
$this->set('mobile',$mobile);
//Check if an alternate mobile view and/or layout exists for this request.
if($mobile){
if(file_exists(APP.'View'.DS.$this->name.DS.'mobile'.DS.$this->view.'.ctp')){
//Render this action on its mobile view.
$this->view = 'mobile'.DS.$this->view;
}
if(file_exists(APP.'View'.DS.'Layouts'.DS.'mobile'.DS.$this->layout.'.ctp' )){
//Render this action on its mobile layout.
$this->layout = 'mobile'.DS.$this->layout;
}
}
The $mobile variable can be used on any view if you have small tweaks to make, otherwise you can optionally replace any view with View/{controller}/mobile/same_file_name.ctp or layout with View/Layouts/mobile/same_file_name.ctp to have a separate page structure entirely.
Note that this uses $this->view and $this->layout and then modifies them, instead of using $this->action and $this->render(view,layout), because your view won't always match your action (same view, multiple actions, for example, break using $this->action), and this solution prevents needing to worry about when $this->render() will be forced, and allows it to happen naturally.
Yes, you can re use all of your domain and controllers, have a look to Tera-WURLF
And even better, you don't need a subdomain for the mobile version.

Cakephp Auth with multiple "Users" tables

I would like to know how to deal with only ONE authentification process and "users" in multiple tables. I have 4 Users table: users, admins, artists, teamadmins which all have specific fields, but I would like all of these users to be able to connect via only one form on the homepage, and being redirected after that to their specific dashboards.
I think the redirections shouldn't be a problem, and some routes added should work, but I really don't know where to look/start to ake this all possible.
Cheers,
Nicolas.
EDIT: here's the final solution (thanks to deizel)
App::import('Component', 'Auth');
class SiteAuthComponent extends AuthComponent {
function identify($user = null, $conditions = null) {
$models = array('User', 'Admin', 'Artist');
foreach ($models as $model) {
$this->userModel = $model; // switch model
$this->params["data"][$model] = $this->params["data"]["User"]; // switch model in params/data too
$result = parent::identify($this->params["data"][$model], $conditions); // let cake do its thing
if ($result) {
return $result; // login success
}
}
return null; // login failure
}
}
CakePHP's AuthComponent only supports authentication against a single "User" model at a time. The model is chosen by setting the Auth::userModel property, but it only accepts a string and not an array of models.
You can switch the userModel on the fly with the following code, but this requires you to know in advance which model to switch to (eg. your users have to choose their account type from a dropdown):
public function beforeFilter() {
if (isset($this->data['User']['model'])) {
$this->Auth->userModel = $this->data['User']['model'];
}
}
You can likely extend the core AuthComponent to add the functionality you want by overwriting the AuthComponent::identify() method so it loops over and attempts authentication with each model:
App::import('Component', 'AuthComponent');
class AppAuthComponent extends AuthComponent {
function identify($user = null, $conditions = null) {
$models = array('User', 'Admin', 'Artist', 'TeamAdmin');
foreach ($models as $model) {
$this->userModel = $model; // switch model
$result = parent::identify($user, $conditions); // let cake do it's thing
if ($result) {
return $result; // login success
}
}
return null; // login failure
}
}
You will have to replace occurrences of Auth in your application with AppAuth to use your extended AuthComponent, unless you use this trick.
While annoying, I think the best solution is probably using Cake's built in ACL support (see http://book.cakephp.org/2.0/en/tutorials-and-examples/simple-acl-controlled-application/simple-acl-controlled-application.html).
If you do authentication the way you're talking about, you have to keep track of permissions in your controller code, checking to see what the userModel is. If you use an access control list, the permission tree will already exist in the database, which should simplify your code a great deal, and make it more modular.
It also means restructuring your data model to have a single users table and groups table instead of entity classes for each type of user.
I just went through the process of doing this myself... :(
this is also a possibility
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->authenticate = array(
AuthComponent::ALL => array('userModel' => 'AnotherModel'),
'Form',
'Basic'
);
}
Here is the final solution as suggested by deizel and modified by Nicolas:
App::import('Component', 'Auth');
class SiteAuthComponent extends AuthComponent {
function identify($user = null, $conditions = null) {
$models = array('User', 'Admin', 'Artist');
foreach ($models as $model) {
$this->userModel = $model; // switch model
$this->params["data"][$model] = $this->params["data"]["User"]; // switch model in params/data too
$result = parent::identify($this->params["data"][$model], $conditions); // let cake do its thing
if ($result) {
return $result; // login success
}
}
return null; // login failure
}
}

Resources