I am a 3+ years old in cakephp and facing a somewhat strange issue
with submitting a form to plugin controller's action (i am using
plugin first time). After trying different known things i am posting
this one.
Going straight into the matter here is the form in my "forum" plugin's search_controller.php's "index" view:
echo $form->create("Search", array('url'=>array('controller' =>
'search', 'action' => 'index','plugin'=>'forum'),
'id'=>'searchFormMain'));
<input type="text" name="data[Search][keyword]" style="width:357px; margin-left:9px;"><p><span id="searchButton"><input
type="image" src="/img/button_search.jpg" style="height:40px;width:
136px;border:0;" class="handcursor"></span></p>
</form>
As i am submitting this form to "index" action of search controller of
forum plugin, the following code does print nothing:
public function index($type='') {
if(!empty($this->data)) {
pr($this->data);
die;
}
}
While if i try the same code within beforeFilter of the same
controller i.e. search_controller.php it works well and prints as
follows:
Array
(
[Search] => Array
(
[keyword] => Hello Forum
)
)
And finally here is the beforeFilter code (of search_controller.php):
public function beforeFilter() {
parent::beforeFilter();
if(!empty($this->data)) {
pr($this->data);
}
}
Fyi, it does not matter if i comment out "parent::beforeFilter();" or
even disable $uses of my controller (if they look doubtful to you)
the result is same i.e. the control is not going in to "index" action
in the case of form submit while is working fine in the case of page
call. The url/action to page is http://localhost.rfdf.org/forum/search/index.
If i call the url directly it loads the form fine but when i submit it, it
never gets into the "index" action of the controller thus no view
rendered.
If i try the same set of code out of "forum" plugin environment i.e. in normal application it works just fine
I have been trying to find a way out of this for last 3+ hours now but
no success. I would appreciate any help in solving this puzzle.
I got it, finally!
It was Securty compontent dropping the request into the blackHole whenever it failed to find a security token with the form data. I learned that "Security" component "interferes" with $form->create() method and places a token as a hidden field with each $form->create() call. On the form submit, just after beforeFilter and right before getting into the controller "action" it checks for this token and simply dies everything on a validation failure. Unfortunately there is no error message or entry to cake log.
In my case i had been creating my own custom tag and not with the help of $form->create method so no token was being generated which lead to all the pain.
I resolved it by placing
$this->Security->validatePost = false;
at the end of beforeFilter.
Thanks everyone!
Have you tried putting an else into that if(!empty($this->data)) and doing a pr() as it could be that your post is not empty.
Either that or the format of your url array is not correct.
From ln759, http://api.cakephp.org/view_source/router/#line-757
$defaults = $params = array('plugin' => null, 'controller' => null, 'action' => 'index');
So I guess you need plugin first?
Are you using ACL or any of the like? In the beforeFilter, do a pr of the request. See which action is being requested to make sure that the request is correct
Related
I'm on CakePHP 3.3.16
I've put this in the main app's Bootstrap.php:
Log::write('info','foo');
$contactTable = \Cake\ORM\TableRegistry::get('Contacts.contacts');
$contactTable->eventManager()
->on('Model.afterSave', ['priority' => 1],function($event, $entity)
{
pr( "afterSave - " );
Log::write('info','afterSave');
});
I do get "foo" in the lofs, and yet when I save the plugin model in question, there's nothing in the logs. I've tried with and without priority.
Do I need to update CakePHP? I think a method has been depracated? The CakePHP event docs said to place this code in Bootstrap.php, so I'm confused...
I seem to have run into an issue in which my controller is not receiving the post data being sent to it via the postLink form helper.
I have multiple controllers, all of which seem to run OK with this action, however, this specific one will not.
I have attempted to debug, and have found that the Delete action does not seem to be receiving any Post data.
View postLink code:
echo $this->Form->postLink(__('Delete'), array('controller' => 'tokens', 'action' => 'delete', $data['token']['id']), null, __('Are you sure you want to delete this data?'));
Controller code:
public function delete($id = null) {
$this->request->allowMethod(['post', 'delete']);
if (!$this->request->is('post')) {
throw new MethodNotAllowedException();
}
$this->Token->id = $id;
if (!$this->Token->exists()) {
throw new NotFoundException(__('Invalid Token'));
}
if ($this->Token->delete()) {
$this->Session->setFlash(__('The token has been deleted.'));
} else {
$this->Session->setFlash(__('The token could not be deleted. Please, try again.'));
}
$this->redirect(array('controller' => 'accounts', 'action' => 'addToken'));
}
I'm really not sure where I'm going wrong or what could be causing it, I've been racking my brain and testing different theories all day but nothing seems to change. All componenets, helpers, etc. are loaded in the same manner the other controllers.
Any help is greatly appreciated!
(CakePHP Version 2.6.2)
EDIT
It looks like there is something going on with a session redirect, in which Cake is redirecting me to /accounts/users/sessionStatus.
I'm have no idea why this is happening.
EDIT
After further digging, I have noticed that when I enter the URl directly into the address bar, everything works as expected, however, clicking the link that was generated by the postLink method prevents the post data from being available.
I'm open to any suggestions/questions/help, this is driving me crazy!
After 8 long hours, I finally determined the cause.
The javascript function handling the form is treating a zero (0) as a null so while the var exists and isset, no value is being passed.
If someone knows/understands more about this, please share!
My problem is fairly basic: whenever an action in CakePHP is blackholed, I want to display a custom error page; the default behaviour of Cake to display a "File not found" message confuses the hell out of users (not to mention developers). So I came up with this, by searching the docs and StackOverflow:
class TestsController extends AppController
{
public $components = array ('Security');
public function beforeFilter ()
{
parent::beforeFilter ();
$this->Security->blackHoleCallback = 'blackhole';
$this->Security->csrfExpires = '+5 seconds'; // for testing
}
public function index ()
{
}
public function doit ()
{
$this->log ('Performing request; entry = ' . $this->data['foo'], 'tests');
$this->set ('foo', $this->data['foo']);
}
public function blackhole ($type)
{
$this->log ('Request has been blackholed: ' . $type, 'tests');
$this->render ('/Errors/blackhole');
$this->response->send ();
exit ();
}
}
In index.ctp there is a simple form with a single textbox, that commits to doit (excluded for brevity). This works, but I have one major issue: the exit() in the blackhole() function. The problem is, if I do not exit here doit() is still called, even if the request is blackholed, as evidenced by the log:
2013-01-30 15:37:21 Tests: Request has been blackholed: csrf
2013-01-30 15:37:21 Tests: Performing request; entry = kfkfkfkf
This is clearly not what you expect. The Cake documentation hints at using (custom) exceptions to stop processing in blackhole(), but that:
completely beats the purpose of using a custom handler;
adds another layer of complexity to something that should be simple.
My question is: is there a proper way to do an "exit" from blackhole() so that Cake does all the rendering/cleanup/etc. that it usually does; I already had to add $this->response->send() to force output to the browser. Or, althernatively, a way to tell Cake to skip calling doit() after blackhole().
My suggestion would be to redirect in your blackhole.
This is done e.g. here in the cookbook http://book.cakephp.org/2.0/en/core-libraries/components/security-component.html#usage
$this->redirect(array('controller' => 'test', 'action' => 'index'));
A redirect will issue an exit (http://book.cakephp.org/2.0/en/controllers.html#flow-control).
You can also send something nice to the user if you want, before the redirect:
$this->Session->setFlash('What are you doing!?');
In your blackhole callback you could just throw an exception with required message. That would render the proper error page and get logged too (assuming you have turned on logging for errors in core.php).
I'm just getting started with cakePHP, and things aren't going so well so far.
I have a controller that handles confirming user emails. On registration the user is sent an email with a confirmcode in a link. Depending on the confirm code they give, the controller gives different text responses. One of these responses includes a hyperlink in order to log in.
I'm trying to use the Html helper, but although I've loaded it in $helpers at the top of the class, I an only make it work if I then use App::import, and then instantiate it.
It all seems overkill to simply make a hyperlink! How many times do I have to load the same class?
Wherever I look on the web it keeps telling me it's a bad idea to use a helper in a controller, but how else am I supposed to get the link made?
So I have
var $helpers = array('Html');
at the top of the controller, and:
if (isset($this->User->id)) { // Check the user's entered it right
// Do some stuff to remember the user has confirmed
// This is to load the html helper - supposedly bad form, but how else do I make the link?
App::import('Helper', 'Html');
$html = new HtmlHelper();
$this->set('message', __("Your email address has been confirmed.", TRUE)." ".$html->link(__("Please log in", TRUE), array('controller' => "users", 'action' => "login" )));
} else {
$this->set('message', __("Please check your mail for the correct URL to confirm your account", TRUE));
}
in the controller's confirm method and
<div>
<?php echo $message;?>
</div>
in the view to output the resulting message
Surely I'm going wrong somewhere - can anyone explain how?
You're not supposed to use Helpers in the Controller. As #Lincoln pointed out, you should construct the link in the View. You may construct the URL in the Controller, since a URL is basically data, but a link is a very medium-specific (HTML) implementation of a URL.
Either way, you'll need to create a full URL (including host) if you want to send it in an Email. The most universal way is to use Router::url:
$fullUrl = Router::url(array('controller' => ...), true); // 'true' for full URL
Do this in either the Controller or the View. For creating a link, use this in the View:
echo $html->link('Title', $fullUrl);
The idea is that all the data you need to render the page is sent to the view with set, then any conditional logic or formatting is done in the view with helpers, so send whole query results when appropriate (suppose you need to alter a link to include the user's screen name, you'll have it handy).
in controller action
$this->set('user', $this->User);
in view (this is slightly different depending on if your in <= 1.2 or 1.3
if ($user->id) //available because of Controller->set
{
//1.2
$link = $html->link(__("Please log in", TRUE), array('controller' => "users", 'action' => "login" ));
//1.3
$link = $this->Html->link(__("Please log in", TRUE), array('controller' => "users", 'action' => "login" ));
echo __("Your email address has been confirmed.", TRUE)." $link";
}
else
{
$this->set('message', __("Please check your mail for the correct URL to confirm your account", TRUE));
}
What you are trying to do should be done with the SessionComponent. $this->Session->setFlash('your message here');
and in your layout with the session helper put $this->Session->flash();
About your wanting urls in the controller, Router::url is correct as deceze said, but there is no use for it there as you should not be building html in a controller.
what you want to do it use the session::setFlash() method above and then redirect them using
$this->redirect(array('controller' => "users", 'action' => "login" ));
The problem is i want to call the index function, i need it to render the view and then the
afterFilter to redirect again to the index function and do the same.. Like a loop, the problem is it doesnt render it, ive tried using $this->render('index') but it doesnt work and also other things..
PS: I didnt include all the code that i have in index, because its pointless, doesnt render with or without it, just included the things i needed for the view.
function afterFilter()
{
if ($this->params['action'] == 'index')
{
sleep(3);
$this->redirect(array('action'=>'index',$id), null, true);
}
}
THE FUNCTION
function index($ido = 0)
{
$this->set('Operator', $this->Operator->read(null, $ido));
$this->set('ido', $ido);
}
THE VIEW = INDEX.CTP
<legend>Operator StandBy Window</legend>
<?php
?>
</fieldset>
<?php echo $html->link('LogIn', array('controller' => 'operators', 'action' => 'add')); ?>
<?php echo $html->link('LogOut', array('controller' => 'operators', 'action' => 'logout',$ido)); ?>
a function that constantly checks my database for a change, if a change occurs ill redirect, if not i need to have that constant loop of 'checking the database' and 'rendering the view'.
This is not possible entirely on the server with PHP, and especially not with CakePHP's template system. PHP just "makes pages" on the server and sends them to the browser and a linear fashion. If you loop on the server, the content of your page will just repeat itself:
Normal content
Normal content
Normal content
<redirect>
To redirect the client, you need to output headers. The headers need to be output before anything else. If you've already looped a few times and content has already been sent to the client, you can't redirect anymore.
There are two ways:
You just output one page at a time showing the current status, with a meta tag that'll refresh the page every x seconds. This can be rather expensive and annoying though.
Use AJAX and possibly Comet to update the information on the page dynamically in the browser.