Skip to content

Instantly share code, notes, and snippets.

@Da-Fecto
Created October 19, 2015 05:33
Show Gist options
  • Save Da-Fecto/cfd33085c737a7e5d1b4 to your computer and use it in GitHub Desktop.
Save Da-Fecto/cfd33085c737a7e5d1b4 to your computer and use it in GitHub Desktop.
Replace PW page variable in field descriptions and notes, eg: [Click Here]({page.parent.url}) for creating a link to the parent page.
<?php
/**
* Replace PW page variable in field descriptions and notes, eg: [Click Here]({page.parent.url})
* for creating a link to the parent page.
*
* @author adrianbj (https://gist.github.com/adrianbj/5dc1c00f1617b2639319)
*/
class DescriptionNoteVariables extends WireData implements Module {
public static function getModuleInfo() {
return array(
'title' => 'Description Note Variables',
'version' => 1,
'summary' => 'Lets you use page and other PW variables in field Description and Notes text.',
'autoload' => "template=admin",
);
}
public function init() {
$this->addHookAfter('InputfieldWrapper::render', $this, 'replaceVariables');
}
public function replaceVariables(HookEvent $event) {
$page = wire('page');
if($page->process !== 'ProcessPageEdit') return;
$process = $this->wire('process');
if($process && $process->className() == 'ProcessPageEdit') $p = $process->getPage();
// find variables identified by: page.field or page.field.subfield
if(strpos($event->return, '{page.') !== false) {
preg_match_all('/{page([^}]*)}/', $event->return, $matches);
$i=0;
$properties = array();
foreach(explode('.', $matches[1][0]) as $property) {
if($i>0) $properties[] = $property;
$i++;
}
if(count($properties) == 3) {
$replacement = $p->$properties[0]->$properties[1]->$properties[2];
}
if(count($properties) == 2) {
$replacement = $p->$properties[0]->$properties[1];
}
if(count($properties) == 1) {
$replacement = $p->$properties[0];
}
$event->return = str_replace($matches[0][0], $replacement, $event->return);
}
$event->return = $event->return;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment