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

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);

Related

Creating an auto incremented id when user submits a form

Currently I have a refno. column in my database with the format LP00001. Now I have a add page that inserts all data that the user inserts in the input field and all this data gets sent to a table in my database, but my refno column stays null which I want to have an auto incrementing value where the last 5 digits will be +1 everytime the user submits the form.
I do not want to have it be shown before the submit button as 2 users can be on that page at the same time which means they both will get the same id which means it has to generate it only at the time of submit. Currently this is my code:
Controller class:
if ($this->form_validation->run() == FALSE)
{
$main['page'] = 'crm/listings/add';
$this->load->view('crm/index', $main);
}else {
$maindata=array('clients_id'=>$this->session->userdata('clientsessid'),
'property_for'=>$this->security->xss_clean($this->input->post('property_for')),
'property_type'=>$this->security->xss_clean($this->input->post('property_type')));
$insertid=$this->listings_model->insert_listing($maindata);
if($insertid){
$this->session->set_flashdata('message', '<div>Successfully</div>');
redirect('listings/sales');
Model Class:
function insert_listing($maindata){
$this->db->insert("crm_listings",$maindata);
$prime=$this->db->insert_id();
return $prime;
}
So I assume I'll need to do this in my model class function insert_listing since that is called when I press submit button. Here another thing will be that the model will have to check what was the last entry in the database that has to be incremented for which I'm assuming I'll have to use echo str_replace("LP","","LP00001");
I guess you just have to prepend the initials LP to the returned autoIncremented id.
function insert_listing($maindata){
// ...
$this->db->set("refno", "LP". sprintf('%05d', $prime));
$this->db->where('id', $prime);
$this->db->update("crm_listings");
return $prime;
}

Dynamically set value for a grid column while csv export:-Laravel-admin

I have a user grid it has got a column (status) which is a dynamically created html based on another model value .When trying to export the columns as listed in the grid ,is there anyway to check the model value and set the specified column dynamically. The column 'status; has not saved in the database.
Tried the following
$grid->export(function ($export) {
$export->filename('Filename.csv');
$export->column('status', function ($value, $original) {
// currently $value = 'html tag' and $original is empty
$value = $this->status_flg === '1' ? 'Opened' :'Closed'; //Not working.
return $value;
});
});
In the above code i could not access the model value status_flg .

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
}

How to perform update for each users in table at different time stamp in codeigniter?

For a CRM System In Codeigniter I Have A Admin module which add the balance to reselle. Now reseller has an option to view his own users and he can add to remove balance. Now if have a radio button on editing that balance is either Yes or No.Here i know the logic but don't know how to implement the below: One the reseller edits a user and sets the balance to yes i want to count 30 days, after 30 days the balance would be reset to no. So i think i should fetch all the users and check when thier balance was set to yes. if its already 30 days then i have a update cron job file which will reset the balance to No. Now i dont know how to do this? how could i check each user? i am very confused about the code and logic. Below is my code to edit the User.
public function edit ($id = NULL)
{
$usertype=$this->session->userdata('usertype');
if($usertype ==="reseller")
{
// Fetch a user or set a new one
if ($id) {
$this->data['user'] = $this->user_m->get($id);
count($this->data['user']) || $this->data['errors'][] = 'User could not be found';
}
else {
$this->data['user'] = $this->user_m->get_new();
}
// Set up the form
$rules = $this->user_m->rules_admin;
$id || $rules['password']['rules'] .= '|required';
$this->form_validation->set_rules($rules);
// Process the form
if ($this->form_validation->run() == TRUE) {
$data = $this->user_m->array_from_post(array('sip_id','sip_pass','name','email', 'password','phone','status','created','balance'));
$data['password'] = $this->user_m->hash($data['password']);
$this->user_m->save($data, $id);
redirect('reseller/user');
}
// Load the view
$this->data['subview'] = 'reseller/user/edit';
$this->load->view('reseller/_layout_main', $this->data);
}
else{
$this->load->view('permission');
}
}
the Reseller:
The User Table:
Trigger example for your database (MySQL):
CREATE TRIGGER resetBalance
BEFORE UPDATE ON your_table_name
IF new.balance = "yes" THEN
SET NEW.reset = ADDDATE(curdate(), INTERVAL 30 DAY);
End IF
UPDATE:
Let's say, you have a field in your db called balance, where you store the value yes or no. (I would prefer here a boolean type.)
And let's say, that you have a field called reset, where you save the resetdate for the balance. The reset field should be a datetime.
If you make an update to any balance field and the «new» entry of the balance field is yes, the database will insert in the reset field the current date + 30 days.
New means the new entry which you save in the db, there is also an old value. That is the value, which was before updating in the column.
That's all.
In your cron, you just check the reset field, do some logic or what ever and delete the value in the reset field.
UPDATE 2:
I just saw, that you have a created and modified field in your db. Here is also the best way to use triggers.
Before Insert:
set new.created = NOW();
Before Update:
set new.modified = NOW();
UPDATE 3:
Today is trigger-day ;-))
Let's say you have a tblUsers and a tblResellers. In the tblResellers you would like to set a reset date, based on a balance field in tblUsers. Then you should create a Trigger in tblResellers like this:
BEGIN
set #userBalance = (SELECT balance FROM tblUsers WHERE id = old.userid);
IF #userBalance = "yes" THEN
SET NEW.reset = ADDDATE(curdate(), INTERVAL 30 DAY);
ELSE
SET NEW.reset = "";
END IF;
END
In the second row, I define a variable «userBalance» which gets its value from tblUsers. In the where clause I use a field from tblResellers (userid), which is corresponding with an ID in tblUsers.
The rows above are easy: Checking the value of userBalance, make some decisions and set the reset date.
I think this trigger will match not all your needs, but you get a feeling of how to do it. If you change the code, make it step by step, to debug triggers is a little bit tricky.

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.
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)); ?>

Categories