问题描述
有一种方法可以通过Flash消息从组件重定向到另一个控制器(不是调用该组件的控制器)?像这样:
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]);
}
}
}
我想验证一些值,并避免破坏执行。如果$ var上没有值(非空),我想检查索引方法是否调用了错误,如果是,则将用户与Flash消息一起发送到主页(HomeController)。在另一种情况下,只需从捕获错误并显示Flash消息的控制器向用户发送索引即可。
上面的这段代码允许我显示Flash或重定向,但是我不能同时执行这两个操作。
反正
谢谢大家!
解决方法
实际上,我解决了使用bookstack.cn中的此链接的问题,但是我需要在$ components数组上调用Flash组件,然后正常使用它,这与调用该组件的控制器无关。像这样:
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]);
}
}
}