Issue
There's a way to redirect from a component to a different controller (not the one who called the component) with a Flash message? Something like:
namespace App\Controller\Component;
use Cake\Controller\Component;
class ValidateValueComponent extends Component
{
public function validateValue($var = null){
try{
if(!$var){
throw new \Exception();
}
} catch(\Exception $e){
$action = $this->request->params['action'] === 'index' ? 'home' : $this->request->params['action'];
$controller = $action === 'home' ? 'Home' : $this->request->params['controller'];
$this->_registry->getController()->Flash->error(__('Message!'));
// $this->_registry->getController()->redirect(['controller' => $controller, 'action' => $action]);
}
}
}
I want to validate some values and avoid it to break the execution. If there are no value (not empty) on the $var I want to check if the error was called by the index method, if so send the user to the home page (HomeController) with the flash message. In the other case just send the user to the index from the controller who captured the error and show the flash message.
This code above allow me to show the Flash or redirect, but I cannot do both of them.
Anyway,
Thank you all!
Solution
Actually I solved using this link from bookstack.cn but overwall I needed to call the Flash component on my $components array and then use it normally, independant of the controller who has called the component. Something like:
namespace App\Controller\Component;
use Cake\Controller\Component;
class ValidateValueComponent extends Component
{
public $components = ['Flash'];
public function validateValue($var = null){
try{
if(!$var){
throw new \Exception();
}
} catch(\Exception $e){
$action = $this->request->params['action'] === 'index' ? 'home' : $this->request->params['action'];
$controller = $action === 'home' ? 'Home' : $this->request->params['controller'];
$this->Flash->set(__('Message!'));
return $this->_registry->getController()->redirect(['controller' => $controller, 'action' => $action]);
}
}
}
Answered By - MarceloSnts
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.