purwa-astawa
11/8/2013 - 1:04 PM

Processwire: auto subpages

Processwire: auto subpages

<?php
class Elections extends WireData implements Module {

public static function getModuleInfo() {
  return array(
   'title' => 'Elections',
   'version' => 101,
   'summary' => 'Simple module to demonstrate how to automatically create subpages.',
   'singular' => true,
   'autoload' => true,
   );
}

public function init() {
  // add a hook after the $pages->save
  $this->pages->addHookAfter('save', $this, 'afterPageSave');
}

public function afterPageSave($event) {
  $page = $event->arguments[0];
  // We want to create subpage only when using
  if ($page->template == 'election' && $page->numChildren == 0) {
   $p = new Page();
   $p->template = $this->templates->get("candidates");
   $p->parent = $page;
   $p->title = "Candidates";
   $p->sortfield = wire('fields')->get('v_candidate_number');
   $p->save();
  
   $p2 = new Page();
   $p2->template = $this->templates->get("votes");
   $p2->parent = $page;
   $p2->title = "Votes";
   $p2->save();
   $this->message("New election created.");
  }
}
}