Redirect causing blank screen error cakephp - cakephp

$this->redirect called from any controller method seems to result in a blank screen error, despite turning debug to 2 in my core.php.
In my AdminAppController, located in App/Plugin/Admin/Controller, was this piece of code originally, in my beforefilter():
public function beforeFilter() {
parent::beforeFilter ();
$rusername = $this->Auth->user ( "Username" );
if ($rusername != "admin") {
$this->redirect ( "/" );
return;
}
This results was an admin wide blank screen error, regardless of username. By commenting out the redirect, it allowed me to enter the admin area again.
However, now whenever I use $this->redirect I get blank screen errors.
For example here is my Prices view through my Product controller:
<?php echo $this->Session->flash('flash');?>
<?php echo $this->Form->create('Product', array('action' => 'change')); ?>
<fieldset>
<h3>Products</h3>
<table>
<?php
foreach($products as $k=>$v){
echo $this->Form->hidden("Product.{$k}.id", array('value'=> $v["Product"]['id']));
echo $this->Form->input("Product.{$k}.name", array('value' => $v["Product"]["name"], 'disabled' =>'disabled'));
echo $this->Form->hidden("Product.{$k}.slug", array('value'=>$v["Product"]['slug']));
echo $this->Form->hidden("Product.{$k}.description", array('value'=>$v["Product"]['description']));
echo $this->Form->hidden("Product.{$k}.cateID", array('value'=>$v["Product"]['cateID']));
echo $this->Form->input("Product.{$k}.price", array('value' => $v["Product"]['price']));
echo $this->Form->hidden("Product.{$k}.photo", array('value'=>$v["Product"]['photo']));
echo $this->Form->hidden("Product.{$k}.photo_dir", array('value'=>$v["Product"]['photo_dir']));
echo $this->Form->hidden("Product.{$k}.active", array('value'=>$v["Product"]['active']));
echo $this->Form->hidden("Product.{$k}.views", array('value'=>$v["Product"]['views']));
echo $this->Form->hidden("Product.{$k}.created", array('value'=>$v["Product"]['created']));
echo $this->Form->hidden("Product.{$k}.modified", array('value'=>$v["Product"]['modified']));
}
?>
</table>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
My Products controller contains this method:
public function prices(){
$products = $this->Product->find ("all");
$this->set ("products", $products );
}
And this method is called from this view:
public function change(){
//create() resets model, precaution
$this->Product->create();
$data = $this->request->data;
$this->Product->saveMany($data['Product']);
$this->Session->setFlash( "Prices Saved.");
$this->redirect ( '/' );
return;
}
On submitting a change of price (which does save and alter the database, the redirect line causes the screen to go blank, with no errors, or any other indication of what has gone wrong.
Error logs show no sign of what is happening.
Thanks.

Apologies for the late Answer.
After much struggle it turned out to simple.
AdminAppController included some whitespace before an opening

Related

How to get HashTag in Cakephp Form Submit?

I am working in cakephp 2.x
my current url is http://sitename.com/users/edit_profile#step-2 when i submit page i am not getting #setp-2
Code:
//Setp-2
<?php echo $this->form->create('User',array('action'=>'edit_profile')); ?>
<label>Smoke</label>
<?php $smoke_option = array('Heavy'=>'Heavy','Moderate'=>'Moderate','Light'=>'Light','Occasional'=>'Occasional','Non Smoker'=>'Non Smoker','Herb'=>'Herb');
echo $this->form->input('smoke', array('options' => $smoke_option,'default'=>$getProfile['User_detail']['smoke'],'label'=>false,'div'=>false,'empty'=>'No Answer'));?>
</div>
<?php echo $this->form->end();?>
UsersController.php
public function edit_profile(){
$this->layout='default';
if($this->request->is('post')){
$data = $this->request->data;
$data['User']['id']=$this->Session->read('Auth.User.id');
$updateProfile=$this->User->add_details($data);
if($updateProfile){
$this->Session->setFlash(__('Your Profile Updated Successfully'), 'success_message');
$this->redirect($this->referer());
}
}
}
How to getting hashtag in cakephp form submit?
Use
array('action'=>'edit_profile', '#' => 'step-2')
It appends #step-2 as you need in the url, similarly you can use your for ? also
The hash is never sent to the server.
ref - http://stackoverflow.com/questions/940905/can-php-read-the-hash-portion-of-the-url
though you can set a hidden field and set the value = .
you can access the hash by document.location.hash

pagination not working when clicked next button

Controler
public function search() {
$this->Paginator->settings = $this->paginate;
$this->loadmodel('Usermgmt.User');
if ($this->request -> isPost()) {
$this->User->set($this->data);
$keyword=$this->data['Doctors']['search'];
//$this->loadmodel('Usermgmt.User');
$cond=array('OR'=>array("User.username LIKE '%$keyword%'","User.email LIKE '%$keyword%'", "User.first_name LIKE '%$keyword%'", "User.last_name LIKE '%$keyword%'"));
//$result = $this->paginate('User',array('conditions'=>$cond));
$result = $this->paginate('User',array($cond));
$this->set('result', $result);
}
}
View
<?php
if (!empty($result)) { $sl=0;
foreach ($result as $row1) {
//print_r($row1);
$sl++; ?><div style="width:100%;display:inline-block;">
<div style="float:left">
<?php
//echo $row1['id'];
echo $this->Html->link($this->Html->image('../files/user/photo/'.$row1 ['User']['photo_dir'].'/'.$row1 ['User']['photo'], array('width' => '180', 'height' => '180')),
array('controller'=>'Profiles','action'=>'index',$row1['User']['id']),
array('escape' => false));
?>
</div>
<div>
<?php echo h($row1['User']['first_name'])." ".h($row1['User']['last_name'])."</br>";
echo h($row1['User']['username'])."</br>";
echo h($row1['User']['email'])."</br>";
echo h($row1['User']['mobile'])."</br>";
echo h($row1['UserGroup']['name'])."</br>";
?></div>
<div style="clear:both;"></div>
</div>
<?php }?>
<?php echo $this->Paginator->prev('previous'); ?>
<?php echo $this->Paginator->numbers(); ?>
<?php echo $this->Paginator->next('Next'); ?>
<?php }?>
here am search the user name or user details like fname, email like and display in view page
here i get output with pagination like 1 2 3 4 only first page displays when i click next page that shows empty pages may be $result getting unset how to solve this ??
The variable result is only sometimes set
if ($this->request->isPost()) {
...
$result = $this->paginate('User',array($cond));
$this->set('result', $result);
}
The variable result is only set for POST requests - clicking a link is not a post request, therefore the result variable is undefined.
Ensure you are paginating a GET request
There are several solutions, but the simplest solution to "How to paginate post data" is to not do so. Change your search form to use GET, and ensure the get parameters persist when paginating a request.
At the very least the controller code needs to call paginate and set for the variables in the view to exist irrespective of how the controller action was reached.

Calling a element after login

I have a post index view calling a element which content input field for comment.
I call it in this way
<?php echo $this->element('addcomment', array('post_id' => $post['Post']['id'])); ?>
This work fine, I pass the post id parameter, in the addcomment element, because the post_id input field is hidden in the addcomment. and of course I dont want that the user type the post id.
I have set up the authorization mechanism in order to allow adding comment to the user identified (connected).
When a non-connected user try to add a comment, he receives the login screen.
After login, he is redirected to the add commment form. The problem is that in the mean time it loose the value of the post_id variable.
Rem: If the user is connected before adding comments to the post, it works.
Dont hesitate to contact me in case my explanation is not clear or if you need more information.
This is my addcomment element
<div class="Addcomment form">
<?php
echo $this->Form->create('Comment', array(
'url' => array('controller' => 'comments', 'action' => 'add')
)); ?>
<fieldset>
<legend><?php echo __('Add Comment'); ?></legend>
<?php if (isset($current_user['id']) && isset($post_id)): ?>
<?php $this->request->data['Comment']['user_id'] = $current_user['id']; ?>
<?php $this->request->data['Comment']['post_id'] = $post_id; ?>
<?php echo $this->Form->input('post_id', array('type' => 'hidden')); ?>
<?php echo $this->Form->input('user_id', array('type' => 'hidden')); ?>
<?php else: echo $this->Form->input('post_id'); ?>
<?php endif; ?>
<?php echo $this->Form->input('content', array('class' => 'comment')); ?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
</div>
As per i understand your problem. You can use a session variable to store a post id which should not affected if user logs in. And using this session you can redirect a user to particular post after login.
Set a session value before redirecting user to login.
$this->Session->write('last_post_id',YOUR_POST_ID);
Redirect user to the post if user successfully logged in and if you find a session value not empty.
if ($this->Session->check('last_post_id') && $this->Session->read('last_post_id') != '') {
$this->redirect(YOUR_URL_TO_POST . '?postid=' . $this->Session->read('last_post_id'));
exit;
}else{
//NORMAL REDIRECTION
}
Hope this will help you. Unset session last_post_id after redirection and if no longer required.

cakephp - change password method leaves blank the password field in database

i've created a method in my UsersController.php file , so that my users can change their password.
My method php code is:
public function changepass() {
$this->User->id = $this->Auth->user('id');
if($this->User->exists()) {
$new_pass = $this->request->data['User']['newpass'];
$repeat_pass = $this->request->data['User']['newrepeat'];
if($new_pass == $repeat_pass) {
$this->User->saveField('password',$new_pass);
$this->Session->setFlash(__('Updated successfully'));
$this->redirect(array('controller' => 'users','action' => 'dashboard'));
} else {
$this->Session->setFlash(__('Passwords did not match'));
$this->redirect(array('controller' => 'users','action' => 'changepass'));
}
}
}
and my changepass.ctp View file is:
<?php
echo $this->Form->create();
echo $this->Form->input('newpass',array('type'=>'text','label'=>array('text'=>'Enter new password')));
echo $this->Form->input('newrepeat',array('type'=>'text','label'=>array('text'=>'Confirm new password')));
?>
<button type="submit">Save</button>
<?php echo $this->Form->end(); ?>
When i try to browse under the users/changepass,it returns me 2 errors about an undefined index:
Notice (8): Undefined index: User [APP/Controller/UsersController.php, line 108]
Notice (8): Undefined index: User [APP/Controller/UsersController.php, line 109]
pointing at this part of my code:
$new_pass = $this->request->data['User']['newpass'];
$repeat_pass = $this->request->data['User']['newrepeat'];
and also it (immediately) changes the user password in my database to blank.
I cannot find out what's wrong in any way. I'd be very grateful if you could help me at this point.
Thank you in advance.
You forgot one vital part about form processing in the controller: Check on POST.
if ($this->request->is('post')) {
// only then try to access $this->request->data['User'] content!
}
In the case thats it not a post (get), you just display the form - especially without trying to save anything.
Tip: Take a look at baked code (using cake bake) and you will see how it's done properly.

cakephp $this->request-is("post") return false for just one form, so strange?

I have many forms in the website. They are all created in the similar way like
<?php echo $this->Form->create('SysUser');?>
<fieldset>
<legend><?php echo __('Edit Basic Information'); ?></legend>
<?php
echo $this->Form->input('SysUser.first_name');
echo $this->Form->input('SysUser.family_name',array('label'=>__("Last Name")));
echo $this->Form->input('SysUser.mobile_phone_number');
echo $this->Form->input('SysUser.user_name',array('label'=>__("Screen Name")));
echo $this->Form->input('action', array('type'=>'hidden','value'=>'edit_basic_info'));
echo $this->Form->input('SysUser.id', array('type'=>'hidden','value'=>$user["id"]));
?>
</fieldset>
<?php echo $this->Form->end(__('Submit'));?>
But the type of one form becomes "put" , not "post". I never explicitly set the type to "post" when I create these forms. I gather CakePHP sets the default value to post. Now it seems something wrong about the way I create this new special form. Oddly, this was working days ago!
I don't know what's wrong. Here is it:
<?php echo $this->Form->create('Member'); ?>
<fieldset>
<legend><?php echo __('Basic Profile Setup'); ?></legend>
<?php
echo $this->Form->input('Member.gender_id');
$w = array();
for ($i = 40; $i < 120; $i++) {
$w[$i] = $i . " kg";
}
$h = array();
for ($i = 120; $i < 230; $i++) {
$h[$i] = $i . " cm";
}
echo $this->Form->input('Member.height', array(
'options' => $h,
'empty' => __("choose one")
));
echo $this->Form->input('Member.weight', array(
'options' => $w,
'empty' => __("choose one")
));
$options['minYear'] = date('Y') - 78;
$options['maxYear'] = date('Y') - 18;
echo $this->Form->input('Member.birthdate', $options);
echo $this->Form->input('Member.residential_location_id', array('label' => __("City/Location")));
echo $this->Form->input('Member.occupation_id',array('id'=>'MemberOccupationId'));
echo $this->Form->input('action', array('type' => 'hidden', 'value' => 'create_member'));
?>
</fieldset>
<?php
echo $this->Form->end(array("label" => __('Save')));
When the Request data contains a Model.id CakeRequest::method() is set to put. The preferred way to handle this in cakephp would be as follows.
if ($this->request->is(array('post', 'put'))) {
// Code
}
You can see this in baked controller, edit actions.
Not sure why it is happening, but you can set the form type this way:
<?php echo $this->Form->create('Member', array('type' => 'post')); ?>
I had this problem as well. In my situation this was happening when I had validation errors. So for the second run, the script thought it was a PUT request instead of a POST request. Now, because it was a PUT, it didn't even get inside the if-clause where I checked if it was a POST, so it would return to the input and try to create a POST request. This was looping forever.
The solution? Checking for a NOT GET.
So you would get something like this:
if (!$this->request->is('get')){
//Save logic here
}
I have seen an example like this in the Cookbook, but I can not find it. So I have a feeling it has been updated, but as far as I am concerned you have to use this method. So you will cover a PUT, as well as a POST request.
UPDATE
It is not recommended to use this approach. It is a PUT/POST based on if the id is set in the form. Since I was setting the id based on the type of request, instead of if it actually exists, it was switching over and over again. I am using 1 form for the add and the edit action. They both use the edit.ctp which is just set up more flexible.
From the Cookbook:
If $this->request->data contains an array element named after the form’s model, and that array contains a non-empty value of the model’s primary key, then the FormHelper will create an edit form for that record.
Is that the case, perhaps? What's Member's primary key?
I had the same issue and after 4 hours searching I just resolved it appending the Model name to the fields in the view like this:
<?php echo $this->Form->create('User');?>
<?php
echo $this->Form->input('User.id');
echo $this->Form->input('User.username', array('readonly' => true));
echo $this->Form->input('User.email', array('readonly' => true));
echo $this->Form->input('User.name');
echo $this->Form->input('User.phone');
echo $this->Form->input('User.gender');
echo $this->Form->input('User.locale', array('id' => 'locale_select', 'options' => array('es' => __('Spanish'), 'en' => __('English'))));
echo $this->Form->input('User.birthday', array('type' => 'date', 'dateFormat' => 'DMY', 'minYear' => date('Y') - 100, 'maxYear' => date('Y')));
?>
<?php echo $this->Form->end(__('Save', true));?>
Well, I have to say that this code is in a plugin, so I don't know if there could be any other problems. But other forms in that plugin work perfect and this one needs to have the Model name.
One of the ways I've handled this situation is to create my own detector that defines the context of post OR put. This goes in the beforeFilter() method in AppController:
// add a simple form post detector
$this->request->addDetector('formPosted', array(
'env' => 'REQUEST_METHOD',
'options' => array('post', 'put')
));
Then when you need to check if a form has been posted (or "putted"), then:
if ($this->request->is('formPosted')) { ... }
Since the detector is added in AppController, the condition can be checked from within any controller method.

Resources