Skip to content

Commit

Permalink
feat: add magic field methods
Browse files Browse the repository at this point in the history
  • Loading branch information
BernhardBaumrock committed Mar 19, 2023
1 parent 1ae3a5d commit 60eb61e
Showing 1 changed file with 49 additions and 0 deletions.
49 changes: 49 additions & 0 deletions MagicPages.module.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use ProcessWire\HookEvent;
use ProcessWire\Module;
use ProcessWire\Page;
use ProcessWire\PageArray;
use ProcessWire\Paths;
use ProcessWire\RockMigrations;
Expand Down Expand Up @@ -63,13 +64,61 @@ public function ready()
foreach ($ready as $p) $p->ready();
}

/**
* Attach magic field methods
* Makes it possible to access field "foo_bar_baz" as $page->baz()
* This is very useful when creating fields with long prefixed names to
* avoid name collisions. Its primary use was for RockPageBuilder but it
* was moved to MagicPages later as it turned out to be very useful.
*/
public function addMagicFieldMethods(Page $page)
{
$tpl = $page->template;
$fields = $tpl->fields;
foreach ($fields as $field) {
$fieldname = $field->name;
$parts = explode("_", $fieldname);
$methodname = array_pop($parts);

// add the dynamic method via hook to the page
$this->wire->addHookMethod(
"Page(template=$tpl)::$methodname",
function ($event) use ($fieldname) {
// get field value of original field
$page = $event->object;
$raw = $event->arguments(0);
if ($raw === 2) {
$event->return = $page->getUnformatted($fieldname);
return;
}
if ($raw) {
$event->return = $page->getFormatted($fieldname);
return;
}
$val = $page->edit($fieldname);
if (is_string($val)) {
/** @var RockFrontend $rf */
$rf = $this->wire->modules->get('RockFrontend');
if ($rf) $val = $rf->html($val);
}
$event->return = $val;
},
// we attach the hook as early as possible
// that means if other hooks kick in later they have priority
// this is to make sure we don't overwrite $page->editable() etc.
['priority' => 0]
);
}
}

/**
* Add magic methods to this page object
* @param Page $magicPage
* @return void
*/
public function addMagicMethods($magicPage)
{
$this->addMagicFieldMethods($magicPage);

if (method_exists($magicPage, "editForm")) {
$this->wire->addHookAfter("ProcessPageEdit::buildForm", function ($event) use ($magicPage) {
Expand Down

0 comments on commit 60eb61e

Please sign in to comment.