简体   繁体   中英

send email on form submit only when a field has changed

I have a form to edit a job, a job has a status column which can be 1, 2 or 3

<?php echo $this->Form->input('status', array('label' => '', 'options' => $status)); ?>

When i submit the form i want to check if the value of status is equal to 3, if it is then i want to send an email. BUT i dont want to send the email if the value was 3 already.

Is there an easy way in cakephp to check the previous value to the new value etc?

Thanks.

  1. Read the existing record from the database just before you save the new one. You'd then have something to compare the new data against.

  2. Or, store the status in the session and compare the new data against it.

So when you read the record from the database, save the status in session:

$this->data = $this->Job->read(null, $id);
$this->Session->write('JobStatus.'.$this->data['Job']['id'], $this->data['Job']['status']);

When the Job is edited, you can check the new value against the old one:

if (!empty($this->data)) {
  if ($this->data['Job']['status'] == 3 && $this->Session->read('JobStatus.'.$this->data['Job']['id']) != 3) {
    /**
     * Send email
     */
  }
}

No need to mess with sessions, or indeed set the value beforehand.

Basically when you edit the record, you get the current records status value from the table. If it's already 3, we do not want to send an email, so set a boolean.

Update the record as required.

If the status was not 3, and the new status is, send the email.

I haven't filled in the whole method; but you should get the idea:

$send_email = true;    
$current_status = $this->Job->field('status');
if($current_status==3) {
    $send_email = false;
}

// save the record

if($send_email==true && $this->data['Job']['status']==3) {
   //send the email
}

您可以使用源值设置一个隐藏字段,并对照提交的值检查它的值。

<?php echo $this->Form->input('old_status', array('type' => 'hidden', 'default' => $old_status)); ?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM