How to update READONLY values in ATK
Mini-Howto (ATK tip) - How to update READONLY values in ATK
Problem: If you use the AF_READONLY flag in ATK so that the user cannot modify a record’s value, you may run into problems when you are trying to update that attribute prior to inserting to the database.
To keep track of changes on a record some developers add a “modified_date” field to the database table and update that field every time a change is made by the user.
Say you have the following ATK code:
$this->add(new atkDateAttribute("modified_date","m/d/y","m/d/y",0,0, AF_HIDE_ADD | AF_READONLY));
By using the AF_READONLY flag, you are instructing ATK that whenever the value for this record is displayed, the user should only be allowed to view it and not change it. The AF_HIFE_ADD flag simply hides the “modified_date” field during the creation of a new record.
To place the date on the field prior to updating the database you would use the preUpdate() function:
// update field before saving
function preUpdate(&$record)
{
// before we update the record, let's get today's date and added to the modified_date field
$record['modified_date'] = date('Y-m-d');
return true;
}
As correct as it may seem, this will not update the “modified_date” field on the database, unless you instruct ATK to specifically do so.
Solution:
This problem can be easily solved by using the setForceUpdate() function.
The following code on your constructor will effectively allow you to update the record on the database, while allowing users to view it without the possibility of altering it:
$modified_date = &$this->add(new atkDateAttribute("modified_date","m/d/y","m/d/y",0,0, AF_HIDE_ADD | AF_READONLY));
$modified_date->setForceUpdate(true); // for field to be updated on database after edit function
Say you have a node named “order” on a file called “class.order.inc” then your node skeleton code to update your AF_READONLY field would look as follows:
useattrib("atkdateAttribute");
class order extends atkNode
{
function order(){
$this->atkNode("order",NF_ADD_LINK | NF_TRACK_CHANGES);
$modified_date = &$this->add(new atkDateAttribute("modified_date","m/d/y","m/d/y",0,0, AF_HIDE_ADD | AF_READONLY));
$modified_date->setForceUpdate(true); // for field to be updated on database after edit function
$this->setTable("order");
}// end function
// update field before saving
function preUpdate(&$record)
{
// before we update the record, let's get today's date and added to the modified_date field
$record['modified_date'] = date('Y-m-d');
return true;
}// end function
}// end class
Closing remarks:
The code demonstrated here was tested on ATK 5.5. Prior to this version I was using a custom trick to accomplish the same job. This way of doing is far more elegant.
Copied by WayneH from FORUM post by - Jorge Garifuna Professional Web Developer Your Web Solution Partner http://www.GariDigital.com