Jump to content

Leaderboard

Popular Content

Showing content with the highest reputation on 06/19/2024 in all areas

  1. You do not need Ajax in this case - only JS is enough. I will try to write the JS for showing and hiding the fields and afterwards we will see further for setting the fields to required or not.? Thanks! I know these docs are just like more a book, so offering examples is often much clearer for the users.
    2 points
  2. @leode, you'll have to make sure your page classes now extend DefaultPage, rather than Page: <?php namespace ProcessWire; class ArticlePage extends DefaultPage //not Page { //your article page specific methods } ?> <? pages()->get('/mytestpage/')->test(); //should now work
    2 points
  3. Welcome to the ProcessWire forums! This is a great question and I think ProcessWire is a great platform to begin transitioning into OOP because ProcessWire itself is object oriented and is built using OOP. It includes powerful tools and features that can help make your code cleaner, more efficient, and reusable. I recommend starting with custom Page classes. Custom page classes lets you use OOP principles to extend ProcessWire and add additional custom behaviors by thinking with objects. There are a couple of examples in that link, but I'll provide one here that specifically contrasts different methods of doing the same thing. This example is a real-world case that I use on many projects, and because of how it's written I can replicate this feature easily when I start new projects. This is just a simple example of code I use that hopefully opens the door to thinking in OOP when working with ProcessWire. On blog posts I like to add something that shows how long it will take to read it, a la "5 minute read" like articles on Medium do. I wrote code that implements Medium's own method of calculating read time and use it often. The code that calculates the reading time is real, but I threw this together for illustration so please excuse any errors. Lets assume that you have a template called blog-post.php where you calculate reading time and output that value to the page. Here is what that looks like using procedural code: <?php namespace ProcessWire; // site/templates/blog-post.php // Calculate the read time for this article by using the words contained in the title, summary, and // body fields $text = "{$page->title} {$page->summary} {$page->blog_body}"; $blogText = explode( ' ', $sanitizer->chars($text, '[alpha][digit] ')); $wordCount = count($blogText); $dom = new \DOMDocument; @$dom->loadHTML( "<?xml encoding=\"UTF-8\"><div>{$blogText}</div>", LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD ); // Account for images in text and add to read time // Starts at 12 seconds for first img, 11, 10, 9, etc. until floor of 3 secs $secondsPerImage = 12; $imageReadTimeInSeconds = 0; $imageCount = $dom->getElementsByTagName('img')->length; while ($imageCount > 0) { $imageReadTimeInSeconds += $secondsPerImage; $imageCount--; $secondsPerImage > 3 && $secondsPerImage--; } // Word count divided by average adult reading speed per minute with image read time added $readTime = (int) (ceil($wordCount / 275) + ceil($imageReadTimeInSeconds / 60)); ?> <!DOCTYPE html> <html lang="en"> <head> <title><?= $page->title; ?></title> </head> <body> <h1><?= $page->headline; ?></h1> <span class="read-time"><?= $readTime; ?> minute read</span> <div class="summary"> <?= $page->summary; ?> </div> <div class="blog-content"> <?= $page->blog_body; ?> </div> </body> </html> So, there's nothing wrong with that- gets the job done! But it could be better... It adds a lot of logic to our template and makes it harder to read, imagine if we had to add more logic for other features Mixing raw PHP and HTML works, but can be confusing when it comes to managing and maintaining our code We can't reuse the the code that calculates reading time, if we wrote this in another place then we have to make sure both are bug free and accurate Of course, we could create a function called readTime() that does the same thing and cleans up the template. But now we are writing functions that do a specific thing but exist without context and are harder to organize and maintain flexibility. Luckily, there's a better way. I'll let the notes by Ryan in that link I shared above explain how to start using custom Page classes, so I'll assume you have that set up. So now lets think in objects and use OOP to improve our code. Now we have our template, blog-post.php, and a custom Page class called BlogPostPage.php. Lets refactor. Here's our BlogPostPage.php file: <?php namespace ProcessWire; // site/classes/BlogPostPage.php class BlogPostPage extends Page { private const INITIAL_SECONDS_PER_IMAGE = 12; private const WORDS_READ_PER_MINUTE = 275; private const ALLOWED_CHARACTERS = '[alpha][digit] '; public function readTime(): int { $text = "{$this->title} {$this->summary} {$this->blog_body}"; $blogText = explode( ' ', wire('sanitizer')->chars($text, self::ALLOWED_CHARACTERS)); $wordCount = count($blogText); $dom = new \DOMDocument; @$dom->loadHTML( "<?xml encoding=\"UTF-8\"><div>{$blogText}</div>", LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD ); $secondsPerImage = self::INITIAL_SECONDS_PER_IMAGE; $imageReadTimeInSeconds = 0; $imageCount = $dom->getElementsByTagName('img')->length; while ($imageCount > 0) { $imageReadTimeInSeconds += $secondsPerImage; $imageCount--; $secondsPerImage > 3 && $secondsPerImage--; } $time = ceil($wordCount / self::WORDS_READ_PER_MINUTE) + ceil($imageReadTimeInSeconds / 60); return (int) $time; } } Now that our code is in the context of a class method, we've made a couple of extra changes: $page->{name of field} is now $this->{name of field} because we're now working within BlogPostPage which extends the Page class itself. We've added constants to define values that would otherwise be a little difficult to understand at first glance. Seeing self::WORDS_READ_PER_MINUTE is clear and self-documenting where only using the integer 275 in place doesn't really state what that number means We switched $sanitizer to wire('sanitizer') because the $sanitizer variable does not exist in the method scope and the wire() function makes the entire ProcessWire API available to us both inside and outside classes ProcessWire will use BlogPostPage class to create the $page object we use in our templates when it boots, executes our code, and renders content via our templates. Thanks to OOP inheritance, BlogPostPage has all of the methods and properties available in the Page class and can be used in our templates with the $page object. And now let's go back to our blog-post.php template: <?php namespace ProcessWire; // site/templates/blog-post.php ?> <!DOCTYPE html> <html lang="en"> <head> <title><?= $page->title; ?></title> </head> <body> <h1><?= $page->headline; ?></h1> <span class="read-time"><?= $page->readTime(); ?> minute read</span> <div class="summary"> <?= $page->summary; ?> </div> <div class="blog-content"> <?= $page->blog_body; ?> </div> </body> </html> Now we're talking. With a little extra code and some OOP we've created a method on the Page object. Some benefits: Our template is cleaner and easier to maintain We've made the BlogPostPage class extend Page, so it inherits all of the methods and properties you access via $page The $page object is used to output the reading time to the page, just like $page outputs our field content, so our custom behavior is predictable and and feels at home with the core ProcessWire API It's easier to find where your programming logic is and keep a separation of concerns What's even better is that because we have used OOP to extend the Page class and add new functionality, we can use this a lot more places in our templates (so now it's reusable too). Let's say that you want to add a blog feed to the home page that shows the latest 3 blog posts and displays them with their title, read time, summary, and a link to read the post. <?php namespace ProcessWire; // site/templates/home.php ?> <!DOCTYPE html> <html lang="en"> <head> <title><?= $page->title; ?></title> </head> <body> <header> <h1><?= $page->headline; ?></h1> </header> <section class="blog-feed"> <!-- Create an <article> preview card for each blog post --> <?php foreach ($pages->get('template=blog-post')->slice(0, 3) as $blogPost): ?> <article> <h2><?= $blogPost->title; ?></h2> <span class="read-time"> <?= $blogPost->readTime(); ?> minute read </span> <div class="post-summary"> <?= $blogPost->summary; ?> </div> <a href="<?= $blogPost->url; ?>">Read More</a> </article> <?php endforeach ?> </section> </body> </html> That would be a lot harder to do if you had to write more procedural code to calculate the read time for each blog post. Thanks to that method in BlogPostPage, we can use it anywhere we reference a blog post. Think we can make this better? Let's improve it using PHP traits. Using a Trait will allow us to reuse our code that calculates reading time in many places thanks to OOP. We'll create another file called CalculatesReadingTime.php and put it in a new folder at /site/classes/traits. Time to refactor, here's our new trait file: <?php namespace ProcessWire; // site/classes/traits/CalculatesReadingTime.php trait CalculatesReadingTime { private const INITIAL_SECONDS_PER_IMAGE = 12; private const WORDS_READ_PER_MINUTE = 275; private const ALLOWED_CHARACTERS = '[alpha][digit] '; /** * Takes an arbitrary number of field values and calculates the total reading time * @param string $fieldValues Contents of fields to calculate reading time for * @return int Total read time, in minutes */ public function calculateReadingTime(string ...$fieldValues): int { $text = array_reduce( $fieldValues, fn ($content, $fieldValue) => $content = trim("{$content} {$fieldValue}"), '' ); $text = explode( ' ', wire('sanitizer')->chars($text, self::ALLOWED_CHARACTERS)); $wordCount = count($text); $dom = new \DOMDocument; @$dom->loadHTML( "<?xml encoding=\"UTF-8\"><div>{$text}</div>", LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD ); $secondsPerImage = self::INITIAL_SECONDS_PER_IMAGE; $imageReadTimeInSeconds = 0; $imageCount = $dom->getElementsByTagName('img')->length; while ($imageCount > 0) { $imageReadTimeInSeconds += $secondsPerImage; $imageCount--; $secondsPerImage > 3 && $secondsPerImage--; } $time = ceil($wordCount / self::WORDS_READ_PER_MINUTE) + ceil($imageReadTimeInSeconds / 60); return (int) $time; } } Let's take a look at that before we go back to our other files. Our new trait has a name that is an "action" because now, as we'll see, we can add this ability to other classes so they can calculate reading times We've abstracted our code. Now instead of referring to content as $blogText, we are calling it $text because it can be used in many places and many contexts but provide the same behavior The readTime() method is now called calculateReadingTime() and has been converted to a variadic function so you can pass as many field values as needed We've taken an extra step of type hinting our parameters as strings to make sure the method is always getting the proper type of data to work with. This will help a lot as this method becomes used more in different places Our docblock is more robust to help understand what this method does, what parameters it takes, and what it will return, another extra step to help us as we use this method in more places Now back to our BlogPostPage.php file <?php namespace ProcessWire; // site/classes/BlogPostPage.php require_once __DIR__ . '/traits/CalculatesReadingTime.php'; class BlogPostPage extends Page { use CalculatesReadingTime; public function readTime(): int { return $this->calculateReadingTime($this->title, $this->summary, $this->blog_body); } } Now we're giving our BlogPostPage class the ability to calculate reading time and all of the functionality has been kept the same. We were able to abstract the logic for calculating reading time to a reusable trait that can be included in any Page class Our readTime() method still exists and is available to all of the templates where we were already using $page->readTime() Now our readTime() method calls the calculateReadingTime() method and passes the fields we know we need as they exist in our blog-post template This code is clean, concise, and easy to maintain. Right now it looks like OOP has made things look nice but caused some extra work... but then the phone rings. Your client wants to add Press Releases to the blog section of the site and it's going to need a new layout and different fields, but they love your reading time calculator so much that they want it on the new Press Release pages too. So we create our new files- a press-release.php template, and a PressReleasePage.php file. We'll skip writing out the press-release.php HTML, but while creating the new template in ProcessWire you've created new fields. The new fields are 'pr_abstract', 'pr_body', 'company_information', and 'pr_contact_info'. Here's our new PressReleasePage.php file: <?php namespace ProcessWire; // site/classes/PressReleasePage.php require_once __DIR__ . '/traits/CalculatesReadingTime.php'; class PressReleasePage extends Page { use CalculatesReadingTime; public function readTime(): int { return $this->calculateReadingTime( $this->pr_abstract, $this->pr_body, $this->company_information, $this->pr_contact_info ); } } Since we've created this simple class that uses the CalculatesReadingTime trait, we can use $page->readTime() in all of our Press Release pages, and anywhere that a Press Release $page object is present. Very nice. Now OOP has really shown how useful it is and we can appreciate how ProcessWire uses objects and provides tools for us extend that power with our own code. There's also some other OOP things happening here: Our BlogPostPage and PressReleasePage classes do one thing and one thing only: handle logic and features for their respective pages. So, they have a single responsibility The calculateReadingTime() and readTime() methods do one thing and one thing only, calculate reading time based on content. They only care about one thing and have no side effects. Our BlogPostPage and PressReleasePage clases can both calculate reading time, but other hypothetical page classes, like "HomePage" and "AboutUsPage" aren't required to have a readTime() method that isn't used, thanks to making use of traits to share behavior only where it's needed. So, that's composition over inheritance Our readTime() method does not expose how it calculates reading time and it provides an interface to only expose information we want our object to make available. So, readTime() is read-only and can safely be used knowing that the value will never be overwritten or modified except when content is changed by editing the page. This is a great tool that shows the difference between setting a value to $page->title and getting a value from readTime(), each have their purposes and roles. Our code is modular and easy to maintain. If we had to adjust how reading time was calculated- we could for example adjust the value of WORDS_READ_PER_MINUTE in our CalculatesReadingTime trait. Then all of our Press Releases and Blog Posts would have their reading time correctly calculated with one change. We can also add CalculatesReadingTime to any future page classes that need it. ProcessWire's strong OOP foundation and the way that it uses objects that are created from classes for everything (like $page, $config, $input, etc.) is the reason that the API is easy to work with, enjoyable, and powerful. If you get the hang of working with OOP in ProcessWire you can build even more powerful websites and applications, better understand the ProcessWire core code, and write your own modules (which is actually pretty fun). Wasn't sure of your overall exposure to OOP but hopefully this helps and inspires!
    2 points
  4. --- Module Directory: https://modules.processwire.com/modules/privacy-wire/ Github: https://github.com/blaueQuelle/privacywire/ Packagist:https://packagist.org/packages/blauequelle/privacywire Module Class Name: PrivacyWire Changelog: https://github.com/blaueQuelle/privacywire/blob/master/Changelog.md --- This module is (yet another) way for implementing a cookie management solution. Of course there are several other possibilities: - https://processwire.com/talk/topic/22920-klaro-cookie-consent-manager/ - https://github.com/webmanufaktur/CookieManagementBanner - https://github.com/johannesdachsel/cookiemonster - https://www.oiljs.org/ - ... and so on ... In this module you can configure which kind of cookie categories you want to manage: You can also enable the support for respecting the Do-Not-Track (DNT) header to don't annoy users, who already decided for all their browsing experience. Currently there are four possible cookie groups: - Necessary (always enabled) - Functional - Statistics - Marketing - External Media All groups can be renamed, so feel free to use other cookie group names. I just haven't found a way to implement a "repeater like" field as configurable module field ... When you want to load specific scripts ( like Google Analytics, Google Maps, ...) only after the user's content to this specific category of cookies, just use the following script syntax: <script type="text/plain" data-type="text/javascript" data-category="statistics" data-src="/path/to/your/statistic/script.js"></script> <script type="text/plain" data-type="text/javascript" data-category="marketing" data-src="/path/to/your/mareketing/script.js"></script> <script type="text/plain" data-type="text/javascript" data-category="external_media" data-src="/path/to/your/external-media/script.js"></script> <script type="text/plain" data-type="text/javascript" data-category="marketing">console.log("Inline scripts are also working!");</script> The data-attributes (data-type and data-category) are required to get recognized by PrivacyWire. the data-attributes are giving hints, how the script shall be loaded, if the data-category is within the cookie consents of the user. These scripts are loaded asynchronously after the user made the decision. If you want to give the users the possibility to change their consent, you can use the following Textformatter: [[privacywire-choose-cookies]] It's planned to add also other Textformatters to opt-out of specific cookie groups or delete the whole consent cookie. You can also add a custom link to output the banner again with a link / button with following class: <a href="#" class="privacywire-show-options">Show Cookie Options</a> <button class="privacywire-show-options">Show Cookie Options</button> I would love to hear your feedback ? CHANGELOG You can find the always up-to-date changelog file here.
    1 point
  5. So I started playing around with Supermaven's free tier. If you are looking for a code assistant for VSCode I would recommend giving it a try. I started using it after Theo covered it in one of his tool videos, and I can say it probably shaves about 15 minutes of work per hour for me. It does a reasonably good job of anticipating structures you are building based on a quick overview of the codebase for your project. I haven't extended the codebase to include the entire source for processwire in my projects, but even with just the minimum core wire folder modules and a few site module source code bits it is more than enough to cover the bases. I am using the free tier which has a smaller token context limitation, but the code suggestions are fast, they don't feel inappropriately intrusive and don't write-ahead too far until the engine has high confidence in the direction you are trying to go. When it has high certainty, it opts to give you large code blocks - even entire functions with appropriate substitutions. It has sped up my RockMigration script writing considerably - beyond the macros, because it sees other migration functions I have defined and does a very good job of anticipating not only the class structures for custom page classes, etc, but also replacing names for new classes with proper singular/plural forms, etc. I'd say it provides the correct code without modification 85% of the time. https://supermaven.com/
    1 point
  6. As our current Processwire Professional switched business focus, we are looking for a new partner to manage our multi-domain and multi-language websites – It is a single Processwire installation. Short-time Tasks: Complete CSS rework. It is an utter mess of multiple systems. Design can stay the same. Processwire Upgrade and minor bug fixes Mid-term Tasks: Custom shop system Customer back-end Requirements: PHP programming skills Formal invoices required Ideally German language skills (not mandatory) 24h response time We would love to hear from YOU!
    1 point
  7. Fruitcake has been using ProcessWire for a while now but I didn't get around to posting any of the around 30 sites we did so far. I will create sort of a megathread here adding any project we did (and want to talk about :D). But let me start off with our own new website which launched earlier this year. Our new brand website had the goal to be modern and simple and uses a minimalistic approach. The centerpiece of the page of course is our portfolio which most of the effort went into. It uses a playful and seemingly random (it's not!) layout. The portfolio detail page uses a vertical slider which from a technical point of view was the most challenging part. As for modules we are using, we like to do most of the stuff ourselves so it really only boils down to the Repeater Matrix Fieldtype from @ryan's ProFields package and SEO is done using SeoMaestro by @Wanze. Here you can have a look yourself: Die Kommunikationsagentur | fruitcake.ch Here is a preview of the masthead: Let me know what you think ?
    1 point
  8. hmmyes. But that would make things even more complicated? (I am not really familar with ajax.) By the way: its super helpful that you provided the exmple files. very good organised an written. big ups!
    1 point
  9. Ok, I see! Just to mention: To validate the form (including the hidden fields if they are displayed after clicking a certain radio button) all fields must be added to the form object. This means: You need to create ALL form fields first and add them to the form object (independent if the should be visible or not). Now all fields are visible. This is the point were you are now. To change the visibility of certain form fields, you need Javascript (Jquery or plain JS). Take an eventlistener and check if radio button 1 (Einzelperson) or radio button 2 (Doppelmitgliedschaft) has been clicked. Depending on that you hide or show the fields inside the form. The second part would be the validation depending on the radio button status. So you need to add a validator which has a dependency on the radio button value selected. To clearify: If you want to make some of the fields required, if they are visible, you need to add a required validator with dependency of the value selected in the radio button multiple. More in detail: Field A is only required if radio button A is selected, Field B is only required if radio button B is selected and so on. So we need a kind of "requiredIf" validator, but I am afraid that Valitron does not offer such a validator. There is only a requiredWith validator and I guess this is not the right one for your usecase, but I have not used it before, so I am not sure Maybe there is a need to create a custom validator for this scenario.? That does not matter - I am speaking German ? Can you post the complete form code here, so I can make an exact copy of your form on my local host for testing purposes. Please also write which form fields should be visible on the first and wich one on the second radio button.
    1 point
  10. @DrQuincy Matrix repeaters are pages themselves. They are different than usual fields. First you create a matrix type and add content. Then save the matrix page and then you can save your actual page. Each time you add a matrix type a new page is created. You can find these pages in the page tree under admin
    1 point
  11. Thanks for this awesome module!! I am running it on various installations without any issues and flaws! ? Now, a client wants to show form fields only, if the user selected one check box. In the file, I am calling InputRadioMultiple to integrate various buttons. How to I validate for one specific button being checked to show additional form fields? Happy for any input. Thanks a lot!!!
    1 point
  12. https://processwire.com/api/ref/sanitizer/entities-markdown/
    1 point
  13. Thanks everyone for the feedback. You know how it is with your own websites... they get neglected in favor of everything that can make you money and thus, image optimization wasn't the most important thing to finish because we are only targeting the Swiss market anyway. In Switzerland, load times much better. Nevertheless, I did now finish the optimizations and enabled webp everywhere and so most images are <100k now. The videos remain untouched but will be done at some point.
    1 point
  14. Thanks, success! For the sake of ulterior reference : str_replace($short, '', $person->content);
    1 point
  15. For the title field you can enable access control in template context to limit editability by role. For deletion you can revoke the delete permission per template per role. For the settings tab there is a $template->noSettings property: https://github.com/processwire/processwire/blob/38a5320f612a4b38a7353265343219f224f20e6d/wire/core/Template.php#L100 You can conditionally set this with a hook for non-superusers: $wire->addHookBefore('ProcessPageEdit::execute', function(HookEvent $event) { /** @var ProcessPageEdit $ppe */ $ppe = $event->object; /** @var Page $page */ $page = $ppe->getPage(); if($page->template == 'my_template' && !$event->wire()->user->isSuperuser()) { $page->template->noSettings = 1; } });
    1 point
  16. In a recent GitHub issue report, I was asked about output formatting in ProcessWire, and where more information could be found about it. I know I've written about it numerous times, and went to locate the documentation page, only to find we didn't have one! Output formatting is such an important topic, so here is everything you need to know. I hope you'll find it simple enough, but also useful and thorough— https://processwire.com/blog/posts/output-formatting/
    1 point
  17. While you are optimizing images, don't forget this one: view-retro-looking-personal-computer-2-1-1.png (on https://fruitcake.ch/projekte/40-jahre-fruitcake/) which is 14.7 MB :)
    1 point
  18. @poljpocket Thanks for posting that. Looks good, but I'm experiencing extremely slow page loads on the "Meet the team" page. Some of the staff images have been loading for well over a minute. (Chrome or Firefox, both the same.)
    1 point
  19. This week I'm releasing the ProcessWire Fieldtype/Inputfield module "Functional Fields" as open source in the modules directory. This was originally built in 2017 for ProFields, but hasn't required much in terms of support resources, so I thought I should release this newest version (v4) publicly. While this module is completely different from other Fieldtypes, I think it's quite useful and fulfills some needs better than other Field options. Give it a try and please let me know what you think. For an introduction to Functional Fields, please revisit this blog post which covers all the details: https://processwire.com/blog/posts/functional-fields/ Functional Fields is available for download in the modules directory here: https://processwire.com/modules/fieldtype-functional/ Thanks and have a great weekend!
    1 point
  20. There's so much more to write about ProcessWire in practice. On a personal note, I have to give ProcessWire credit for being a point of education for me years ago as I started to transition to OOP. An example is seeing how the ProcessWire API is structured with fluent methods, I thought that was so cool that I learned how to implement them myself by studying the core source code. ProcessWire grows with you as a developer and it continually gets better as time goes on. Many thanks to @ryan, contributors, and module authors for their inspiration and impact on my skills. Thank you for the kind words! This truly only scratches the surface and, as you can see, OOP is not something you do "in" ProcessWire, it's something you do with ProcessWire should that be your choice, as much or as little as you want, when and where it makes sense. Go forth and build! If you get stuck, there are plenty of friendly and knowledgeable devs here in the forums who are happy to help.
    1 point
  21. Wow. And the award for the greatest answer of the year goes to...
    1 point
  22. "Everything" in ProcessWire is a page. So for example I have a "Global Settings" Page (which is actually a page!) in my backend here: Inside this page you can add whatever fields you like to store data that you want to use "globally" on your website. For example text blocks, or repeaters that contain page references to use as a footer menu: In my ready.php file have this global variable that acts as a page reference to the settings page: // Global Settings Page as API variable $wire->wire('globalSettings', $pages->get('template=global-settings')); Then on any template file I can access a field on that global settings page like this: <?= $globalSettings->body; ?>
    1 point
×
×
  • Create New...