I am having problems with updating records using cakephp, this is the second time it happens and cant figure out what it is.. When I click on 'Submit' to update a record it always, always sends me to the login and it either logs me in or logs me out.. I dont understand..and it never updates the record it just jumps to the login stuff...the registration page same thing.. it was working before.. the only thing i changed.. was in app_controller instead of specifying the controls to allow I just added the '*' for all and now its not allowing to update or save anything.. the reason why i did that was because other pages that are under pages/contact_us or pages/about_us they were also being blocked by the Auth but with the '*' it went away..
In my App_Controller I have set it up to allow everything in the before filter, also in the controller itself i have a beforeFilter again saying the same thing.. I have tried about everything.. Here is my code
App_Controller
<?php
class AppController extends Controller {
var $helpers = array('Html', 'Form', 'Javascript', 'Session');
var $components = array('Auth', 'Session');
function beforeFilter() {
$this->Auth->allowedActions = array('*');
$this->Auth->autoRedirect = false;
}
}
?>
one of my controllers where I update
<?php
class DishRatingsController extends AppController {
function list_ratings() {
$this->loadModel('Dish');
$this->set('list_ratings', $this->Dish->find('all'));
$this->layout = 'master_layout';
}
function rate_dish($id = null)
{
$this->layout = 'master_layout';
$this->set('rate_dishes', $this->DishRating->find('all', array(
'conditions' => array(
'Dish.id' => $id
)
)));
if(!empty($this->data)) {
if($this->DishRating->save($this->data)) {
$this->Session->setFlash("Rating Saved!");
$this->redirect(array('action' => 'dish_ratings'));
}
// set master layout
}
}
function beforeFilter() {
parent::beforeFilter();
$this->Auth->allowedActions = array('*');
}
}
and My view where the submit button is
<?php
echo $this->Form->create('DishRating', array('action' => 'rate_dish'));
echo '<div><h3>Rate this Dish...</h3><p>You can rate this dish on this page and view other ratings from out customers... </p></div>
<table id="recipes">
<tr>
<td style="padding:10px;">';
//<input type="hidden" name="userID" value="'.$rate_dishes[0]["DishRating"]["user_id"].'">
echo $this->Form->hidden('id', array('value'=> $rate_dishes[0]["DishRating"]["user_id"]));
//<input type="hidden" name="dish_id" value="'.$dish_rateid.'">
echo $this->Form->hidden('rate_id', array('value'=> $rate_dishes[0]["DishRating"]["dish_id"]));
echo '
<span style="font-size: 20px; vertical-align:top;">Comments</span>
</td>
<td style="padding:10px;">';
echo $this->Form->input('comments', array('type' => 'textarea', 'escape' => false , 'rows'=>'2','cols'=>'40', 'div' =>'false', 'label'=>''));
//<textarea name="comments" cols="40" rows="2"></textarea>
echo '</td>
<td>
<div>
<input name="star1000" value "1" type="radio" class="star"/>
<input name="star1000" value="2" type="radio" class="star"/>
<input name="star1000" value="3" type="radio" class="star"/>
<input name="star1000" value="4" type="radio" class="star"/>
<input name="star1000" value="5" type="radio" class="star"/>
</div>
</td>
<td>';
// <input type="submit" value="Submit" name="submitrating" class="button"/>
echo $this->Form->end(array('value'=>'Submit','name'=>'submitrating', 'type' =>'submit', 'class'=>'button'));
echo '</td>
<tr>
</table>';
print("<table id='results'><tr><th>User Name</th><th>Comments</th><th>Star Rating</th></tr>");
$j = 0;
foreach ($rate_dishes as $key => $rate_dish):
print("<tr>");
print("<td width='20px'>");
print("<p style='font-size:14px; color:blue; padding:0;'>".$rate_dishes[$j]['User']['username']."</p>");
print("</td>");
print("<td width='100px'>");
print("<p style='font-size:14px; color:blue; padding:0;'>".$rate_dishes[$j]['DishRating']['rate_comments']."</p>");
print("</td>");
print("<td width='100px'>");
print("<div>");
for($i = 1; $i < 6;$i++)
{
if($i != $rate_dishes[$j]['DishRating']['rate_num'])
{
echo '<input name="star'.$j.'" type="radio" class="star" disabled="disabled"/>';
}
else
{
echo '<input name="star'.$j.'" type="radio" class="star" disabled="disabled" checked="checked"/>';
}
}
print("</div>");
print("</td>");
print("</tr>");
$j++;
endforeach;
print("</table>");
if($j> 6)
{
echo '<div id="pageNavPosition"></div>
<div> </div>';
echo $this->Html->script('padminbottom.js');
}
?>
Please help solve this issue, I have researched, went to the cakePHP cookbook, nothing...
if you want to allow every action of every controller your beforeFilter in app_controller should be like
function beforeFilter() {
$this->Auth->allow('*');
$this->Auth->autoRedirect = false;
}
specifying $this->allowedActions is a different thing and in that case your Auth's authorize variable should be set to 'controller'. That means whenever a user requests an action he/she will be checked for their correct username, password. After that user will be checked by the isAuthorize() function implemented by every controller to grant access based on some additional logic.
Since you are not using that feature you don't need to specify allowedAction. If you are using controller for authorization specifying allowedActions will allow certain actions by default without checking them in Controller::isAuthorize().
Related
This is my AdminsController class where I have included the Cookie Component, and used the cookie creation code given below in #1. #2 is the code I am using in my view.
Whenever I fire the url, it is showing the error: "Helper class CookieHelper could not be found.".
Why is this error is showing, as I have asked to use CookieComponent to set and get the value of the cookie. I have followed instructions and code syntax from the CakePHP docs that they have provided on their website. I'm really having trouble on setting and getting the cookie. I need help on this. The CakePHP version that i'm using is 2.6.
#1 - Controller:
class AdminsController extends AppController {
/**
* This controller does not use a model
*
* #var array
*/
//public $uses = array('Admin');
/**
* Displays a view
*
* #return void
* #throws NotFoundException When the view file could not be found
* or MissingViewException in debug mode.
*/
public $components = array('Cookie');
public function index() {
$this->layout=false;
//echo "=users index====";
//$this->layout = 'adminlayout';
if($this->request->is('post'))
{
$username = $this->request->data['Admin']['username'];
$password = $this->request->data['Admin']['password'];
$remember_me = $this->request->data['Admin']['remember_me'];
$sql = $this->Admin->find('count',array(
'conditions' => array('Admin.username'=>$username,'Admin.password'=>md5($password))
));
//$this->Session->write('is_admin_login','Y');
if($sql>0)
{
$this->Session->write('is_admin_login','Y');
if(!empty($remember_me))
{
//*** set cookie starts
if($this->Cookie->check('username_cookie'))
{
$this->Cookie->delete('username_cookie');
$this->Cookie->write('username_cookie', $username, false, '30 Days');
}
if($this->Cookie->check('password_cookie'))
{
$this->Cookie->delete('password_cookie');
$this->Cookie->write('password_cookie', $password, false, '30 Days');
}
//*** set cookie ends
}
else
{
if($this->Cookie->check('username_cookie'))
{
$this->Cookie->delete('username_cookie');
}
if($this->Cookie->check('password_cookie'))
{
$this->Cookie->delete('password_cookie');
}
}
$this->redirect('/admin/home');
}
else
{
$this->Session->setFlash('Invalid username or password','default',array('class'=>'error_msg'));
}
}
$this->render('admin_login');
}
}
#2 - AdminLogin View
<div class="form-box" id="login-box">
<div class="header">Sign In</div>
<?php echo $this->Form->create(null, array(
'url' => array('controller' => 'Admins', 'action' => 'index')
)); ?>
<div class="body bg-gray">
<div class="row">
<div class="col-md-12 col-lg-12 col-sm-12 col-xs-12">
<?php echo $this->Session->flash(); ?>
</div>
</div>
<div class="form-group">
<?php /*?> <input type="text" name="user_name" id="user_name" class="form-control" placeholder="User ID" value="<?php // echo get_cookie("username_cookie"); ?>"/><?php */?>
<?php
$options=array();
$options['id']='username';
$options['class']='form-control';
$options['placeholder']='User ID';
$options['label']=false;
if($this->Cookie->check('username_cookie'))
{
$options['value']=$this->Cookie->read('username_cookie');
}
echo $this->Form->input('username',$options);
?>
</div>
<div class="form-group">
<?php /*?><input type="password" name="password" id="password" class="form-control" placeholder="Password" value="<?php // echo get_cookie("password_cookie"); ?>"/><?php */?>
<?php
$options=array();
$options['id']='password';
$options['class']='form-control';
$options['placeholder']='Password';
$options['label']=false;
if($this->Cookie->check('password_cookie'))
{
$options['value']=$this->Cookie->read('password_cookie');
}
echo $this->Form->input('password',$options);
?>
</div>
<div class="form-group">
<?php
$options=array();
$options['id']='remember_me';
//$options['class']='form-control';
$options['type']='checkbox';
$options['label']=false;
$options['div']=false;
$checked="";
if($this->Cookie->check('username_cookie') || $this->Cookie->check('password_cookie'))
{
$options['checked']="checked";
}
echo $this->Form->input('remember_me', $options);
?> Remember me
</div>
</div>
<div class="footer">
<button type="submit" class="btn bg-olive btn-block">Sign me in</button>
<p>Forgot my password</p>
</div>
<?php
echo $this->Form->end();
?>
<div class="margin text-center">
<!-- <span>Sign in using social networks</span>-->
<br/>
</div>
You are trying to use a Component in a view, which is why it is telling you there is no helper class called Cookie.
Use the Cookie component in your Controller action to set a variable, and then use the variable in your view:
Remove these lines from your view:
$this->Cookie->check('username_cookie')
$this->Cookie->check('password_cookie')
Use them in your controller action to set view variables ...something similar to:
$this->set('username_cookie', $this->Cookie->read('username_cookie'));
$this->set('password_cookie', $this->Cookie->read('password_cookie'));
Then you will be able to use the set variables in your view:
if(!empty($username_cookie)) {
//do something
}
//or
if(!empty($password_cookie)) {
//do something
}
I am using cakephp 2.1 and I used login action in UsersController as follows.
public function login() {
if ($this->request->is('post')) {
if ($this->Auth->login()) {
$this->redirect($this->Auth->redirect());
} else {
$this->Session->setFlash('Invalid email or password, try again', 'default/flash_error');
}
}
}
And the login.ctp code is as follows.
<?php echo $this->Form->create('User', array('class' => 'form')); ?>
<div class="control-group">
<label class="control-label" for="inputEmail">Email</label>
<div class="controls">
<?php echo $this -> Form -> text('email', array('id' => 'inputEmail', 'placeholder' => 'Email')); ?>
<?php echo $this -> Form -> error('email', null, array('wrap' => 'span', 'class' => 'help-block')); ?>
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputPassword">Password</label>
<div class="controls">
<?php echo $this -> Form -> password('password', array('id' => 'inputPassword', 'placeholder' => 'Password')); ?>
<?php echo $this -> Form -> error('password', null, array('wrap' => 'span', 'class' => 'help-block')); ?>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox"/>
Remember me </label>
<?php echo $this->Form->button('Sign in', array('type' => 'submit', 'class' => 'btn')); ?>
</div>
</div>
<?php echo $this->Form->end(); ?>
When the form get submitted with email and password, the user is not able to login so its showing an error 'Invalid email or password, try again'. Even I am passing the $this->request->data['User'] into $this->Auth->login() method and debugged $this->Session->read(Auth.User.id). Its giving me null. Please give me a solution for this.
You can try passing $this->request->data into the $this->Auth->login() method. It's not a great way to do it (see this post: CakePHP Auth Component Not logging in when using $this->Auth->login();), but it works for me. Have you debugged $this->Auth->login()?
I have two forms, one to edit room details and the other to edit Extras. Within the forms I pull in a file upload and pass in the id. For some reason one requires a url and the id does not get passed in. Both have the same code. Can see why they are differnt.
Room form
<div class="boxgrid grid_8">
<?php echo $this->element('attachments',array('control'=>'upgrades','id'=>$this->data['AddOn']['id'],'att'=>$this->data['Attachment'])); ?>
</div>
Room upload
Form->create('Room', array('type' => 'file'));?>
<legend><?php __('Upload Room Images'); ?></legend>
<?php
echo $this->Form->input('id');
?>
<input type="hidden" name="data[Attachment][0][model]" value="Room" id="Attachment0Model" />
<input type="hidden" name="data[Attachment][0][group]" value="attachment" id="Attachment0Group" />
<div class="input file required"><input type="file" name="data[Attachment][0][file]" class="" id="Attachment0File" /></div>
<div class="submit"><button>Upload</button></div>
<div>Upload files</div>
Extras Form
<div class="boxgrid grid_8">
<?php echo $this->element('attachments',array('control'=>'upgrades','id'=>$this->data['AddOn']['id'],'att'=>$this->data['Attachment'])); ?>
</div>
Extras Upload
Form->create('Upgrade', array('type' => 'file','url'=>'/admin/upgrades/addfiles','id'=>'AddOnAdminAddfilesForm'));?>
<legend><?php __('Upload Addon Images'); ?></legend>
<?php
echo $this->Form->input('id');
?>
<input type="hidden" name="data[Attachment][0][model]" value="AddOn" id="Attachment0Model" />
<input type="hidden" name="data[Attachment][0][group]" value="attachment" id="Attachment0Group" />
<div class="input file required"><input type="file" name="data[Attachment][0][file]" class="" id="Attachment0File" /></div>
<div class="submit"><button>Upload</button></div>
<div>Upload files</div>
Javascript on each form:
<script type="text/javascript">
$(document).ready(function() {
$("div#uploader").resloader();
$("div#uploader").load('<?=BASE_URL?>/admin/upgrades/addfiles/<?=$this->data['AddOn']['id']?>',null,function(){}).fadeIn();
Upgrades Contoller
function admin_addfiles($id = null) {
$this->layout = null;
if (!$id && empty($this->data)) {
$this->Session->setFlash(__('Invalid Add On', true));
$this->redirect(array('controller' => 'upgrades', 'action' => 'index'));
}
if (!empty($this->data)) {
$this->layout = null;
//if(empty($this->data['AddOn']['id'])){unset($this->data['AddOn']);}
// restructure data for uploader plugin // NEED TO GET RID OF THIS ? MOVE IT
$tmp_file = $this->data['Attachment'][0]['file'];
$tmp_file['extension'] = array_reverse(explode('.', $tmp_file['name']));
$tmp_file['extension'] = $tmp_file['extension'][0];
$tmp_file['title'] = strtolower(substr($tmp_file['name'],0,(0-strlen('.'.$tmp_file['extension']))));
$this->data['Attachment'][0]['alternative'] = ucwords(str_replace('_',' ', $tmp_file['title']));
if ($this->AddOn->saveAll($this->data, array('validate' => 'first'))) {
$id = $this->AddOn->Attachment->getLastInsertID();
$att = $this->AddOn->Attachment->query("SELECT * from attachments WHERE id = ".$id);
$this->set('attachment',$att[0]['attachments']);
} else {
$tmp_file['name'] = 'INVALID FILE TYPE';
}
//debug($this->data);
$this->set('file', $tmp_file);
$this->RequestHandler->renderAs($this, 'ajax');
$this->render('../elements/ajax');
}
if (empty($this->data)) {
$this->data = $this->AddOn->read(null, $id);
}
}
}
Your problem is with the $this->data. Check how it is filled in your controller.
Both views are NOT the same, the main difference is in the create form.
Form->create('Room', array('type' => 'file'));?>
Form->create('Upgrade', array('type' => 'file','url'=>'/admin/upgrades/addfiles','id'=>'AddOnAdminAddfilesForm'));?>
As you can see, one has the first parameter 'Room' and the other one is 'Upgrade', this IS important since you call the id like this
echo $this->Form->input('id');
Cake expects that for the first case you have something like, $this->data['Room']['id'] and the second one $this->data['Upgrade']['id']
If you pass from the controller your id variable like this
$this->set('id',$id);
then in the view you can do somthing like this
<?php
echo $this->Form->input('id', array('value'=>$id, 'type'=>'hidden'));
?>
Hope this solves your answer, if not, please post the $this->data value of each and the part of the controller where you assign $this->data
First all, I am still learning CakePHP and I am close to ZERO using JQuery.
I would like to get help for the following problem I am having:
I have an Articles_Controller a Comments_Controller and Users_Controller
Currently my articles_controller display an article and its comments are loaded on that page
Whoever user inputted the comment will also appear along with his/her image
On each comment I have added a like/dislike button.
Example:
Right now, however, I am only able to display it. What I wanted to accomplish is to use JQuery so that when a user clicks on the Thumbs Up or Thumbs Down image the like and disliked fields are automatically updated in the Db. Also, using JQuery I would like to update those same values in the View. Please my code below and thank you for your help.
articles/view.ctp
<div id="articles_comments">
<p>
Comments
</p>
<?php
foreach($comments as $comment){
?>
<div id="articles_comments_user">
<img src="<?php echo $comment['User']['image']; ?>">
<p>
<?php
$created = $comment['Comment']['created'];
echo $comment['User']['first_name'];
echo " ";
echo $comment['User']['last_name'];
echo " ";
//echo $comment['Comment']['created'];
echo $this->Time->timeAgoInWords(
$comment['Comment']['created'],
array(
'end'=>'+150 years'
)
);
?>
<p>
</div>
<div id="articles_comments_comment">
<table>
<tr>
<td style="width:85%">
<?php echo $comment['Comment']['comment'];?>
</td>
<td style="width:15%;border-left:solid thin teal;">
<div style="float:left;">
<?php echo $comment['Comment']['liked'];?>
<img width="20" src="/img/icons/thumb-up-icon.png"
</div>
<div style="float:right;margin-left:10px;">
<?php echo $comment['Comment']['disliked'];?>
<img width="20" src="/img/icons/thumb-down-icon.png">
</div>
</td>
</tr>
</table>
</div>
<?php
}
?>
<div class="articles_add_comment" id="formUpdateID">
<hr style="width:100%"><br>
<div style="float:left">
<h3>Seu Commentario:</h3>
<?php
echo $form->create(
'Comment',
array(
'url'=>array(
'controller'=>'articles',
'action'=>'view',
$article['Article']['id']
),
'class' => 'articles_form',
'id' => 'loginForm'
)
);
echo $form->input(
'Comment.comment',
array(
'label' => false,
'type' => 'textarea',
'div' => 'articles_comments_textarea',
'cols' => 90,
'rows' => 3
)
);
?>
</div>
<div style="float:right">
<?php
echo $this->Form->submit(
'Send',
array(
'class' => 'articles_comments_button'
)
);
echo $form->end();
?>
</div>
<div class="ajax-save-message">
<?php echo $this->Session->flash(); ?>
</div>
</div>
</div>
Comments is generated from the Articles View action
I was able to fix my problem by the following upon some research and try outs:
View file
<?php foreach $commments as $commment{ ?>
// .............................................................................
<td style="vertical-align:middle;border-left:solid thin teal;padding-left:5px;">
<div class="voteup" style="margin-left:10px;float:left;width:55px;">
<p style="display:none;float:left">
<?php echo $comment['Comment']['id']; ?>
</p>
<div style="float:left" id="article_thumbsUp">
<?php echo $comment['Comment']'liked'];?>
</div>
<img width="20" src="/img/icons/thumb-up-icon.png">
</div>
<div class="votedown" style="float:left;width:55px;">
<p style="display:none;float:left">
<?php echo $comment['Comment']['id']; ?>
</p>
<div style="float:left" id="article_thumbsDown">
<?php echo $comment['Comment']'disliked'];?>
</div>
<img width="20" src="/img/icons/thumb-down-icon.png">
</div>
</td>
// ...............................................................................
<?php } ?>
jQuery I used
<script>
$(document).ready(function(){
$(".voteup").click(function() {
var Id = $(this).children("p").text();
$(this).children("#article_thumbsUp").load("/comments/voteup/"+Id);
});
});
</script>
<script>
$(document).ready(function(){
$(".votedown").click(function() {
var Id = $(this).children("p").text();
$(this).children("#article_thumbsDown").load("/comments/votedown/"+Id);
});
});
</script>
And both of my actions in my comments_controller.php
function voteUp($id = null){
$this->autoRender = false;
if($this->RequestHandler->isAjax()){
$this->Comment->id = $id;
if($this->Comment->saveField('liked',$this->Comment->field('liked')+1)){
}
}
$newValue = $this->Comment->findById($id);
return $newValue['Comment']['liked'];
}
function voteDown($id = null){
$this->autoRender = false;
if($this->RequestHandler->isAjax()){
$this->Comment->id = $id;
if($this->Comment->saveField('disliked',$this->Comment->field('disliked')+1)){
}
}
$newValue = $this->Comment->findById($id);
return $newValue['Comment']['disliked'];
}
This is my entire code in detail and hopefully it can help someone else. This is the way I know how to do, and if you have any better way, I was be glad to know. Thanks a lot. THIS WORKS GREAT. I JUST NEED TO ADD A FEW MORE THINGS TO THIS SYSTEM, SUCH AS ONLY ALLOW REGISTERED USERS TO VOTE AND ONLY ONCE PER COMMENT. THAT WILL INVOLVE CREATING ANOTHER TABLE TO TRACK THAT.
Personally, I would create actions in the Comments_Controller, voteup and votedown. Then, make the thumbs up and thumbs down images link to /comments/voteup/id, etc.
After doing this, use jQuery to prevent a page reload when they're clicked, as such...
<a class="voteup" href="<?php echo $this->base;?>/comments/voteup/<?php echo $comment['Comment']['id'];?>">
<img ... />
</a>
<script>
$(".voteup").click(function(e) {
e.preventDefault();
$.ajax({
url: $(this).attr('href),
success: function() {
// Update vote counter
}
});
});
</script>
I'm sure you can piece together the rest.
I am using a Form helper in CakePHP. like
echo $form->input('field', array(
'type' => 'radio','legend'=>$r['Attribute']['label'],
// 'after' => '--after--',
// 'between' => '--between---',
'separator' => '--separator--',
'options' => array('1', '2')
));
which generates me as
<div class="input radio">
<fieldset>
<legend>Gender</legend>
<input type="hidden" value="" id="field_" name="data[field]"/>
<input type="radio" value="0" id="Field0" name="data[field]"/>
<label for="Field0">1</label>--separator--
<input type="radio" value="1" id="Field1" name="data[field]"/>
<label for="Field1">2</label>
</fieldset>
</div>
Is there any way to keep my options that i have received from my Database instead of 1,2
where i tried it with receving my options using
<?php foreach ($viewfields as $r): ?>
<script type="text/javascript">
jQuery.noConflict();
jQuery(document).ready(function($){
$("#"+<?=$r['Attribute']['id'];?>).each(function() {
type= "<?=$r['Attribute']['type'];?>";
if(type=="radio")
{
var ht = $.ajax({
type: "GET",
url: "http://localhost/FormBuilder/index.php/forms/viewChoices/"+attribute_id,
async: false
}).responseText;
var myObject = eval('(' + ht + ')');
var data = myObject;var j=0;
$.map(data.choices, function(i){ j++;
alert(i.choice);//which alerts as male and female correctly.
return i.choice;});
}
});//each
});
alert(i.choice); alerts the options correctly ..
How to keep these options in the array() of the Form Helper so that to get these options male and female instead of default 1,2
Please suggest me..
Place the options in a key => value array - as shown here : Cake Options
echo $form->input('field', array(
'type' => 'radio',
'legend' => $r['Attribute']['label'],
'separator' => '--separator--',
'options' => array('Male' => 'male', 'Female' => 'female')
));
See how you go.