Search the Community
Showing results for tags 'Hook'.
-
Hey all. This might sound a bit strange but I am looking for a solution to hook into page edit and remove or disable the two save buttons including their dropdown options. I managed to partly remove the buttons, but the dropdowns remained. However, I would prefer a solution with disabled buttons but have no idea how to achieve this. I hope somebody of you can tell me how to remove or disable these buttons. Thanks a lot in advance
-
I've spent way too much time trying to figure this out so now I just have to ask. I added an option to the save button when editing a page. What I want it to do is, when clicked, send an email out to the appropriate person, change a field on the page, then save. I have everything working up until the change a value on the page and save. I can't seem to figure out how to do this. I really don't understand what I'm doing. So far the email part works because I just smashed together various bits and pieces from the forums. Here is the hook that adds the button $wire->addHookAfter('ProcessPageEdit::getSubmitActions', function($event) { $actions = $event->return; // array of actions indexed by name $page = $event->object->getPage(); // page being edited // add a new action to process the Change of Address request if // this page uses the change of address template if ($page->template == 'Change_Of_Address' && $page->yes_no == false){ $actions['Process Form'] = [ 'value' => 'process', 'icon' => 'address-card', 'label' => '%s + Process', 'class' => '', ]; $event->return = $actions; } }); And here is the modified code that attempts to change a field value and save the page. I removed all the part that creates/sends the email. $wire->addHookAfter('ProcessPageEdit::processSubmitAction', function($event) { $action = $event->arguments(0); // action name, i.e. 'hello' $page = $event->object->getPage(); // Page that was edited/saved if($action === 'process') { $page->yes_no = true; $pages->saveField($page, 'yes_no'); $notice = new NoticeWarning("This address change has been sent to the appropriate crew."); $notice->icon = 'address-card'; $event->notices->add($notice); $event->object->setRedirectUrl('../'); } }); I get an error on the $pages->saveField line saying: Call to a member function saveField() on null Can anyone offer some help on this? If there is an easier way to do this other than using hooks and adding buttons I would welcome that as well.
-
$wire->addHookAfter('Pages::added(template=booking)', function(HookEvent $event) { $page = $event->arguments(0); $selectable_pages = $page->getInputfield('booking_group')->getSelectablePages($page); $current_group = $selectable_pages->find("template=booking_price, parent.booking_current_group=1"); $first = $current_group->eq(0); $second = $current_group->eq(1); if ($page->booking_numberofpeople->id == 1 ) { $page->setAndSave('booking_group', $first); } else if ($page->booking_numberofpeople->id !== 1 ) { $page->setAndSave('booking_group', $second); } }); I have this code in ready.php It works when i change to (Pages::save) but when (Pages::added) it doesn´t work? It sets the value to $second regardless.. Any clues? booking_group = page reference field booking_numberofpeople = select option field the options in booking_numberofpeople is 1=1 2=2 3=3 4=4 5=5 Also i have set the required value to 1. The pages are created from the module (Simple Contact Form). Please help!!
-
Hi, I want to redirect users that hit 1) pages using a specified template 2) when the url is using a specific syntax. Url syntax is: /PRODUCT/redir/PAGEID Example: /foo/redir/1234 My intention is to redirect the user to the specified PAGEID - but I don't know how to user $input in a hook. How might that be done with hooks in ready.php? $this->addHookBefore('Session::redirect', function(HookEvent $event) { $session = $event->object; // (Product template always lives a root level) if( TEMPLATE == 'product' && INPUT->urlSegment1()=='r' ) { $dest = $pages->get(PAGEID); $session->redirect( $dest->url ); } });
-
Hi PW fanatics In this post I share two of my addHookMethods for those interested. As you surely already know (if not, time to take a look at it) the Wire::addHookMethod() and the Wire::addHookProperty() API methods can be used to "breath some extra OOP" into your projects. Using addHookMethods and addHookProperty are alternatives to "Using custom page types in ProcessWire". The methods I want to share: basically the idea here is to get the URL pointing to images uploaded in the admin without writing much code in the template files. With methods like these below, it does not matter what Formatted value is set to the images, because some predefined defaults are used in all circumstances. #1 Example template file code: <?php $img_src = $latest_article->siteFeaturedImage(); ?> <img src="<?= $img_src ?>" alt="<?= $page->title ?>"> addHookMethod goes into /site/init.php <?php /* Returns URL of the original Pageimage of Article. * Image field's value can be either null (default missing image), Pageimage or Pageimages. * * @return string */ $wire->addHookMethod('Page::siteFeaturedImage', function($event) { $page = $event->object; if ($page->template != "article") { throw new WireException("Page::siteFeaturedImage() only works on 'Pages of article template', Page ID=$page is not such!"); } $article_featured = $page->getUnformatted('article_featured'); //always a Pageimages array if (count($article_featured)) { $img_url = $article_featured->first()->url; } else { $img_url = urls()->templates . "assets/img/missing-article_image.jpg"; //we show this when image is not available } $event->return = $img_url; }); ?> #2 Example template file code: <?php $img600_src = $page->siteProductImageMaxSize(600, 600, ['rotate' => 180]); ?> <img src="<?= $img600_src ?>" alt="<?= $page->title ?>"> addHookMethod goes into /site/init.php <?php /* Generates image variations for Product images. Returns URL of Pageimage. * Image field's value can be either null (default missing image), Pageimage or Pageimages. * * @param int arguments[0] Max allowed width * @param int arguments[1] Max allowed height * @param array arguments[2] See `Pageimage::size()` method for options * @return string */ $wire->addHookMethod('Page::siteProductImageMaxSize', function($event) { $page = $event->object; if ($page->template != "product") { throw new WireException("Page::siteProductImageMaxSize() only works on 'Pages of product template', Page ID=$page is not such!"); } $width = isset($event->arguments[0]) ? $event->arguments[0] : 48; //default width $height = isset($event->arguments[1]) ? $event->arguments[1] : 48; //default height $options = isset($event->arguments[2]) ? $event->arguments[2] : $options = array(); //default empty options $product_image = $page->getUnformatted('product_image'); //always a Pageimages array if (count($product_image)) { $img_url = $product_image->first()->maxSize($width, $height, $options)->url; } else { $img_url = urls()->templates . "assets/img/product-missing-image.jpg"; //we show this when image is not available } $event->return = $img_url; }); ?> BTW, you can find more examples here: How can I add a new method via a hook? Working with custom utility hooks Adding array_chunk support to WireArray addHookProperty() versus addHookMethod() Have a nice weekend!
-
Hi I'm working with PW for some time now, but – please don't laugh – never used hooks. I have 200 – 300 subpages with the template 'artist', the title of each page represents the full name, sometimes John Doe, sometimes John Emmet Brown Doe. I want to auto-populate the field 'artist_last_name' with the word that is most likely the last name, the last word of the page title. If there are more names, it can be changed manually. I need this for easier and quicker alphabetical sorting. What I put together is this, in ready.php. Doesn't work. Again, I'm new to hooks.. <?php $wire->addHookBefore('Pages::saved', function(HookEvent $event) { $p = $event->arguments('page'); if($p->template != 'artist') return; if($p->artist_last_name) return; $ln = end(explode(' ', $p->title)); $p->set('artist_last_name',$ln); }); ?> In the best case this would be done once globally without having to open and save every page. But new pages should populate the field on page save. Thanks for your help, I think it's easy, I just need a push.. Nuél
-
I use a PageTable field to make edits to children of pages more intuitive… To register the hooks, insert the following Snippet inside your init function in your module (or add it to your init.php file): /** * Initialize the module. * * ProcessWire calls this when the module is loaded. For 'autoload' modules, this will be called * when ProcessWire's API is ready. As a result, this is a good place to attach hooks. */ public function init() { // Prefill pageTable field $this->wire()->addHookBefore('InputfieldPageTable::render', $this, 'addChildrenToPageTableFieldsHook'); $this->wire()->addHookBefore('InputfieldPageTableAjax::checkAjax', $this, 'addChildrenToPageTableFieldsHook'); } Then, add this hook method: /** * Fill pagetable fields with children before editing…. * * @param HookEvent $event */ public function addChildrenToPageTableFieldsHook(HookEvent $event) { $field = $event->object; // on ajax, the first hook has no fieldname if (!$field->name) { return; } // get the edited backend page $editID = $this->wire('input')->get->int('id'); if (!$editID && $this->wire('process') instanceof WirePageEditor) { $editID = $this->wire('process')->getPage()->id; } $page = wire('pages')->get($editID); // disable output formating – without this, the ajax request will not populate the field $page->of(false); // you could also insert a check to only do this with sepcific field names… // $page->set($field->name, $page->children('template=DesiredTemplate')); // just specific templates $page->set($field->name, $page->children); } Now whenever there is a page-table field on your page, it gets populated with the children
-
So hello i am trying to get a .png file from file field and put it automatically to image field, why png image is in the file field is because i already have a hook that extracts .zip and uploads all content into file field, but i just realizes i cant use size() function on image in file field so i am tryin got reupload it to images field i already have something like this in ready.php $word = ".png"; foreach($page->subor_hry as $file) { if(strpos($file, $word) !== false){ $page->images_thumb = $file->url; } } by my logic it should work but it dosnt i get error ProcessPageEdit: Unable to read: /site-hry/assets/files/1027/flash_fishy_screenshot.png when i remove url from $file->url i just get ProcessPageEdit: Item added to ProcessWire\Pageimages is not an allowed type so what am i doing wrong? is there some other way to do this ? also can i have all this in $this->addHookAfter('Pages::saveReady', function(HookEvent $event) { whats the correct function to have it apply on all pages ?
-
Hi! I am trying to create a hook that takes the value of a form file field, and add it to an image gallery of an existing page. $forms->addHookBefore('FormBuilderProcessor::processInputDone', function($e) { $form = $e->arguments(0); if($form->name == 'new-inuse') { // related_font is a page selector $font = $form->getChildByName('related_font'); // getting the page name $fontName = $font->attr('value')->name; // finds the page from its name $fontPage = wire('pages')->find("name=$fontName"); // in_use_image is a file upload field $image = $form->getChildByName('in_use_image'); // trying to add the image to the existing image gallery in_use field $fontPage->in_use->add('$image'); // error here $fontPage->save(); } }); This outputs the following error: `Call to a member function add() on null`. Any idea what’s wrong with my code?
-
hooks, get MD5 and stuff from .xml and output into fields
picarica posted a topic in API & Templates
so what i am trying to do is that i uploded some files into file field, and then i want hook to get MD5sum and other stuff from .xml and put it into text field into it coresponding pages, pages like this are gonna be many, for each one i want it to output it into its fields -
Hi there. I wrote a custom module for one of my projects. In fact I maybe want to use my module in other projects too. In order to be variable and customizable I need to implement some custom hooks into my module. So I can afterwards hook into the my functions in order to modify them to match the needs of the new project. I tried simply defining functions with the '__' prefix. But that did not work. I'm imagining something like the following: <?php class MyClass { public function ___someFunction() { // Do something } } // ready.php $this->addHookBefore('MyClass::someFunction', function($event) { // some customization }); Is there a way to accomplish that?
-
Hello so am trying to make a hook so that all checkbox field is defaul;ty checked when making new page, soo i made hook in init.php and the contents are <?php $wire->addHookAfter("Pages::added", function($event) { $page = $event->arguments(0); // check for page template if necessary here $page->checkboxfield('check', 1); }); ?> and what i get which is weird because "table" is a repeat field where checkboxfield is nowhere present, but table repeat field and checkboxfield are in the same template, so why does it outputs error like that? any ideas ?
-
Hi folks, i try to use a hook to change some markup inside admin, this hook works fine inside a ready.php file, but its not working inside my module: <?php namespace ProcessWire; class InputfieldPageTableExtendedGrid extends InputfieldPageTable { public static function getModuleInfo() { return array( 'title' => __('Inputfield for PageTableExtendedGrid', __FILE__), // Module Title 'summary' => __('Adds Inputfield for PageTableExtendedGrid', __FILE__), // Module Summary 'version' => 233, 'requires' => array('FieldtypePageTableExtendedGrid'), 'permanent' => false, ); } public function ready() { $this->addHookAfter('Page::render', function($event) { $value = $event->return; // Return Content $style = "<style type='text/css'>". $this->pages->get((int) wire('input')->get('id'))->style ."</style>"; // Add Style inside bottom head $event->return = str_replace("</head>", "\n\t$style</head>", $value); // Return All Changes }); } } whats wrong here?
-
Hello Till now I hacked something with the twig template but it works no more with new PW versions so I look forward to create a module. I am working on a site in multiple languages : French, English, Italian, German, Spanish, Portuguese, Hebrew, Russian. The new posts are entered in any language with a field for language. Till now, I got twig files to get the translations with constants defined for each part of the pages. So I'd like to create a module to include theses files added according to the url /fr/en/... Have you some observations to do before I begin about the direction to take ? Thank you
-
Hello, I have a hook in a custom method of a non autoload module and it is not calling my hook method. In the wiki I read Modules that are intended to attach hooks in the application typically should be autoload because they listen in to classes rather than have classes call upon them. If they weren't autoload, then they might never get to attach their hooks. Does this mean that hooks are only working in autoload modules? I added 'singular' => true and 'autoload' => true to getModuleInfo() but still my hook funktion does not get called. My hook call at the end of this render method $this->inlineScript = $inlineScript; $page->addHookAfter('render', $this, 'addInlineScript'); $page object is available. Also tried $this->addHookAfter('Page::render', $this, 'addInlineScript'); and my hook method public function addInlineScript($event) { exit("gbr"); // $value contains the full rendered markup of a $page $value = $event->return; $value = str_replace("</body>", $this->inlineScript . "</body>", $value); // set the modified value back to the return value $event->return = $value; } Why is this not working? Any help would be much appreciated.
- 14 replies
-
- hook
- non autoload
-
(and 1 more)
Tagged with:
-
Hello all, wasn't sure where to put this, so it goes in General section. Ryan shows a hook that we can use to mirror files on demand from live server to development environment to be up to date with the files on the server without having to download complete site/assets/files folder. I just implemented this but had problems getting files to load from a site in development that is secured with user/password via htaccess. First I tried to use WireHttp setHeader method for basic authentication like this function mirrorFilesfromLiveServer(HookEvent $event) { $config = $event->wire('config'); $file = $event->return; if ($event->method == 'url') { // convert url to disk path $file = $config->paths->root . substr($file, strlen($config->urls->root)); } if (!file_exists($file)) { // download file from source if it doesn't exist here $src = 'http://mydomain.com/site/assets/files/'; $url = str_replace($config->paths->files, $src, $file); $http = new WireHttp(); // basic authentication $u = 'myuser'; $pw = 'mypassword'; $http->setHeader('Authorization: Basic', base64_encode("$u:$pw")); $http->download($url, $file); } } But, unfortunately this didn't work. So now I am using curl to do the download. My hook function now looks like this function mirrorFilesfromLiveServer(HookEvent $event) { $config = $event->wire('config'); $file = $event->return; if ($event->method == 'url') { // convert url to disk path $file = $config->paths->root . substr($file, strlen($config->urls->root)); } if (!file_exists($file)) { // download file from source if it doesn't exist here $src = 'http://mydomain.com/site/assets/files/'; $fp = fopen($file, 'w+'); // init file pointer $url = str_replace($config->paths->files, $src, $file); $u = 'myuser'; $pw = 'mypassword'; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_TIMEOUT, 50); // crazy high timeout just in case there are very large files curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_USERPWD, "$u:$pw"); // authentication curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); // authentication curl_setopt($ch, CURLOPT_FILE, $fp); // give curl the file pointer so that it can write to it curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); $data = curl_exec($ch); curl_close($ch); } } Now I can load files and images from the htaccess protected development server ? If anyone knows how to get this to work with WireHttp, please let me know. Thank you.
-
I'm trying to update certain repeater fields with a hook. This almost works, but is somehow buggy. Each repeater is supposed to represent a row: service, remarks, number of days, day-rate, row total. The last repeater should then show the grand total. I've tried this: $this->addHookAfter("Pages::saveReady", function (HookEvent $event) { $page = $event->object->getPage(); if ($page->template->id == 89 && $page->parent->parent->id == 11180) { $repeater = $page->offer_calc_repeater; $itemCount = $repeater->count(); $c = 0; $grandTotal = 0; foreach ($repeater as $rep) { if($c < ($itemCount - 1) ) { if (!empty($rep->days) && !empty($rep->daily_rate)) { $num_days = $rep->days; $day_rate = $rep->daily_rate; $row_total = $num_days * $day_rate; $rep->row_total = $row_total; $grandTotal = $grandTotal + $row_total; $page->save(); unset($num_days); unset($day_rate); unset($row_total); $c++; } } if ($c == $itemCount) { $rep->row_total = $grandTotal; } } } }); Most calculations are correct, but: The first one is empty. The second one is calculated wrong. I've tried typecasting (float), or checking with strlen instead of !empty, but that doesn't make any difference. Is the Pages::saveReady the ideal hook for such stuff? (placed in site/ready.php). Also, I get an error message: Session: Method Pages::getPage does not exist or is not callable in this context. Any ideas? Would you perhaps rather do stuff like this via JS?
- 6 replies
-
- pages::saveready
- hook
-
(and 1 more)
Tagged with:
-
Hello! The only hook into 'trash' in a module runs twice, by itself, as it seems. The following code outputs: Session: Hooked 1 times on abcd Session: Hooked 2 times on abcd on the admin side when one page is deleted from it's delete tab. And it's no matter 'addHookBefore', 'addHookaAfter' or 'addHook' method is used. Why?! private $i = 0; public function init() { $this->pages->addHookBefore('trash', $this, 'test'); } public function test($event) { $page = $event->arguments('page'); $this->i++; $this->message("Hooked {$this->i} times on {$page->title}"); }
-
Searching a ProFields Table from within ready.php hook code
JayGee posted a topic in API & Templates
I've created a simple sports league fixture generator in a template called 'League'. Teams are added as page references then a fixture list is created as a ProFields table by hooking page save to add new rows to the table. The bit I need help with is that I'm trying to check a fixture doesn't already exist before adding it to the table (e.g. if a new team is added to the league). I'm trying to do this with a PW selector to filter the fixtures table and check whether Team A vs Team B already exists in the table. Then on the next line checking no fixture was found by using count(). However as soon as I add the selector the script no longer adds any rows to the table. If I take it out, it all works fine (albeit with duplicate fixtures each time the page is saved). I've also tested the selector in a page template and it filters as expected. It's late here (UK)... I'm probably doing something stupid! Any ideas? <?php //Hook page save to generate league fixture lists $wire->addHookAfter("Pages::saved(template=league)", function ($event) { //Get which page has been saved $page = $event->arguments(0); $noFixturesAdded = 0; //For each team in league cycle through and add home fixtures foreach ($page->teams_in_league as $teamA) { foreach ($page->teams_in_league as $teamB) { //Check if fixture already exists $existingFixtures = $page->fixtures("team_a=$teamA,team_b=$teamB"); //Check team A is not the same as team B as you can't play yourself //Then add row to fixture table if ($teamB != $teamA && $existingFixtures->count() < 1 ) { $fixture = $page->fixtures->makeBlankItem(); $fixture->team_a = $teamA->id; $fixture->team_b = $teamB->id; $page->fixtures->add($fixture); $noFixturesAdded ++; } } } //Save updates to table $page->save('fixtures'); $message = "League saved. $noFixturesAdded new fixtures were added"; $this->message($message); }); -
It's a bilingual site. There are two pages: "Artists" and "Events" each with a "Page Reference" field connecting each other. - Artists has a field where one can choose events available. - Events has a field where you can either choose artists available or create new ones. The problems: - When I create an "Artist" page and select events from the list, it doesn't update the collection of participating artists on the "Event" page. - When I create an artist from the "Event" page. The field 'artist page > settings > language' is not "Active" for the second language. When the artist page is created manually,"Active" is on by default. I know this all have to do with hooks, but I'm don't fully understand the logics.
-
Hello forum! I started to write my first hook for Processwire but I'm pretty confused how you should write these. My idea is to hook after publishing in init.php (called before templates) for a certain template. Here's the code: Trying to reset the checkbox (ajasta) and then saving it so it shows unchecked in the admin page when publishing "article" page. But the code isn't doing anything. Not even dumping anything What seems to be the problem? And have you made a similar hook for this usage or am I doing it totally wrong? ? Thanks for the support in advance!
-
In a project I had to add the attribute 'disable' to some options of a select field (page reference) to show them but make them unselectable. Since I could not find an integrated solution, I wrote a tiny module and a hook. This could also be a POC to similar needs. Install module Add the Module to InputfieldPage in the module settings to make it selectable as Inputfield for page reference fields Create a hook in ready.php to manipulate attributes of the <option> tag for specified items Module <?php namespace ProcessWire; /** * POC Inputfield Select Hook Add Option -- Replacement for InputfieldSelect * * Selection of a single value from a select pulldown. Same like InputfieldSelect * except this version provides hookable addOption() function which allows to modify * attributes of the <option> tag (i. e. 'disabled' to show items but disallow to select them * * @author Christoph Thelen aka @kixe * */ class InputfieldSelectHookAddOption extends InputfieldSelect { /** * Return information about this module * */ public static function getModuleInfo() { return array( 'title' => __('Select Hookable Add Option', __FILE__), // Module Title 'summary' => __('Selection of a single value from a select pulldown. Same like InputfieldSelect. except this version provides hookable addOption() function which allows to modify attributes of the <option> tag (e.g. \'disabled\' to show items in dropdown but disallow to select', __FILE__), // Module Summary 'version' => 100, ); } /** * Hook in here to modify attributes */ public function ___addOptionAttributes($value, $label) { return array(); } /** * @see InputfieldSelect::addOption() * */ public function addOption($value, $label = null, array $attributes = null) { if (!is_array($attributes)) $attributes = array(); $attributes = array_merge($attributes, $this->addOptionAttributes($value, $label)); return parent::addOption($value, $label, $attributes); } } Hook /** * This example hook modifies the attributes of the selectable options of a Pagereference field named 'test'. * The selectable pages have the template 'test' assigned which includes a checkbox 'disallow'. * The attribute 'disabled' will be added to the selectable page if the user does not have the role 'user-extended' and 'disallow' is set. * */ $wire->addHookAfter('InputfieldSelectHookAddOption::addOptionAttributes', function($e) { // quick exit if ($e->object->name != 'test') return; if ($this->wire('user')->isSuperuser()|| $this->wire('user')->hasRole('user-extended')) return; // disable items (pages) in select $restrictedPageIDs = $this->wire('pages')->find('template=test,disallow=1')->each('id'); if (in_array($e->arguments[0], $restrictedPageIDs)) $e->return = array('disabled' => 'disabled'); });
- 3 replies
-
- 4
-
-
- inputfieldselect
- hook
-
(and 1 more)
Tagged with:
-
Hello, I am getting nuts trying to understand hooks and I hope someone in the community will be able to help. This is deiving me crazy ! I have tested tens of possibilities to eventually reduce my code to this : bd('outside'); $wire->addHookAfter('Page::render', function($event) { bd('inside'); }); And if someone could tell me why my bd('inside'); never triggers... I would be infinitely grateful ! EDIT : Forgot to say : this piece of code is in my _init.php included in my template (but I've also tried in my site/ready.php for no better results...)
-
Is there a hook to do something right after cloning a page ? I want the page to be saved right after cloning it either from the button in the tree or from a lister, because saving the page triggers several calculations that are not triggered by just cloning the page. Thanks in advance !
-
Hi! tell me, pls, how to execute this equality (from ready.php) $wire->addHookAfter('InputfieldPage::getSelectablePages', function($event) { if($event->object->hasField == 'FIELDNAME') { ..... } } - $hasField The Field object associated with this Inputfield (from definition parent class for InputfieldPage) the left side equation is the object entity, and the right side - the string How it is?