Process post action with another action within controller - cakephp

I have a terribly designed app where the index action displays a form in a JavaScript-based dialogue that's submitted to process action and then redirects to index (either on success or on error). The process action does not even have a view:
class UnicornsController
{
public function index($foo, $bar)
{
$this->set(
array(
'unicorn' => $this->Unicorn->findByFooAndBar($foo, $bar);
)
);
}
public function process()
{
$this->Unicorn->save($this->request->data);
$this->redirect(
array(
'action' => 'index',
$this->request->data['Unicorn']['foo'],
$this->request->data['Unicorn']['bar'],
)
);
}
}
I'm adding proper error reporting. I'm trying to change the this->redirect() part so $this->request->data is not lost and I have a chance to display it again in the form generated in index.ctp but I can't get it right: both $this->requestAction() and $this->index() try to render process.ctp anyway. Am I using them incorrectly or I'm missing the right approach?

If you want to run a different action, you can use Controller::setAction(), it changes the action parameter in the request, sets the template to render accordingly, and returns the possible return value of the invoked action.
public function process()
{
// ....
$this->setAction(
'index',
$this->request->data['Unicorn']['foo'],
$this->request->data['Unicorn']['bar']
);
}
See also
API > Controller::setAction()

Related

Cakephp redirect in isAuthorized method not working

So after login in isAuthorized method I'm trying to redirect user based on a condition. But problem is it's not redirecting. Below the code that I have tried.
protected function isAuthorized($LoginUser)
{
if ($this->getTable('Users')->hasCompany($LoginUser) == false){
$this->redirect(['controller'=>'Companies','action'=>'edit']);
dd("hello");
}
}
It's not redirecting and getting hello message. How can I redirect after login user to another page based on condition ?
As mentioned in the comments, the auth component's authorization objects are supposed to return a boolean, and depending on that, let the component do the unauthorized handling-
What you could do, is for example dynamically set the component's unauthorizedRedirect option (and probably also authError) from the controller's authorization handler for that specific case (I guess you'd also have to exclude the respective company controller's action from that check, as otherwise you'll end up in an infinite redirect loop):
if (!$this->getTable('Users')->hasCompany($LoginUser)) {
$message = __('You must provide company information in order to proceed.');
$url = \Cake\Routing\Router::url([
'controller' => 'Companies',
'action' => 'add'
]);
$this->Auth->setConfig([
'authError' => $message,
'unauthorizedRedirect' => $url,
]);
return false;
}
// ...
return true;
If you find yourself in a situation where there's no such possibility, brute forcing a redirect by throwing a \Cake\Http\Exception\RedirectException could be a solution too, even though it's ideally avoided, it's better than dying, as it will at least emit a clean redirect response:
$url = \Cake\Routing\Router::url([
'controller' => 'Companies',
'action' => 'add'
]);
throw new \Cake\Http\Exception\RedirectException($url);
See also
Cookbook > Controllers > Components > AuthComponent > Configuration options

How to use $this->autoRender = false in cakephp 3.6.10?

I am trying to display the test data on the screen by running function test() in the pagesController. Used $this->autoRender = false for it, but it is still giving me error:
Please help me out. I think some version problem is there, but I can't figure it out. Thankyou.
Cakephp by default takes Pages controller's display actions as a home page. display function manages pages and subpages itself that is why you are getting error. Either you can change your default home page in your /config/routes.php
$routes->connect('/', ['controller' => 'Pages', 'action' => 'index']);
OR
define your test action in some other controller.
OR
Remove code from display action
class PagesController {
function display()
{
// default controller code here
// your custom code here
}
}
Hope this will work.

Cakephp 2.3 beforeFilter and implementedEvents aren't able to co-exist

Using cakephp 2.3.5.
I use beforeFilter in several controllers to allow certain actions without the need to log in. I've used it successfully for quite some time. However, I've noticed that I can't get beforeFilter to fire if the controller also has the implementedEvents() method.
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('matchWwiProducts');
}
public function implementedEvents() {
return array(
'Controller.Product.delete' => 'deleteSku',
'Controller.Product.price' => 'notifySubscribers',
'Controller.Product.stock' => 'notifySubscribers'
);
}
For the code as displayed above I will be forced to do a login if I call the method www.example.com/products/matchWwiProducts.
When I comment out the implementedEvents() everything works as intended. I've searched around and can't find any references to implementedEvents() creating issues with beforeFilter.
The action matchWwiProducts() is as follows. It works perfectly when I log in. However, I don't want to force a log in for this action to take place.
public function matchWwiProducts() {
// this is an audit function that matches Products sourced by wwi
//
$this->autoRender = false; // no view to be rendered
// retrieve products sourced from wwi from Table::Product
$this->Product->contain();
$wwiProducts = $this->Product->getWwiSkus();
$wwiProductCount = count($wwiProducts);
// retrieve products sourced from wwi from Table:Wwiproduct
$this->loadModel('WwiProduct');
$this->Wwiproduct->contain();
$wwiSource = $this->Wwiproduct->getSkuList();
$wwiSourceCount = count($wwiSource);
// identify SKUs in $wwiProducts that are not in $wwiSource
$invalidSkus = array_diff($wwiProducts, $wwiSource);
// identify SKUs in $wwiSource that are not in $wwiProducts
$missingSkus = array_diff($wwiSource, $wwiProducts);
$missingSkuDetails = array();
foreach ($missingSkus as $missingSku) {
$skuStockStatus = $this->Wwiproduct->getStockStatus($missingSku);
$missingSkuDetails[$missingSku] = $skuStockStatus;
}
$email = new CakeEmail();
$email->config('sourcewwi');
$email->template('sourcewwiaudit', 'sourcewwi');
if (count($invalidSkus) > 0 || count($missingSkus) > 0) {
$email->subject('WWI Source Audit: Invalid or Missing SKUs');
$email->viewVars(array('invalidSkus' => $invalidSkus,
'missingSkuDetails' => $missingSkuDetails,
'wwiProductCount' => $wwiProductCount,
'wwiSourceCount' => $wwiSourceCount));
} else {
$email->subject('WWI Source Audit: No Exceptions');
$email->viewVars(array('wwiProductCount' => $wwiProductCount,
'wwiSourceCount' => $wwiSourceCount));
}
$email->send();
}
It doesn't fire because you're overloading the implementendEvents() method without making sure you keep the existing events there.
public function implementedEvents() {
return array_merge(parent::implementedEvents(), array(
'Controller.Product.delete' => 'deleteSku',
'Controller.Product.price' => 'notifySubscribers',
'Controller.Product.stock' => 'notifySubscribers'
));
}
Overloading in php.
Check most of the base classes, Controller, Table, Behavior, Component, they all fire or listen to events. So be careful when extending certain methods there. Most simple way might to do a search for "EventListenerInterface" in all classes. A class that implements this interface is likely to implement event callbacks.

Cakephp validation bug in controller?

I am trying to invalidate a field by a condition in controller instead of Model.
$this->Model->invalidate('check_out_reason', __('Please specify check out reason.', true));
The above won't work to invalidate the field. Instead, I need the below:
$this->Model->invalidate('Model.check_out_reason', __('Please specify check out reason.', true));
However, if I wish get the error message show up in the "field" itself ($this->model->validationErrors), it needs to be "check_out_reason" instead of "Model.check_out_reason". That means, I can't get the error message to show up in the field itself if I wish to invalidate the input in controller.
May I know is this a bug in CakePHP?
i created a test controller called "Invoices", just for testing, and i developed the following function
public function index(){
if (!empty($this->request->data)) {
$this->Invoice->invalidate('nombre', __('Please specify check out reason.'));
if ($this->Invoice->validates()) {
// it validated logic
if($this->Invoice->save($this->request->data)){
# everthing ok
} else {
# not saved
}
} else {
// didn't validate logic
$errors = $this->Invoice->validationErrors;
}
}
}
i think it worked for me
Change the field "nombre" for your field called "check_out_reason" to adapt the function to your code
I found a workaround for manual invalidates from controller. Reading a lot on this issue I found out that the save() function doesn't take in consideration the invalidations set through invalidate() function called in controller, but (this is very important) if it is called directly from the model function beforeValidate() it's working perfectly.
So I recommend to go in AppModel.php file and create next public methods:
public $invalidatesFromController = array();
public function beforeValidate($options = array()) {
foreach($this->invalidatesFromController as $item){
$this->invalidate($item['fieldName'], $item['errorMessage'], true);
}
return parent::beforeValidate($options);
}
public function invalidateField($fieldName, $errorMessage){
$this->invalidatesFromController[] = array(
'fieldName' => $fieldName,
'errorMessage' => $errorMessage
);
}
After that, make sure that your model's beforeValidate() function calls the parent's one:
public function beforeValidate($options = array()) {
return parent::beforeValidate($options);
}
In your controller for invalidating a field use next line:
$this->MyModel->invalidateField('fieldName', "error message");
Hope it helps! For me it's working!

Extending cakephp auth component with extra conditions

Problem: I want to show different error messages to user based on user status on login (using ajax). For ex: If the user status is pending, I want to show one message, or else if the user status is disabled, I want to show another message. Only active user should be able to login.
After some searching found that I can use
identify method
or
I should use write my conditions inside "if
($this->Auth->login())" condition in my login method.
If I use 1st method in custom component (which will extend auth), hope it can only return true or false, right ? Can it set error messages and return, so that I can get it from my controller ?
If I use 2nd method after allowing the user to login I should check the status and if it is not active, I should remove the login credentials from Auth/Session. how can I do that ? Is this a good method ?
Any other better solution ? Im using cakephp2.0
I would create a class extending from BaseAuthenticate for your users and set this up within your AppController.
public $components = array(
'Session',
'Auth' => array(
'loginRedirect' => ..... ,
'logoutRedirect' => ..... ,
'loginAction' => ..... ,
'authenticate' => array('YourUsers'),
)
);
And then create the class
<?php
App::uses('BaseAuthenticate', 'Controller/Component/Auth');
class YourUsersAuthenticate extends BaseAuthenticate {
public function authenticate(CakeRequest $request, CakeResponse $response) {
// your code goes in here
}
}
You can return false from within the authenticate to deny the user access or can return an object on success that will get stored in $this->Auth->user which you can interogate later.
If you get stuck, the CookBook has a lot of detail about this.

Resources