Using a preAdd trigger on a hidden attribute
From Achievo/ATK Wiki
|
ATK Howto: Using a preAdd trigger on a hidden attribute
|
Contents |
Issue
I wanted to use the news table in my database for 2 sections of the website (backend and frontend). So I added a field called "is_backend" to the table "news".
The most userfriendly solution for editing this table was to create 2 nodes. I called these nodes "news_backend" and "news_site".
Because both the "news_site" and "news_backend" contained the same fields I created a base "news" node containing all the basic fields. The "news_site" and "news_backend" are extending the "news" node. I wanted to add a filter on the "is_backend" field so the right items would show up in the admin-view.
I also wanted to fill the "is_backend" field with either "0" or "1". I tried to use the preAdd functionality for this but it wasn't working the way I expected. That's why I wrote this HowTo to share the solution for this problem.
Code
See the comments in the code for an explanation.
class news extends atkNode { function news($type="news",$flags=0) { // The $type is important, otherwise the links in the admin // view will goto this node instead of to the child node $this->atkNode($type, NF_ADD_LINK); $this->add(new atkAttribute("news_id", AF_AUTOKEY)); $this->add(new atkAttribute("title", AF_SEARCHABLE)); $this->add(new atkTextAttribute("text", AF_SEARCHABLE|AF_HIDE_LIST)); // You have to add the is_backend property to the parent node // because otherwise you can't use it in the preAdd function. $this->add(new atkBoolAttribute("is_backend")); $this->setTable("news"); } }
The "news_backend" is almost the same as the "news_site" node, just replace the 1's with 0's :).
// Import the parent node, otherwise you can't extend it // "modules" is the name of the modules directory and // "inhoud" the name of the module atkimport("modules.inhoud.news"); class news_backend extends news { function news_backend() { // Call constructor of parent node with the name of the current node // so the atkNode function can be called with the right node name parent::news("news_backend"); // This filter takes care of only showing the items with the is_backend // field set to '1'. $this->addFilter("is_backend","1"); // This is basically the trick; hide the is_backend field that is created // in the parent node. $attr = &$this->getAttribute("is_backend"); $attr->addFlag(AF_HIDE); } // preAdd function, will only work if the "is_backend" field is present // and visible(!) in the parent node. function preAdd(&$record) { $record["is_backend"] = 1; } }
Comments
Feel free to correct my English grammar :).