I want to prevent double post on double click on the submit button.
I have this code to save the data:
public function reply($id = null){
date_default_timezone_set('Europe/Amsterdam');
date_default_timezone_set('UTC');
$username = $this->Auth->user('username');
$authorRang = $this->Auth->user('rang');
$posts = TableRegistry::get('posts');
$threads = TableRegistry::get('threads');
$query = $threads->find('all');
$last_post_date = date('m/d/Y h:i:s a', time());
$replies = $posts->newEntity();
if ($this->request->is('post')) {
//$token = $this->request->getParam('_csrfToken');
$reply = $posts->patchEntity($replies, $this->request->data);
$reply['thread_id'] = $id;
$reply['author'] = $username;
$reply['created'] = $last_post_date;
$reply['authorRang'] = $authorRang;
$query->update()
->set(['last_post_date' => $last_post_date])
->where(['id' => $id])
->execute();
if ($posts->save($reply)) {
$this->Flash->success(__('Your reply has been saved.'));
//return $this->redirect(['action' => 'view/'.$id.'']);
}else{
$this->Flash->error(__('Unable to add your reply.'));
}
}
$this->set('reply', $replies);
}
How can I prevent it?
I have tried many things but it doesn't work. I tried to unset the entity but it does not work. It still saves the data multiple times.
Thanks
Related
I'm trying to create a log system for users add and notificate the admins when a new user has been added, asking him permissions to let the new user login.
Anyone knows if there is a plugin for it available? Or how can I save this data in two tables.
I've tried this
public function add() {
$user = $this->Users->newEntity();
$log = $this->Logs->newEntity();
if ($this->request->is('post')) {
$user = $this->Users->patchEntity($user, $this->request->data);
$user->criado_por = $this->Auth->user('nome');
$user->modificado_por = $this->Auth->user('nome');
$user->userstatus = 'waiting for permitions';
$log->date = date::now();
$log->newuser = $user->name;
$log->whocreate = $this->Auth->User('name');
if ($this->Users->save($user)) {
$this->Flash->success(__('The user has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The user could not be saved. Please, try again.'));
}
}
$this->set(compact('user'));
$this->set('_serialize', ['user']);
}
Here's a notification plugin for CakePHP: Notifier
I m having trouble in updating the student profile form,after i gave the user_id to the student profile.Every time when i try to edit the form, on saving it provide new id to the existing user. I don't know where I'm getting wrong. Plz help.Thanks in Advance.
Here is my add and edit function in Student Profiles controller:
public function add() {
if ($this->request->is('post')) {
$this->StudentProfile->create();
$data = $this->request->data;
$data['StudentProfile']['user_id'] = $this->Auth->user('id');
// code implemented below
//$this->loadModel('User');
if ($this->StudentProfile->save($data)) {
//Update user here if Profile saved successfully
//$this->StudentProfile->id = $this->Auth->user('id');
$this->Session->setFlash(__('Your account profile has been created'));
$this->redirect(array('controller' => 'studentprofiles', 'action' => 'index'));
}else{
$this->Session->setFlash(__('Your Profile was saved, but an error has occurred while updating the Users table'));
//Email your self the user ID here or something ??
}
}
$h=array(
'fields' => array('Height.height'),
'recrusive' => 0
);
$this->loadModel('Height');
$height = $this->Height->find('list',$h);
$this->set(compact('height'));
}
public function edit($id = null) {
if (!$this->StudentProfile->exists($id)) {
throw new NotFoundException(__('Invalid student profile'));
}
if ($this->request->is(array('post', 'put'))) {
$this->request->data['StudentProfile']['user_id'] = $this->Auth- >user('id');
// code implemented below
// $this->loadModel('User');
if ($this->StudentProfile->save($this->request->data)) {
//$this->StudentProfile->id = $this->Auth->user('id');
$this->Session->setFlash(__('The student profile has been saved.'), 'default', array('class' => 'alert alert-success'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The student profile could not be saved. Please, try again.'), 'default', array('class' => 'alert alert-danger'));
}
} else {
$options = array('conditions' => array('StudentProfile.' . $this- >StudentProfile->primaryKey => $id));
$this->request->data = $this->StudentProfile->find('first', $options);
}
$h=array(
'fields' => array('Height.height'),
'recrusive' => 0
);
$this->loadModel('Height');
$height = $this->Height->find('list',$h);
$this->set(compact('height'));
}
Can't believe I'm replying to my own question . Well In case anyone have the same above problem,the solution is just add the following code after this-
$this->request->data['StudentProfile']['user_id'] = $this->Auth->user('id');
// add this code to avoiding giving new id to existing user on edit:
$this->request->data['StudentProfile']['id'] = $id;
A better way of saving edited information is to set the ID on the model before the save like so
$this->StudentProfile->id = $this->Auth->user('id');
If you initiate a save after setting the above then the row will be edited and not add a new row.
i wan't to send the same mail to multiple recipients retreived from database, using zend framework 2. With my solution i can only display all emails from database but i can't send mails to them. I do not no what's the problem exactly. This is my action in the indexController:
public function eventdetailsAction() {
$id = (int) $this->params()->fromRoute('id', 0);
$this->layout()->setVariable('lang', $this->params()->fromRoute('lang', 'en_US'));
$this->layout()->setVariable('action', $this->params()->fromRoute('action', 'index'));
$request = $this->getRequest();
$aPost = $request->getPost();
if (isset($aPost['invitUser'])) {
$user = new Container('user');
$db = $this->getServiceLocator()->get('db1');
if (!$user->offsetExists('id')) {
$idconnected = '0';
} else {
$user = new Container('user');
$db = $this->getServiceLocator()->get('db1');
if (!$user->offsetExists('id')) {
$idconnected = '0';
} else {
$idconnected = $user->offsetGet('id');
$sql = "SELECT * FROM user";
$statement = $db->query($sql);
$res = $statement->execute();
if ($res instanceof ResultInterface && $res->isQueryResult()) {
$resultSet = new ResultSet;
$resultSet->initialize($res);
$message = new Message();
foreach ($resultSet as $row) {
echo $row->email . PHP_EOL;
$message->addTo($row->email)
->addTo('xxxxx#hotmail.com', 'eee#web.com')
->addFrom('xxxxx#gmail.com')
->setSubject('Invitation for the event : Event Latino');
}
// Setup SMTP transport using LOGIN authentication
$transport = new SmtpTransport();
$options = new SmtpOptions(array(
'host' => 'smtp.gmail.com',
'connection_class' => 'login',
'connection_config' => array(
'ssl' => 'tls',
'username' => 'xxxxx#gmail.com',
'password' => 'xxxxxx'
),
'port' => 587,
));
$html = new MimePart('Invitation for the event: Latin Night, orgonized by Mr. Jony Cornillon. Date : 06/04/2015');
$html->type = "text/html";
$body = new MimeMessage();
$body->addPart($html);
//$body->setParts(array($html));
$message->setBody($body);
$transport->setOptions($options);
$transport->send($message);
}
}
}
}
And this is the error displayed each time:
5.1.2 We weren't able to find the recipient domain. Please check for any
5.1.2 spelling errors, and make sure you didn't enter any spaces, periods,
5.1.2 or other punctuation after the recipient's email address. cj9sm2642949wjc.42 - gsmtp
Any help please. Thanks.
i wan't to send the same mail to multiple recipients retreived from database, using zend framework 2. With my solution i can only send email to the first row on my database, and i do not no what's the problem exactly.
This is my action in the indexController:
public function eventdetailsAction() {
$id = (int) $this->params()->fromRoute('id', 0);
$this->layout()->setVariable('lang', $this->params()->fromRoute('lang', 'en_US'));
$this->layout()->setVariable('action', $this->params()->fromRoute('action', 'index'));
$request = $this->getRequest();
$aPost = $request->getPost();
if (isset($aPost['invitUser'])) {
$user = new Container('user');
$db = $this->getServiceLocator()->get('db1');
if (!$user->offsetExists('id')) {
$idconnected = '0';
} else {
$user = new Container('user');
$db = $this->getServiceLocator()->get('db1');
if (!$user->offsetExists('id')) {
$idconnected = '0';
} else {
$idconnected = $user->offsetGet('id');
$mail = $db->query("SELECT * FROM user")->execute()->current();
print_r($mail);
exit();
$message = new Message();
foreach ($mail as $recip) {
$message->addTo($recip)
->addFrom('xxxxx#gmail.com')
->setSubject('Invitation for the event : Event Latino');
}
// Setup SMTP transport using LOGIN authentication
$transport = new SmtpTransport();
$options = new SmtpOptions(array(
'host' => 'smtp.gmail.com',
'connection_class' => 'login',
'connection_config' => array(
'ssl' => 'tls',
'username' => 'xxxxx#gmail.com',
'password' => 'xxxxxx'
),
'port' => 587,
));
$html = new MimePart('<b>Invitation for the event: Latin Night, orgonized by Mr. Jony Cornillon. Date : 06/04/2015</b>');
$html->type = "text/html";
$body = new MimeMessage();
$body->addPart($html);
//$body->setParts(array($html));
$message->setBody($body);
$transport->setOptions($options);
$transport->send($message);
}
}
}
}
And also when i put printr($mail); exit(); to show the result, only the first line will be displayed on the page. Any help please.
In the line below you are executing the query, and then obtaining the current() record from the result set the execute() call returned. That will always give you the first record in the result set.
$mail = $db->query("SELECT * FROM user")->execute()->current();
Change that to
$mail = $db->query("SELECT * FROM user")->execute();
and you should be able to iterate over the result set as expected.
i find another solution and i can succefully diplay all emails from database with print_r. However now when i put the resultset on the message->addTo(), an error will diplay. This is my new code
$sql = "SELECT * FROM user";
$statement = $db->query($sql);
$res = $statement->execute();
if ($res instanceof ResultInterface && $res->isQueryResult()) {
$resultSet = new ResultSet;
$resultSet->initialize($res);
$message = new Message();
foreach ($resultSet as $row) {
echo $row->email . PHP_EOL;
$message->addTo($row->email)
->addTo('xxxxx#hotmail.com', 'eee#web.com')
->addFrom('xxxxx#gmail.com')
->setSubject('Invitation for the event : Event Latino');
}
Any help please. Thanks.
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