send email on form submit only when a field has changed - php

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.

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
}

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.
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
*/
}
}

You can set a hidden field with the source value and check it's value against the submitted one.
<?php echo $this->Form->input('old_status', array('type' => 'hidden', 'default' => $old_status)); ?>

Related

Duplicate data on multiple clicks using random token check Laravel

I have a form where I am adding some data to db, but I want to avoid duplicate records if user clicks multiple times on the button, I can disable the button using JS but I want to have some checking on server side as well.
Currently on form I am setting a session variable with random number and sending it to controller using textbox (hidden) and then in controller I check if session variable is equal to textbox then add to db - but still the data adds multiple time in db, would appreciate if someone could help. Thanks.
Controller:
if ($request->token == session('test')){
session()->forget('test');
sleep(20); (this i added in order to test)
TableName::create([
'code' => 'test',
'name' => 'testing',
]);
return "done";
} else {
return "stopped";
}
Blade:
{{session(['test'=> rand()])}}
<input type="text" value="{{session('test')}}" name="token">
There are two methods in Laravel firstOrCreate or firstOrNew.
Refer https://laravel.com/docs/5.8/eloquent
The firstOrNew method, like firstOrCreate will attempt to locate a record in the database matching the given attributes. However, if a model is not found, a new model instance will be returned
// Retrieve flight by name, or create it with the name, delayed, and arrival_time attributes...
$flight = App\Flight::firstOrCreate(
['name' => 'Flight 10'],
['delayed' => 1, 'arrival_time' => '11:30']
);
You can check with not exist in MYSQL, check Below
INSERT INTO table_listnames (name, address, tele)
SELECT * FROM (SELECT 'Rupert', 'Somewhere', '022') AS tmp
WHERE NOT EXISTS (
SELECT name FROM table_listnames WHERE name = 'Rupert'
) LIMIT 1;

How to check if only specific table column affected in Codeigniter?

Currently, I have controller & model for form edit. If user submit different value, this will modify the value in database and if there is an affected rows, will set flash message as "success" and if same data is submitted by user without modify the value,then will set flash message as "nochange".
if($this->db->affected_rows() > 0 ) {
$this->session->set_flashdata('success','Database is updated');
redirect('registrar');
} else {
$this->session->set_flashdata('nochange','There is no changes in database');
redirect('registrar');
}
In Codeigniter, how can I check if only specific columns are affected?
For example, if my table in database have 12 columns, if user only change the value let say in column 10, then set flash message as "nochange".
If user changes values in other columns except column 10, set flash message as "success"
There is no in-built functionality in CodeIgniter or php to do this.
You would have to essentially get the entire entry before updating it. And then column by column compare the submitted value with the current value of the entry as per your required logic.
Example pseudo-code:
$q = $this->db->get_where('table', array('id' => $id))->row();
$change = false;
if ($this->input->post('col1') !== $q->col1) {
$change = true;
}
...
if ($this->input->post('col10') == $q->col10) {
$change = false;
}
$this->db->update('table', $data);

Unable to change value with codeIgniter validation

Here i have a list of contacts where user can add new contacts as well as edit them. Now at the add time i'm using server-side validation by codeIgniter for reduce redundancies. Also here i have a number of users that can add their contacts.
Suppose their are users named "John" and "Sara".
In this case, whenever "john" add new contact that are prevoiusly added by him, then it can't be add as duplicate contact number.
But whenever "john" add new contact that are previously added by "Sara", them it can be add . but its unable to add because CodeIgniter form_validation check unique value with entire table data.
Here is my Controller Code
$this->form_validation->set_rules('customer_email','Email', 'trim|check_email[customer.customer_email.' .$userId. ']', array('check_email' => 'Email must be unique.'));
$this->session->set_flashdata('check_email','Mobile must be unique');
$this->form_validation->set_rules('customer_mobile', 'Mobile', 'required|is_unique[customer.customer_mobile]');
$this->session->set_flashdata('contact_exists','Mobile must be unique');
if ($this->form_validation->run()) {
$userdata = $this->session->userdata();
$userId = $userdata['id'];
if (!$userId):
redirect(site_url());
endif;
I trying to many time but unable to fix this issue. I need your kind efforts. Thanks
Please find below solution.
First you need to remove unique check from customer_mobile.
$this->form_validation->set_rules('customer_mobile', 'Mobile', 'trim|required');
Once form_validation runs true then check customer_mobile with user in database and if it return row then return error else insert Contact.
if ($this->form_validation->run() == TRUE) {
// $check = Check here for customer_mobile with user in database
if($check):
return 'Contact already exist';
else:
// Insert Contact
endif;
}
Let me know if it not works.

Validating insert codeigniter

I'm trying to validating my insert data in codeigniter
The problem is the code returning me a duplicate entry's page error. And i want to throw that failure to home page with error message.
Here is my code:
$data = array(
'heheId' => $this->input->post('heheId'),
'userId' => $this->input->post('userId')
);
$this->db->insert('tentarasaya',$data);
if ($this->db->affected_rows() > 0){
$this->session->set_flashdata('info', "Hore sukses");
} else {
$this->session->set_flashdata('danger', "Fail insert");
}
redirect('my_home');
Any answer?
Update:
Duplicate entry like this
Try this
$data = array(
'heheId' => $this->input->post('heheId'),
'userId' => $this->input->post('userId')
);
if (!$this->db->insert('tentarasaya',$data)) { # add if here
# Unsuccessful
$this->session->set_flashdata('danger', "Fail insert");
}
else{
# Success
$this->session->set_flashdata('info', "Hore sukses");
}
redirect('my_home');
make sure that auto increment option is selected in your database. I am assuming that user_id here is a primary key, no need to insert that into a database yourself.
data = array(
'heheId' => $this->input->post('heheId'),
);
$this->db->insert('tentarasaya',$data);
Otherwise if you wish to insert user_ids yourself you can 1) define a custom call back function to check to see if the specified user id already exists in the database, 2) use the is_unique form validation rule that comes bundled with codeigniter

CakePHP how to add data from another field of a related model

This is one of my first applications out of tutorials so I don't know how to express my issue well.
Well I have these 2 tables:
User ( id, code )
Hours ( id, user_id, created)
I want to know how I can add an entry to the Hours table using the user_code.
I tried to grab the data of the User table with the code value and then findBy and pass for the patchEntity but it did not work.
I don't have a whole lot of information to work with, but I'll give it a go.
I want to know how I can add an entry to the Hours table using the
user_code
You mention using patchEntity, so that's updating information that's already there. Assuming user_code is the 'code' column you're talking about there, first find the user by his code:
$users_tbl = TableRegistry::get('Users');
// find the user
$user = $users_tbl->findByCode($user_code)->first();
if ($user) {
// replace '$this->request->data() with whatever patch data you wanted
$users_tbl->patchEntity($user, $this->request->data(), [
'associated' => ['Hours']
]
if ($users_tbl->save($user)) {
// success!
} else {
// error!
}
} else {
// error!
}
It will also depend on how you have the data you passed in (where my '$this->request->data() is, or whatever your array might be) - it needs to match the right column names and be in the correct format listed here.
However, this is updating the data. Just adding the data, you can load the hours table and add a new entry with the user_id acquired from the user search:
$hours_tbl = TableRegistry::get('Hours');
$hours = $hours_tbl->newEntity([
'user_id' => $user->id // $user populated from same method earlier
]);
/* assumed 'id' was autoincrementing and 'created' was populated
through Timestamp behavior */
if ($hours_tbl->save($hours)) {
// yay!
} else {
// boo
}

Categories