Change Default action base on user groups in CakePHP - php

I have different users groups e.g. admin, author,publisher and have separately controllers for them I want to set default path after login on base of
$this->Auth->User('group_id')
like this in appcontroller in beforefilter() method
if ($this->Auth->User('group_id') == '1')
{
Router::connect('/', array('controller' => 'admin', 'action' => 'index'));
}
elseif($this->Auth->User('group_id') == '2')
{
Router::connect('/', array('controller' => 'author', 'action' => 'index'));
}
else {
Router::connect('/', array('controller' => 'publisher', 'action' => 'index'));
}
I tried this in
routes.php
in Config using $_SESSION Variable because in that file couldnt use
$this.
Main purpose is that when user login it will take to their controller and so i can have clean URL
I dont want to same controller i have to use check for group than ACL library's power will be in waste.
Any Help will be appreciated to accomplish this. Thanks in advance

Based on your comment on Isaac's answer, you can do something like this.
Say, in routes.php you can have:
Route::connect('/', array('controller' => 'some_controller', 'action' => 'index'));
Then in your redirected controller's index() method:
public function index()
{
$group = $this->User->Group->find('first', array( //assuming User belongsTo Group
'conditions' => array(
'id' => $this->Auth->User('group_id')
),
'fields' => array('name')
)
)); //getting the name of the group the user belongs to
call_user_func(array($this, strtolower($group['Group']['name']).'_index'));
}
And then in your controller you can have something like:
protected function admin_index()
{
//code for admins
}
protected function publisher_index()
{
//code for publishers
}
protected function author_index()
{
//code for authors
}
So you have all code on the same controller but separated on different methods.

//Don't miss the app_controller for this small kind of thing. bear in mind always keep the app controller clean and tidy.
function login(){
//here you can say after login what's happen next
if ($this->Auth->login()){
$this->redirectUser();
}
}
//redirect user groups
function redirectUser(){
$role = $this->Auth->User('group_id');
switch ($role) {
case 1:
return $this->redirect(array('controllers'=>'admin_controller', 'action'=>'action_name'));
break;
case 2:
return $this->redirect(array('controllers'=>'author_controller', 'action'=>'action_name'));
default:
return $this->redirect(array('controllers'=>'user_controller', 'action'=>'action_name'));
break;
}
}
If you want to use custom url You also need to name it into routes.php
Route::connect('/admin', array('controller' => 'admin_controller', 'action' => 'index'));
the rest of links

Related

Cakephp 3 - The page isn’t redirecting properly

I am using Cakephp 3.x in which I have created one method inside my AppController (checkBrandAssigned) in which I have checked my logic and redirecting to the other page as per my needs. Below is how method looks like.
AppController.php
public function checkBrandAssigned(){
$this->loadModel('Users');
$user_data = $this->Users->find()
->select(['user_id'])
->where([
'user_type' => SALES_REPRESENTETIVE,
'user_status' => STATUS_INACTIVE,
'user_id NOT IN (SELECT ub_user_id FROM fp_user_brand)'
])
->order([ 'user_modified_date'=>'DESC'])
->first();
if (!empty($user_data)) {
return $user_data->user_id;
} else {
return '';
}
}
And below is my full snippet of AppController.php file.
<?php
class AppController extends Controller {
public function initialize() {
parent::initialize();
switch ($this->request->session()->read('Auth.User.user_type')):
case COMPANY_ADMIN :
$loginRedirectUrl = ['controller' => 'users', 'action' => 'dashboardCompanyAdmin'];
break;
default : $loginRedirectUrl = ['controller' => 'users', 'action' => 'dashboardSalesRep'];
break;
endswitch;
}
public function checkBrandAssigned(){
$this->loadModel('Users');
$user_data = $this->Users->find()
->select(['user_id'])
->where([
'user_type' => SALES_REPRESENTETIVE,
'user_status' => STATUS_INACTIVE,
'user_id NOT IN (SELECT ub_user_id FROM fp_user_brand)'
])
->order([ 'user_modified_date'=>'DESC'])
->first();
if (!empty($user_data)) {
return $user_data->user_id;
} else {
return '';
}
}
}
As you can see above, I have used checkBrandAssigned method inside my beforeFilter and if my condition gets true, I am redirecting at, $this->redirect(['controller' => 'Users', 'action' => 'brandRetailerView','?'=>['repId'=>'6b12337d37870e4afb708a20f4f127af']]);.
Below is how my UsersController.php file.
UsersController.php
class UsersController extends AppController {
public function initialize() {
parent::initialize();
}
public function beforeFilter(Event $event) {
parent::beforeFilter($event);
}
public function brandRetailerView() {
die('inside my function');
}
}
As you can see I have put die('inside my function'); I am able to see this text, howerver, If I comment it, I am getting error saying...
The page isn’t redirecting properly
I have also created blank brand_retailer_view.ctp file in my respective location. Below is screenshot of my error.
I have also used Auth Component. I want brandRetailerView and checkBrandAssigned methods to be used after login hence I have not added inside my $this->Auth->allow in AppController.php and UsersController.php. However, I tried to add checkBrandAssigned in $this->Auth->allow, but still its not working.
I have tried to use return parent::beforeFilter($event); in my UsersController.php but its not working as well.
I have not added anything extra inside my .htaccess file, hence I am not adding here.
Can someone help me why I am having this issue. Even if I use die its working but as soon as I comment it, I am getting above error.
the issue is not in the code, it's in the logic
the issue is because irrespective of the condition returned by checkBrandAssigned(), the redirect will be to users controller and before filtering the user controller the condition will be checked again and will again be redirected to the user controller.
it will become an infinite loop of redirection, in case of die() it is working because die() break the loop before the redirect happens.
to solve this remove the redirect check from beforeFillter and put somewhere else...
add this to enable cookies in AppController.
use Cake\Controller\Component\CookieComponent;
and update the condition as follows.
if (!isset($this->Cookie->read('checkedInLast30Secs'))) {
$this->Cookie->write('checkedInLast30Secs',
[
'value' => true,
'expires' => '+30 secs'
]
);
if (!empty($checkSalesRepId)) {
$this->redirect(['controller' => 'Users', 'action' => 'brandRetailerView', '?' => ['repId' => '6b12337d37870e4afb708a20f4f127af']]);
// $this->dashboardUrl = ['controller' => 'users', 'action' => 'brandRetailerView'];
} else {
$this->dashboardUrl = ['controller' => 'users', 'action' => 'dashboardCompanyAdmin'];
}
}
Eventually I have solved with below code.
case COMPANY_ADMIN :
if (!empty($checkSalesRepId)) {
if($this->request->params['action'] != 'brandRetailerView'){
$this->redirect(['controller' => 'Users', 'action' => 'brandRetailerView','?'=>['repId'=>$checkSalesRepId]]);
}
else {
$this->dashboardUrl = ['controller' => 'users', 'action' => 'dashboardSalesManager'];
}
}
Here I am simply checking if the current action is not brandRetailerView. If so, I am redirecting to brandRetailerView page, else dashboardSalesManager page.
Hope this helps.

How to use custom routes in CakePHP?

I want to implement custom routes in CakePHP. I am following the docs
http://book.cakephp.org/2.0/en/development/routing.html#custom-route-classes
My custom route in app/Routing/Route
<?php
App::uses('CakeRoute', 'lib/Cake/Routing/Route');
class CategoryRoute extends CakeRoute
{
public function parse($url)
{
$params = parent::parse($url);
if (empty($params)) {
return false;
}
return true;
}
}
app/Config/routes.php
App::uses('CategoryRoute', 'Routing/Route');
Router::connect('/mypage/*', array('controller' => 'mycontroller', 'action' => 'view'), ['routeClass' => 'CategoryRoute']);
but I get
Missing Controller
Error: Controller could not be found.
Error: Create the class Controller below in file: app/Controller/Controller.php
When I remove ['routeClass' => 'CategoryRoute'], rerouting just works fine.
Have a closer look at the API documenation: API > CakeRoute::parse()
The parse() method is supposed to return an array of parsed parameters (ie $params) on success, or false on failure.

How to configure cakephp custom route class

I have create custom router class in cakephp 2.x, I'm just follow this blog post. In my app i don't have /Routing/Route folders and I create folders and put StaticSlugRoute.php file to it. In that file include following code
<?php
App::uses('Event', 'Model');
App::uses('CakeRoute', 'Routing/Route');
App::uses('ClassRegistry', 'Utility');
class StaticSlugRoute extends CakeRoute {
public function parse($url) {
$params = parent::parse($url);
if (empty($params)) {
return false;
}
$this->Event = ClassRegistry::init('Event');
$title = $params['title'];
$event = $this->Event->find('first', array(
'conditions' => array(
'Event.title' => $title,
),
'fields' => array('Event.id'),
'recursive' => -1,
));
if ($event) {
$params['pass'] = array($event['Event']['id']);
return $params;
}
return false;
}
}
?>
I add this code but it didn't seems to working (event/index is working correct).I want to route 'www.example.com/events/event title' url to 'www.example.com/events/index/id'. Is there any thing i missing or i need to import this code to any where. If it is possible to redirect this type of ('www.example.com/event title') url.
Custom route classes should be inside /Lib/Routing/Route rather than /Routing/Route.
You'll then need to import your custom class inside your routes.php file.
App::uses('StaticSlugRoute', 'Lib/Routing/Route');
Router::connect('/events/:slug', array('controller' => 'events', 'action' => 'index'), array('routeClass' => 'StaticSlugRoute'));
This tells CakePhp to use your custom routing class for the URLs that look like /events/:slug (ex: /events/event-title).
Side Note: Don't forget to properly index the appropriate database field to avoid a serious performance hit when the number of rows increases.

CakePHP 2.0+: Retrieving POST data from Js->submit form in controller

I am using $this->Js->submit to pass a value to my controller asynchronously and than update a div (id = #upcoming). Somehow I cannot save/retrieve the value of the field 'test' which is passed to my controller. Firebug tells me that the correct value is passed. What am I doing wrong?
View file (playlist.ctp):
echo $this->Form->create('Add', array('url' => array('controller' => 'Gods', 'action' => 'add')));
echo $this->Form->input('test');
echo $this->Js->submit('Addddd', array(
'url' => array(
'controller' => 'Gods',
'action' => 'add'
),
'update' => '#upcoming'
));
echo $this->Form->end();
echo $this->Js->writeBuffer(array('inline' => 'true'));
Controller action:
public function add()
{
$this->autoLayout = false;
$this->layout = 'ajax';
$link = $this->request->data['Add']['test'];
$this->set('test',$link);
}
And its view file (add.ctp):
<?php
echo $test;
?>
Thanks for your help!
have you tried pr($link) in the controller method? Or just send it to a log file if you prefer that. That way you can see if the data is received.
If so, I think there is nothing returned because of
$this->autoLayout = false;
Try it without this. It will still call the ajax layout instead of the default.
Otherwise you have to manualy call the render function
$this->render('add');
EDIT
As explained in the comments below, make sure your views are in the right place. (that would be the view folder associated with the controller)

How to pass values throuh link in Zend Framework?

I want to pass values through
<a href= <?php $this->baseUrl()/admin/registration/activate/> </a>
this is my code an i have to pass user Id to this url to activate user. what I have to use I wll get my user id <?php $this->userid; ?>
please help
my action is
public function activateAction()
{ // Administrator actvate user
$user_name = $this->getRequest()->getParam('user_name');
$reg = new clmsRegistrationModel();
$reg->setActive($user_name);
}
inside your action
$this->_request->getParam('prop_id', null);
Lets assume you have Controller Index and Action Customer, so you can build you link with an Zend Framework View helper (inside your view script):
echo $this->url(array(
'controller' => 'index',
'action' => 'customer',
'prop_id' => 5
));
in your Controller:
customerAction() {
$propId = $this->getRequest()->getParam('prop_id');
}
After your comment (add to your view script):
<?php $postUrl = $this->url(array(
'controller' => 'admin',
'action' => 'registration',
'activate' => $this->userid
)); ?>
Activate

Categories