I am trying to delete cakephp data by ajax.Here I have changed postlink button to simple html button like as
<button class="del" id=<?php echo $user['User']['id']; ?>>Delete </delete>
Here now I am able to get user id by bellow code
$('document').ready(function(){
$('.del').click(function(){
var x=$(this).attr("id");
alert(x);
});
});
I have successfully get id of the user.Now I am trying to sent it for userscontroller in delete action.So I have coded like
$('document').ready(function(){
$('.del').click(function(){
var x=$(this).attr("id");
alert(x);
jQuery.get("<?php echo $this->webroot . $this->params["users"]; ?>/delete",{"id":x},function(data,stat){
jQuery("#success").load("success.ctp");
});
});
});
Now in controller in delete action I have tried
public function delete($id=NUll) {
$id=$_GET['id'];
$this->User->id = $id;
if ($this->User->delete()) {
$this->Session->setFlash(__('The user has been deleted.'));
}
return $this->redirect(array('action' => 'index'));
}
Here it's not working.In controller how can I defined it ?
If u use before filter,
function beforeFilter()
{
//Here set Which pages should be accessable to various users
$adminPages =array('delete');
$this->Auth->allow($adminPages);
......
}
Allow it to be executed using Auth allow.
If thats also working fine,Check if AJAX string is proper. Check using MANUAL DELETE like abc.com/Users/delete/id:2 Just copy paste string u get in jQuery.get(). Does it delete properly??
IF ALL DOESNT Work TRY following : :)
public function delete($id=NUll) {
$id=$_GET['id'];
$this->User->id = $id;
if ($this->User->delete()) {
$this->Session->setFlash(__('The user has been deleted.'));
}
return $this->redirect(array('action' => 'index'));
}
And ajax :
jQuery.get("<?php echo $this->webroot . $this->params["users"].'/delete/';?>"+x+"",{"id":x},function(data,stat){
jQuery("#success").load("success.ctp");
});
Here the wrong was only url, I have changed it and now it's working fine
echo $this->webroot . $this->params["users"]; ?>/delete"
TO
echo Router::url(array('controller'=>'users','action'=>'delete'));?>"
try this if you want to use ajax
public function delete_user() {
$this->autoRender = false;
if ($this->request->data) {
$this->User->id = $this->request->data['id'];
$update = $this->User->saveField($this->request->data['field'], $this->request->data['value']);
if ($update) {
$repsonce['success'] = '1';
$this->Session->setFlash(__d('User', 'User Deleted successfully'), 'default', array('class' => 'alert alert-success'));
} else {
$repsonce['success'] = '0';
}
} else {
$repsonce['success'] = '0';
}
echo json_encode($repsonce);
}
Related
Hello everyone i am using cakephp 2.x, as i am new to here, i need to encrypt my password before it stores to database
User.ctp : I am posting like this to post
<?php
echo $this->Form->input('password',array('type'=>'password','label'=>false,'div'=>false,'class'=>'form-control','id'=>'password'));
?>
Controller:
public function setting()
{
$this->layout='setting_template';
if($this->Session->read('username')==""){
$this->redirect(array('action' => 'user_login'));
}
elseif ($this->Session->read('username') == "admin" )
{
if($this->request->is('post'))
{
$this->data['password'] = encrypt($this->data ['password']);
if ($this->Login->save($this->request->data)) {
$this->Session->setFlash('The user has been saved');
$this->redirect(array('action' => 'setting'));
} else {
$this->Session->setFlash('The user could not be saved. Please, try again.');
}
}
$opp=$this->Login->find('all');
$this->set('login',$opp);
}
else{
echo "<script type='text/javascript'> alert('Permission Denied'); </script>";
$this->redirect(array('action' => 'index'));
}
}
Login controller:
public function login()
{
$this->layout='login_template';
if($this->data)
{
$this->Session->write('id',$this->data['Login']['id'] );
$results = $this->Login->find('first',array('conditions' => array('Login.password' => $this->data['Login']['password'],'Login.username' => $this->data['Login']['username'])));
$this->Session->write('name',$results['Login']['name']);
if ($results['Login']['id'])
{
$this->Session->write($this->data['Login']['username'].','. $this->data['Login']['password']);
$this->Session->write('username',$this->data['Login']['username']);
$this->redirect(array('action'=>'index'));
}
else
{
$this->Session->setFlash("error");
}
}
How can i encrypt the password file and also how can use the Model
As you are using CakePhp go with framework's best practices.
When creating new user records you can hash a password in the
beforeSave callback of your model using appropriate password hasher
class:
App::uses('SimplePasswordHasher', 'Controller/Component/Auth');
class User extends AppModel {
public function beforeSave($options = array()) {
if (!empty($this->data[$this->alias]['password'])) {
$passwordHasher = new SimplePasswordHasher(array('hashType' => 'sha256'));
$this->data[$this->alias]['password'] = $passwordHasher->hash(
$this->data[$this->alias]['password']
);
}
return true;
}
}
You don’t need to hash passwords before calling $this->Auth->login(). The various authentication objects will hash passwords individually.
If you are using different model than User for authentication you need to define that in AppController. In your Case you need to do something like this in AppController:
$this->Auth->authenticate = array(
'Form' => array('userModel' => 'Login')
);
If you wish to hash your password, try this:
$hashedPassword = AuthComponent::password('original_password');
See Here :Cakephp Password Hashing.
I am currently doing a reset password of which is sending the following link to a user in an email
http://localhost/realestateagencyadministration/users/reset/859be257b603ce278c42dca470be642a/48/
Then the user goes to the form and the controller does the following
public function reset($resetkey = null, $id = null) {
if (!$this->User->exists($id)) {
throw new NotFoundException(__('Invalid user'));
}
$result =$this->User->find('first', array('conditions' => array('User.id' => $id, 'User.resetKey' => "'" . $resetkey . "'")));
if ($result) {
$message = __('<b>Please check your reset link</b>');
$this->Session->setFlash($message);
}
if ($this->request->is('post')) {
if ($this->User->save()) {
$message = __('Your password has been reset');
$this->Session->setFlash($message);
} else {
$message = __('Something has gone wrong. Please try later or <b>sign up again</b>');
$this->Session->setFlash($message);
}
}
else {
$this->request->data = $this->User->findByIdAndResetkey( $id, $resetkey );
$log = $this->User->getDataSource()->getLog(false, false);
debug($log);
}
}
The problem is when I submit it gives an error like so
Error: The requested address
'/realestateagencyadministration/users/reset/48' was not found on this
server.
How should I handle this?
The answer that I have found be it correct or not and if anyone has suggestions on how it should be altered do comment.
I took skywalker's suggestion and switched around the params so that id is first.
public function reset($id = null,$resetkey = null) {
and changed my save code
if ($this->request->is(array('post', 'put'))) {
$data = $this->User->findById($id);
$data['User']['password'] = $this->request->data['User']['password'];
$data['User']['resetkey'] = '';
if ($this->User->save($data)) {
$message = __('Your password has been changed, try logging in with your new password.');
$this->Session->setFlash($message);
} else {
$message = __('Something has gone wrong. Please try again later.');
$this->Session->setFlash($message);
}
}
I know it isn't clean and if anyone knows a better way it would be gratefully appreciated.
Try this:
[1] Remove trailing slash (/):
http://localhost/realestateagencyadministration
/users/reset/859be257b603ce278c42dca470be642a/48
[2] If still no success, add router statement (app/Config/routes.php), :
Router::connect('/users/reset/:resetkey/:id',
array('controller' => 'users', 'action' => 'reset'),
array('pass' => array('resetkey', 'id'))); // <-- must be in action argument order
I have following code to upload a file in cakephp
class UsersController extends AppController {
var $name = 'Users';
function index() {
$this->set('users', $this->User->find('all'));
}
function add() {
if (!empty($this->data)) {
if ($this->User->save($this->data)) {
$this->Session->setFlash('Your user data has been saved.');
$this->redirect(array('action' => 'index'));
}
$this->User->create();
if ($this->uploads() && $this->User->save($this->data)) {
$this->Session->setFlash(_('Upload saved', true));
} else {
$this->Session->setFlash(_('Upload not saved.Please try again', true));
}
}
}
function uploads() {
$uploads_dir = '/uploads';
$users = $this->request->data['Upload']['file'];
if ($users['error'] === UPLOAD_ERR_OK) {
if (move_uploaded_file($users['User']['file'], $uploads_dir)) {
$this->User->saveAll($this->data);
return true;
}
}
return false;
}
function edit($id = null) {
$this->User->id = $id;
if (empty($this->data)) {
$this->data = $this->User->read();
} else {
if ($this->User->save($this->data)) {
$this->Session->setFlash('Your user details has been updated.');
$this->redirect(array('action' => 'index'));
}
}
}
function delete($id) {
$this->User->delete($id);
$this->Session->setFlash('This user has been deleted.');
$this->redirect(array('action' => 'index'));
}
}
When I'm trying to upload, the file is uplaoding but I need the file uploaded to be viewed when the hyperlink given for each .jpeg to be displayed but I'm getting the error as
" The requested address '/Users/app/webroot/index.php/uploads' was not found on this server."
Also please help me how to store the uploaded image in another folder
PS:: code should b purely in CakePHP
Please help,
Thanks in advance
Make sure the folder used for uploading files have sufficient permissions and you can use Cakephp Media view to download files. For your reference,check this.
Downloading files using media view in CakePHP
Use image name or image id as an argument in function download and change path to
'path' => APP . 'uploads' . DS
"uploads" folder should be inside webroot directory.
can anybody tell me how to delete records from the database?
I'm done with the rest part only deletion remains. I'm running the deletion command but
the data is not deleted from the database.Actuaaly i created an action in controller(delete_user) which contains the code for deleting the user from the database.
email value is stored in a session and i'm accessing it;s value using session read function
in the next controller.
function delete_user()
{
$email=$this->Session->read('User.email');
$this->User->delete($email, $cascade = true);
echo $this->Session->delete('User.email');
echo $this->Session->delete('User.username');
$this->redirect(array('action' => 'login'));
} );
i'm creating a link in home(View) page. and it is like this.
a href='/cakephp/cakephp/Users/delete_user'>Delete Profile</a>
i'm doing it right or wrong?
Please check the online documentation first before asking such a question.
Update 18/10/12
Try using CakePhp's magic find types:
$user = $this->User->findByEmail("bob#gmail.com");
$this->User->delete($user['User']['id']);
In your controller replace following code with delete action:
public function delete($id = null) {
if (!$this->request->is('post')) {
throw new MethodNotAllowedException();
}
$this->User->id = $id;
if (!$this->User->exists()) {
throw new NotFoundException(__('Invalid user'));
}
if ($this->User->delete()) {
$this->Session->setFlash(__('User deleted'));
$this->redirect(array('action' => 'index'));
}
$this->Session->setFlash(__('User was not deleted'));
$this->redirect(array('action' => 'index'));
}
and in ctp file add the following link:
<?php echo $this->Form->postLink(__('Delete'), array('action' => 'delete', ID OF THE RECORD, null, __('Are you sure you want to delete # %s?', ID OF THE RECORD)); ?>
then your problem will be solved...
you just need to pass the id as a first parameter:
$this->User->delete($id, $cascade);
with this you can delete it without cascade:
$this->Todo->delete($this->request->data('Todo.id'));
you can hook into this befor with
function beforeDelete(){
}
and here is my full delete action:
function delete($id = null){
$this->Todo->recursive = 1;
// new
$todo = $this->Todo->read(null,$id);
if($id == null || $todo == null) {
$this->Session->setFlash('Todo existiert nicht.');
$this->redirect(array('action' => 'index'));
return;
}
$this->set('todo',$todo);
$this->Todo->delete($this->request->data('Todo.id'));
$this->redirect(array('action' => 'index'));
return;
}
I have a users controller, where if I add a user I want to redirect based on the usertype a user selects on making his account
the situation:
users table
id
name
usertype_id
The user add form has a select box for user type, I have two types of users: teachers and students (each another table, model, controller) if the user chooses teacher I want to redirect to /teachers/add/$id if the user chooses student I want to redirect to: /students/add/$id
this is what I have atm, but that doesn't work obviously
<?php
class UsersController extends AppController {
var $name = 'Users';
function add() {
if (!empty($this->data)) {
$this->User->create();
if ($this->User->save($this->data)) {
$id = $this->User->id;
if ($this->User->usertype_id=='1')
{
$this->redirect(array('students/add/'.$id));
} elseif ($this->User->usertype_id=='2') {
$this->redirect(array('teachers/add/'.$id));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.', true));
}
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.', true));
}
}
$usertypes = $this->User->Usertype->find('list');
$this->set(compact('usertypes'));
}
}
?>
I'm pretty sure the problem is the assumption that, because $this->User->id exists, $this->User->usertype_id must also exist, which it does not. I ran into that issue when I first started working with CakePHP, too. :)
If the user type was passed via the add form, you need to check the data array:
Change
if ($this->User->usertype_id=='1')
To
if ($this->data['User']['usertype_id'] == '1')
If that doesn't work (I can't remember if $this->data is emptied after a successful save) then you should store the value prior to the save, like so:
function add() {
if (!empty($this->data)) {
$usertype_id = $this->data['User']['usertype_id'];
$this->User->create();
if ($this->User->save($this->data)) {
$id = $this->User->id;
if ($usertype_id == '1') {
$this->redirect(array('students/add/'.$id));
} elseif ($usertype_id == '2') {
// the rest remains the same
Addendum
Rather than using the concatenation in your redirect, This looks cleaner to me:
$this->redirect(array('controller' => 'teachers', 'action' => 'add', $id));
But I guess that's just preference.
Addendum 2
I have some additional advice about cleaning up your controller and moving all of the logic to the model. This way you can re-use the code from other controllers in the future, and your current controller will be easier to read. I would change the entire method to look like this:
// this is in /controllers/users_controller.php
function add() {
if (!empty($this->data)) {
$saved_user = $this->User->save_user($this->data);
if ($saved_user['success']) {
$this->redirect(array(
'controller' => $saved_user['controller'],
'action' => 'add',
$this->User->id
));
}
}
$this->Session->setFlash(__('The user could not be saved. Please, try again.', true));
$usertypes = $this->User->Usertype->find('list');
$this->set(compact('usertypes'));
}
// this is in your model, /models/user.php
function save_user($data) {
$this->create;
$usertype_id = $data['User']['usertype_id'];
return array(
'controller' => ($usertype_id == '2') ? 'teachers': 'students';
'success' => $this->save($data),
);
}