Jump to content

Leaderboard

Popular Content

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

  1. The core dev branch version has been bumped up to 3.0.240 this week. As always, see @teppo's excellent ProcessWire Weekly for details on what has been added recently. More can also be found in the commit log. This week adds the ability to hook into ProcessWire's admin live search to add your own custom results. This is useful for modules or for your own hooks placed in /site/templates/admin.php. Previously, only modules implementing the SearchableModule interface could manipulate the admin search engine results. Now there's another even simpler way to do it. We'll focus on examples placed in /site/templates/admin.php, but they could also go in /site/ready.php, /site/init.php or in an autoload module's init() or ready() method. The following is a simple example for when one types "today" into the search engine, it returns search results of pages that were modified today. $wire->addHook('ProcessPageSearchLive::findCustom', function(HookEvent $event) { $data = $event->arguments(0); // array $search = $event->object; // ProcesPageSearchLive $group = 'Pages modified today'; // description of this type of search if($data['q'] === 'today') { $items = $event->wire()->pages->find("modified>=today, include=unpublished"); foreach($items as $item) { $search->addResult($group, $item->title, $item->editUrl); } } }); The point of that example is just to demonstrate something simple. In reality, that example isn't that useful because you can already type "modified>=today" to get the same results in the search engine. So let's look at a potentially more useful example. There have recently been requests for better "id" search support in the search engine. In this next example, we add support for "id=123" searches, where it will match templates, fields or pages having id "123" (or whatever ID you specify). Further, it will also support it if you just type "123" on its own. Here's how we might accomplish that below. We'll limit this particular type of search to the superuser since this hook doesn't have any access control checking. if($user->isSuperuser()) { $wire->addHook('ProcessPageSearchLive::findCustom', function(HookEvent $e) { $search = $e->object; /** @var ProcessPageSearchLive $search */ $data = $e->arguments(0); /** @var array $data Search data */ $type = $data['type']; // what to search $q = $data['q']; // search query text // support search of "id=123" or just "123" // skip search if not an "id" search, or query is not a number if(($type != 'id' && !empty($type)) || !ctype_digit($q)) return; // reduce default search operator "%=" to just "=" (if used) $operator = trim($data['operator'], '%'); // search for id in templates, fields and pages foreach(['templates', 'fields', 'pages' ] as $apiVarName) { $apiVar = $e->wire($apiVarName); // get API var $selector = "id$operator$q"; // selector i.e. id=123 or id<10, etc. // some additional considerations for page ID searches if($apiVarName === 'pages') { // PW already handles "id=123" for pages, so skip that kind if($type === 'id' && $operator === '=') continue; // add more to selector for page searches $selector .= ", include=all, limit=$data[limit], start=$data[start]"; } // find by selector $items = $apiVar->find($selector); // tell ProcessPageSearch which results we found foreach($items as $item) { $title = $item->get('title|label|name'); $url = $item->editUrl(); $search->addResult($apiVarName, $title, $url); } // optionally return false to tell it to stop searching after this hook // which would prevent the default behavior of the search engine // $e->return = false; } }); } As you may (or not) know, the search engine displays help if you type the word "help". Help for the search engine usually consists of example searches and descriptions of what those examples do. If we want to add some help for our example above, we could add this to to the top of our hook above, perhaps right after the $data = $e->arguments(0); line: if(!empty($data['help'])) { return $search->addHelp('ID Search Help', [ 'id=1234' => 'Find templates, fields, pages with id 1234', '1234' => 'Same as above but “id=” is optional', ]); } That's the gist of it. These are fairly basic examples but hopefully communicate enough to show that you can add any kind of results you want into the search engine. Right now it's pretty simple and enables anyone with a ProcessWire site to add custom results into the admin live search. But if you find your needs go beyond this, the SearchableModule interface does support more options too. It's also worth using TracyDebugger to examine the $data array that the hook receives, as there are several other things in there you may find useful as well. Thanks for reading and have a great weekend!
    9 points
  2. Imagine we could clone @ryan. (super villain laughing in the background)
    4 points
  3. That really works. I didn't know that. Not at all. TIL: something new, again. Have a great weekend @ryan and everyone that is reading this.
    3 points
  4. Hello all, FieldtypeFormSelect has been added to the modules directory and is also now installable via Composer. Thanks, and enjoy!
    2 points
  5. It was the goal by insisting a bit, glad it work and cheer on you for not surrendering ?
    2 points
  6. Update: The module is now available in the modules directory ?
    2 points
  7. 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
  8. hi there, block setting is a fantatstic feature! i'd like to use it to assign severeal additional classes and therefore use several checkboxes in a row. output should be something like: margins: [ ] top [ ] bottom [ ] left a.s.o i tried something like this ( but that doesn't work): $settings->add([ 'name' => 'margin-checkbox', 'label' => 'Marging', 'value' => $field->input('margin-checkbox', 'checkbox', [ '*foo' => 'foo value', 'bar' => 'bar value', 'baz' => 'baz value', ]), ]); is there a way to do that?
    1 point
  9. @bernhard, I meant “_not_ beholden to UIKit…” At any rate, I understand everything you’ve explained. I appreciate your input.
    1 point
  10. wow, that is very beautiful! works like a charm - thank you!
    1 point
  11. Yes! Yes. All the great things that UIkit has to offer: Accordions, Tooltips, Alerts, Offcanvas, Dropdowns etc etc Some parts do unfortunately, but only very, very little, because the profile only uses the @base directives from Tailwind and obviously also the @utilities (for all the great utility classes). @Stefanowitsch found out that we can even turn off preflight in the base component an we tried that on a recent project - he might have some more information on that topic. I'm not sure what you mean here, but you can do whatever you want or prefer. I'm using UIkit components and then add Tailwind for all the individual changes that I need, that are not global. So if I wanted to change the global font-size I'd adjust the UIkit LESS/SCSS variable. If I wanted to change the global "margin-top": Same. But for all the small little changes that would prior go into custom .less files I just add tailwind utility classes. Think of it as UIkit on Steroids ?
    1 point
  12. Hi @herr rilke This looks like some CSS styles are interfering with the Editor Toolbar Styles. I would advice you to investigate the markup this dropdown with the developer tools in the frontend and see what CSS rules are applied and from where they come from (maybe some other stylesheets, maybe the frontend framework that you included in the project, etc.)
    1 point
  13. SOLVED! With many thanks to @BrendonKoz and @flydev for encouraging me to persist in tracking this down. I finally managed to get the error to occur in the dev environment. That was progress as it enabled me to use Xdebug to see what was happening. I found another module with a listable hook in ready(). What was happening was this: When my hook was in /site/ready.php it ran after any hooks in modules' ready(), because that is the order ProcessWire calls them in. When I put my hook in my module's ready() it still ran after the other module's hook in the dev environment but before it in the live environment. Assigning a higher priority to my hook (1000 - i.e. greater than the default 100) fixed it.
    1 point
  14. I just suggested priority in case there is another hook somewhere of even to not let the system decide when to call it as we have not a profiling report, just set a priority highter, it doesn't hurt to make a test. Also, the reason of why I posted the issue is because I am assuming from your screenshots that you are not making tests with root user id (#7815), so you should test with root user on both envs in order to tackle in first instance the permission issue you posted in your other thread, and post the results.
    1 point
  15. When I was adjusting the Page's editable, listable, viewable, and addable method hooks, I was testing access for one to determine access to another. This caused a bit of a recursively confusing mess. You aren't by chance doing something similar, are you? If so, different calls of the same method can/will return different values due to context, and data that either is, or hasn't yet been set (typically access to templates in my case).
    1 point
  16. ? <- me, pretty much all the time with ProcessWire. Fantastic stuff. Thanks as always, and happy Friday everyone!
    1 point
  17. 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!
    1 point
  18. Thanks for this @ryan! Great to see something becoming free in the days that so many simple things tend to become paid on the contrary. The ProFields pack is still clearly a must have and worth its money for sure)
    1 point
  19. TinyMCE inherits this class names from the Page Edit Image module, you can change these classes in the: modules -> configure -> ProcessPageEditImageSelect module
    1 point
  20. Sticking to FA will probably be a good idea because there's a lot of javascript on the backend (for example for adding spinners that indicate loading) and that would likely break with other icon libraries that work differently or use other classes. On the other hand having more icons available would be nice, so the free subset of FA6 sounds like a good idea to me if it does not take up too much space just for the small benefit of having more icons. I think the best chances to get that into the core are if someone just tried it out and provided a PR and let Ryan know about it. Or maybe ask Ryan before doing it if he'd be willing to add it at all (to prevent useless work).
    1 point
  21. Yes - it makes no difference. On the dev site, I can track exactly what happens by stepping through with Xdebug. The only code between the two bardumps is a couple of WireData 'gets' for 'return' returning true. It would be great to be able to do the same in the live environment!
    0 points
×
×
  • Create New...