Jump to content

Search the Community

Showing results for tags 'hook'.

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


Forums

  • Welcome to ProcessWire
    • News & Announcements
    • Showcase
    • Wishlist & Roadmap
  • Community Support
    • Getting Started
    • Tutorials
    • FAQs
    • General Support
    • API & Templates
    • Modules/Plugins
    • Themes and Profiles
    • Multi-Language Support
    • Security
    • Jobs
  • Off Topic
    • Pub
    • Dev Talk

Product Groups

  • Form Builder
  • ProFields
  • ProCache
  • ProMailer
  • Login Register Pro
  • ProDrafts
  • ListerPro
  • ProDevTools
  • Likes
  • Custom Development

Find results in...

Find results that contain...


Date Created

  • Start

    End


Last Updated

  • Start

    End


Filter by number of...

Joined

  • Start

    End


Group


AIM


MSN


Website URL


ICQ


Yahoo


Jabber


Skype


Location


Interests

  1. 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.
  2. $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!!
  3. 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 ); } });
  4. 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
  5. 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 ?
  6. 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?
  7. 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
  8. 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?
  9. 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 ?
  10. 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?
  11. 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
  12. 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.
  13. 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); });
  14. 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.
  15. 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!
  16. 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...)
  17. 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 !
  18. 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?
  19. Hey, I want to hook into the 404 handling of PW at the most earliest stage. Pleas can anybody point me to the hook or file that suits this best?
  20. Hi, I have a page with a repeater called teams with two fields: team (a pageReference with a list of teams) and people (a pageReference with a list of people who likes this team). I'm trying to populate the people field in the repeater according to the value of the team field in the same repeater. So far. I'm able to get the pageArray that I want to assign to the people field, but i don't know how to "save" the value for each instance of the repeater. I hope somebody can give me a light. Thanks in advance. $wire->addHookAfter('InputfieldPage::getSelectablePages', function($event) { if($event->object->hasField == 'people') { $repeaterField = $event->arguments('page')->teams; foreach ($repeaterField as $t) { // Is this the way to loop the instances of the repeater? $team = $t->team->id; $t->people = $event->pages->find("template=user, team={$team}"); var_dump($t->people); // This returns the values that i want to assign for each repeate instance $event->return = $t->people; // I hope this assign a custom pageArray for each repeater, but it assigns the same for all the instances of the repeater } } });
  21. Hello, I am not that experienced with hooks and was hoping if somebody could me with this task: I have a InputfieldFile in wich a single generated file will be added after checking a checkbox in the back-end and saving the page. This happens in the saveReady-hook of a page with a specific template inside a ready.php: <?php $this->addHookAfter("Pages::saveReady", function($event) { $page = $event->arguments(0); if ($page->template->name === "example") { if ($page->checkboxField) { $page->fileField->add($generatedFile); } } }); Now if a new file should be generated and there is already a file in this InputfieldFile, I would like to remove the previous file and replace it with the new one: <?php if (count($page->fileField)) { $page->fileField->removeAll(); } That works well so far. My problem is, that I want to add the new file with the same name filename.pdf. But when I remove the previous file and add the new file inside the same saveReady-hook, the previous file still exists until the page is saved and the name of the new file will be added a filename-1.pdf, because ProcessWire makes the filename unique when a file with the same name exists. My question is: Is there a hook or way to remove the previous file before the new file will be added to keep the same filename? I tried to unlink the previous file, but then the InputfieldFile doesn't always gets updated correctly and has one empty file and the new file. ? Regards, Andreas
  22. 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?
  23. Hello! I apologize in advance if I missed something on the forums. I'm not yet that experienced with hooks and already tried a lot. Maybe someone else has an idea or could give me a hint in the right direction. In my ready.php file I'm creating a random generated URL slug on Pages::setupNew for a specific template. When creating a page and I type in the default language title and leave the other languages blank, the slug gets appended to the page names because the pages have the same url/slug/title but in different trees ( ex. /myarticle-myslug/ and /en/myarticle-myslug/ ) When creating a page and I enter a title for each language, the slug gets only applied to the default language and I get an error that the name for the default language already exists and it was changed to /myarticle-myslug/. The other language gets the page name /en/my-article/ applied. Additionally I noticed that the settings from Module -> Page Name (InputfieldPageName) are not applied when creating the page name using the code below. So non-ascii characters get stripped instead of sanitized Here is a simplified code snippet that I have in the ready.php file: wire()->addHookBefore('Pages::setupNew', function($event) { $page = $event->arguments('page'); if ($page->template->name == 'news-article') { $page->name = $page->title . '-myslug'; } }); I've read this topic and if this still applies, LanguageSupportPageNames isn't used on Pages::setupNew. Especially the post by @Soma looks interesting but I'm not sure how to apply it. Thank you very much in advance.
  24. $this->addHookBefore('InputfieldTextarea::render', function($event) { $field = $event->object; if($field->name == 'body_offer') { $del = ''; foreach($this->wire->pages->get(11229)->textblocks as $item) { $field->entityEncodeText = false; $body = str_replace(PHP_EOL, '', $item->body); $body = addslashes($body); $title = $item->title; $field->description .= $del . "<a href=\"#\" class=\"ckesnippet\" data-snippet=\"$body\">$title</a>"; $del = ' | '; } } $js = wire('config')->urls->templates . 'scripts/ckesnippets.js'; $event->return = str_replace("</html>", "\n<script type='text/javascript' src='$js'></script>\n</html>", $event->return); }); I'm trying to add custom text-blocks from repeater fields into CKEditor. I've stolen the whole idea (and code) from @bernhard Problem is: The links are actually being rendered, but the Javascript is not loaded, i.e. the $event->return line doesn't seem to work. If I inspect the HTML, my additional script-tag is nowhere to be seen. I don't get any errors either. Running latest PW dev + PHP 7.1.19.
  25. 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
×
×
  • Create New...