Yii passing value from one controller to another - php

I am using Yii framework for my application. My application contain 4 controllers in which I want to pass value from one controller to another.
Let us consider site and admin controller. In site controller, I manage the login validation and retrieves admin id from database. But I want to send admin id to admin controller.
I try session variable, its scope only within that controller.
Please suggest the possible solution for me.
Thanks in advance

You want to use a redirect:
In the siteController file
public function actionLogin()
{
//Perform your operation
//The next line will redirect the user to
//the AdminController in the action called loggedAction
$this->redirect(array('admin/logged', array(
'id' => $admin->id,
'param2' => $value2
)));
}
in the adminController file
public function loggedAction($id, $param2)
{
//you are in the other action and params are set
}

Related

Yii2: standalone action does not work in event handler

I'm a beginner in Yii, so don't know, how to solve my problem in most correct way.
There are 2 controllers - SiteController and UsersController. I need to retrieve some data from DB and output it in layout. In particular, if user1 and user2 added user3 as friend, user3 will see it on main menu panel:
User have to see it regardless of controller, action of which is running (in pic above user sees /site/profile page, but a lot of other pages (in particular invitations) render by users controller).
I wrote the same actions in 2 controllers:
public function getStats () { //it duplicates in UsersController and SiteController
$recieved_invitations = Invitations::find()->where(['recipient_id'=>\Yii::$app->user->id])->all();
...
return [$recieved_invitations_count, $received_docs_count];
}
I decided, that, if count need to be in every page, I need trigger it regardless of controllers. So, I wrote in wep.php:
'on beforeAction' => function ($event) {
\Yii::$app->session->set('stats', $event->sender->controller->getStats());
}
And then in menu in layout I retrieve session vars.
Everything works fine. But getStats() action duplicates in controllers. I want to do it standalone.
//action code (in '#app/components' folder) (just from documentation):
namespace app\components;
use yii\base\Action;
class HelloWorldAction extends Action {
public function run() {
return "Hello World";
}
}
//in 'actions()' in controllers:
parent::actions();
return [
'hv' => [
'class' => 'app\components\HelloWorldAction',
]
];
//in 'web.php':
'on beforeAction' => function ($event) {
\Yii::$app->session->set('stats', $event->sender->controller->hv());
}
But exception throws: Calling unknown method: app\controllers\UsersController::hv(). Also: if I disable urlManager in config. file and comment out beforeAction handler, action is accessible via this URL:
http://localhost:8001/index.php?r=users%2Fhv
Why standalone action fails, if it triggers on beforeAction event? And, if it's normal behaviour, what can I do to avoid duplicating getStats() method?
I would actually try to move the getStats method to your User model, that way you can just access it from anywhere in your application by calling it like this:
Yii::$app->user->identity->stats;
// OR
Yii::$app->user->identity->getStats();
It's usually better to have fat models, simple controllers and views.

How to read and write session in helper--Cakephp

I have to use the session in cakephp helper.
To read the session is possible in helper but write session is not.
I don't know how to do it.
Can anyone tell me?
Basic problem is that:
I have created one custom helper which call several times in view for single request.
Suppose helper has called for 5 times.
In helper for textarea some random id has going to be assign.
I need to collect those ids in some variable and then use it for the js function.
If you have new idea related to this problem then please share.
I have added the "session helper" in my custom helper.
Thanks!!!
You can extend SessionHelper , for that place a create a ExtendSessionHelper.php in View/Helper
and add following code in it.
App::uses('SessionHelper', 'View/Helper');
class ExtendSessionHelper extends SessionHelper {
public function write($name, $value = null) {
return CakeSession::write($name, $value);
}
}
Use following code in helpers array of controller to use this helper
var $helpers = array( 'Session' => array('className' => 'ExtendSession'));

Get current controller and action id in Yii

I want to force all users to log in before accessing pages of my site. I have followed Larry Ullman's tutorial Forcing Login for All Pages in Yii.
According to the tutorial you can make an exception for some pages to avoid redirecting to the log in page. In order to check the current controller it has checked $_GET value. My problem is that I have used urlManager to rewrite the URL and $_GET gives me a null value. Is there any method I can use to get the current controller and action in the score of my class?
I tried the following but it is not accessible in the scope of my component class:
Yii::app()->controller->getId
Did you try:
Yii::app()->controller->id
and:
Yii::app()->controller->action->id
?
Yes you can get the current controller/action route, by reversing urlManager rule:
Yii::app()->urlManager->parseUrl(Yii::app()->request)
As now in Yii2
get current controller name
Yii::$app->controller->id
current controller object
Yii::$app->controller
current action name:
Yii::$app->controller->action->id
current route:
Yii::$app->requestedRoute
Using Yii2, obtain the current controller object with:
Yii::$app->controller
From the controller, obtain the current action as a string using:
Yii::$app->controller->action->id
In Yii2:
The problem of calling Yii::$app->controller->id is that when you call it somewhere (example: in one of your top-level abstract controller), Yii::$app->controller might not be instantiated yet, so it will return error.
Just directly call urlManager to map request to route:
var_dump(Yii::$app->urlManager->parseRequest(Yii::$app->request))
Try Yii::app()->controller->getRoute()
If I get you question correctly, you are basically trying to stop access to certain actions in the controller from being accessed without being logged in right?
If this is what you are after, the correct method to do it is this :
Make a actionMethod() in the controller like so :
class SomeController extends CController{
public function actionSomeAction(){
... More code...
}
After that, you can access the site using : path/to/application/controllerName/actionName
Now if you want to force the user to log in before accessing the action, do this :
Make an access control like so :
/**
* #return array action filters
*/
public function filters()
{
return array(
'accessControl', // perform access control for CRUD operations
);
}
/**
* Specifies the access control rules.
* This method is used by the 'accessControl' filter.
* #return array access control rules
*/
public function accessRules()
{
return array(
array('allow', // allow authenticated user to perform 'create' and 'update' actions
'actions' => array('**yourActionMethodName**'),
'users' => array('#'),
),
array('deny', // deny all users
'users' => array('*'),
),
);
}
Now only authenticated users would be able to access the URL.
I hope it solved your problem.
If you simply want to check if the user is a guest and if he is, send him to the login page everytime:
In the config/main.php, add the following :
'defaultController' => 'controllerName/actionMethod',
And in that controller just add the above access rule. Now, by default you are opening the site to an access controlled method. So it would automatically redirect you to the login page.
Even another method :
Just add this in the views/layouts/main.php
<?php
if(Yii::app()->user->isGuest)
{
$this->redirect('/site/login');
}
?>
if (Yii::$app->requestedAction->id == "index") {
//do something
}

Making a dynamic URI in CodeIgniter

I have some website http://www.example.com, I have a controller abc in which I have method index() which loads my website's view. I have made my controller abc as default controller so that when user enters example.com , he can directly see the view. I cannot change this default controller in any case. Now I want that if user enters example.com/1234 , where 1234 is profile number, so it should show that profile . if it is example.com/5678 , then it should show 5678's profile. The problem I am facing is , if user enters example.com/1234 then it will throw a 404 error because I don't have any controller 1234, even if I make a check in my default controller's index function if($this->uri->segment(3) == True) it is throwing 404 error. Any help would be appreciated.
In your routes file add this change:
$route['(:any)'] = 'abc/index/$1';
Then in abc controller:
public function index($profile=NULL)
{
$profile = $this->uri->segment(1, 0);
echo($profile);// just for checking, of course, you will remove this later, + the rest of your code, related to user id
Typically there is a one-to-one relationship between a URL string and its corresponding controller class/method.
In the routes.php (config folder) you can change the defoult controller and routing also. Read the Wildcards (secion) in documentation below
More informacion read the documentation
Create a pre_controller hook in config/hooks.php. Remember to enable hooks in config/config.php if you haven't already.
Example:
$hook['pre_controller'][] = array(
'class' => 'Thehook',
'function' => 'check_for_profile',
'filename' => 'thehook.php',
'filepath' => 'hooks'
);
Then create your hook method check_for_profile() in hooks/thehook.php. This method can check for a matching profile and display or redirect accordingly. If no profile match is found you can call the show_404() method.
This way, your existing controller/method paths are unaffected, and all of your routes remain intact.
If you're redirecting within the hook, use this format:
header("Location: controller/method");
..rather than
redirect('controller/method');
...as the latter will result in a continuous loop
Add in routes.php
$route["(.*)"] = 'abc/userid/$1';
Then in main controller abc add
public function userid()
{
$userid=$this->uri->segment(1);
echo ($userid);
}
Now you have userid in this function :)

CakePHP: using Security::allowedControllers and Security::allowedActions

I'm trying to use Security::allowedControllers and Security::allowedActions. So I have a controller which look more or less like this
class AppController extends Controller {
var $components = array('Security'); //other components
//other stuff
}
class BookController extends AppController {
function beforeFilter() {
parent::beforeFilter();
$this->Security->allowedControllers = array('Users');
$this->Security->allowedActions = array('view');
$this->Security->RequireAuth = array('search', 'results');
}
//other stuff
}
The action 'search' displays a form, which then calls 'results' to show the results of the search. I am intentionally trying to be blackholed.
For what I understand of $this->Security->allowedControllers and $this->Security->allowedActions, I should be able to get POST data only from the action 'view' of the controller 'Users'. In particular the action 'results' should redirect me to a black hole, since it obtains POST data from the action 'search' of the controller 'Books'.
But this is not the case. I can even make cross controller requests, and never get blackholed, so I guess I'm not using correctly this variables. What is the right way to trigger cross-controller requests control?
Try this:
$this->Security->allowedFields = array('Model.fieldname', ...);
You need to add the fields that are not in the model to the allowedFields like I guess your Model.search field in the form.
This is a good and short tutorial for doing Auth with CakePHP 1.3: http://tv.cakephp.org/video/jasonwydro/2011/01/29/cakephp_1_3_auth_authentication_component_tutorial_-_administrator_login

Categories