Jump to content

MoritzLost

Members
  • Content Count

    68
  • Joined

  • Last visited

  • Days Won

    2

MoritzLost last won the day on December 12 2018

MoritzLost had the most liked content!

Community Reputation

242 Excellent

About MoritzLost

  • Rank
    Full Member

Contact Methods

  • Website URL
    https://herebedragons.world/

Profile Information

  • Gender
    Male
  • Location
    Cologne, Germany

Recent Profile Visitors

531 profile views
  1. I just pushed a big update to the textformatter with version 3.0.0! I'm not sure if anyone is actually using this module, but at least for my own projects it has been useful, and it's good training for MySQL intricacies, so I'm still updating it when I think of new stuff to add πŸ™‚ With the updated version, it's now possible to overwrite any option from the module configuration when calling the module manually in your template code. That way, you can automatically link to pages of different templates in different contexts on the same site, or customize the behaviour of the textformatter any way you want! Also, there's now an option to toggle case insensitive behaviour, if needed, as well as an option to force case sensitive queries for case insensitive database collations. The changelog is now included in the repository itself, I also updated the readme with instructions on how to call the module manually. Make sure to check out the full changelog for version 3.0.0, as well as the readme section on manual usage. Let me know if the module is or isn't working for you, and any suggestions you have on how to improve it!
  2. @teppo @wbmnfktr Wow this discussion derailed a bit, but here we are ^^ Teppo, thanks for the pointers regarding target blank, I didn't really have that on my radar. Makes perfect sense though, I'll definitely reconsider my current approach! Even more off-topic, but I feel a bit smug now about having isolated that logic into a twig template in my current project, so now I can change it in a central place: {# blocks/link-start.twig #} {#- # Renders a start tag for a link. The link will automatically have target="_blank" # and rel="noopener" if the link leads to an external domain. # # @var string url The target (href) for the URL. # @var bool is_download Should the link be marked as a download (for direct file downloads)? # @var array classes Optional classes for the anchor. -#} <a href="{{ url }}" {%- if is_download is defined and is_download %} download{% endif -%} {%- if classes is defined and classes is not empty %} class="{{ classes|join(' ')|trim }}"{% endif -%} {%- if isExternalUrl(url) %} target="_blank" rel="noopener"{% endif %}> I'll just get rid of the last part πŸ™‚ Thanks to everyone participating in the discussion! I think it's great how different perspectives come together that provide everyone new insights & best practices ...
  3. I think it's great! I've already incorporated it into my current project, and it has a sizable performance impact on Chrome without any real work on my part. I always thought removing the src attribute and setting it with JavaScript was an antipattern, as anyone with JavaScript disabled wouldn't see any images at all, so it's good to see native support for lazy loading. It's progressive enhancement, so you don't need to have support from all browsers. Support doesn't look half bad though, even though only Chrome supports it at the moment (see caniuse), that's already a sizable chunk of the population. Also, caniuse currently lists Chrome on Android, which is huge (36 %) as not supporting it, I'm not sure that's correct. According to the Chrome Platform Status page, native lazyload is already supported in Chrome on Android. That would get the feature to >50 % browser support already. On current Android versions, all WebViews are provided by Chrome, so it will work in all in-app browsers on Android as well. Also, you can very easily polyfill the native lazyload with JavaScript (see article above), so everyone will profit from this without much of a downside!
  4. This doesn't warrant a full tutorial, but I wrote a little function that will recursively search through a repeater field to find the first non-empty field matching a list of fields to look for. I needed something like this to generate a fallback for SEO fields (og:image, og:description et c.). Here it is: <?php namespace ProcessWire; /** * Find the first non-empty field out of a list of fields in a repeater or repeater matrix field. * Will recursively search through nested repeaters until it finds a non-empty * field. * * @param RepeaterPageArray $repeater The field to search through. * @param array $fields A list of fields the function should look for. * @param array|null $allowed_repeater_types All the Repeater Matrix types the function will check. Leave empty to allow all. * @param array|null $allowed_repeater_fields All the repeater fields the function will check recursively. Leave empty to allow all. * @return void */ function firstRecursiveRepeaterMatch( RepeaterPageArray $repeater, array $fields, ?array $allowed_repeater_types = null, ?array $allowed_repeater_fields = null ) { // iterate over the items of the repeater foreach ($repeater as $current) { // if the function is currently inside a repeater matrix field, // skip this item if it isn't one of the allowed types, unless // allowed_repeater_types is empty (all types allowed) if ( $current instanceof RepeaterMatrixPage && is_array($allowed_repeater_types) && !in_array($current->type, $allowed_repeater_types) ) { continue; } // get all fields of the current item foreach ($current->getFields() as $field) { $name = $field->name; // if the current field is another repeater, check it recursively $fieldtype_class = $field->getFieldType()->className(); if ($fieldtype_class === 'FieldtypeRepeater' || $fieldtype_class === 'FieldtypeRepeaterMatrix') { // continue with the next item if the field name isn't one of the // allowed repeater fields, unless allowed_repeater_fields empty (null) if ( is_array($allowed_repeater_fields) && !in_array($name, $allowed_repeater_fields) ) { continue; } $deep_search = firstRecursiveRepeaterMatch( $current->get($name), $fields, $allowed_repeater_types, $allowed_repeater_fields ); // if the deep search inside the repeater // finds something, the function ends here if ($deep_search !== null) { return $deep_search; } } // if the current field name is one of the requested // fields, return it's value if it isn't empty if (in_array($name, $fields)) { $value = $current->get($name); if ( // check for empty values !empty($value) // if the value is any wirearray, check // if it has at least one item && (!$value instanceof WireArray || $value->count() > 0) ) { return $value; } } } } // if the function reaches this point, there is no match in the entire tree return null; } Can be used like this: $seo_description = firstRecursiveRepeaterMatch( // content sections fields, a repeater matrix with multiple types $page->sections, // look for the first non-empty instance of any of those fields ['body', 'html_basic', 'html_full'], // only check sections of the following types ['section_text', 'section_columns', 'section_accordion'], // only check the following nested repeaters recursively ['columns', 'accordion'] ); Wanted to share because I thought it could be useful to others. It should be easy to adjust the matching condition from non-emtpy fields to some other condition, depending on the use case ...
  5. @szabesz Fair enough! 😁 @adrian As a user, I agree - i don't like it when I try to navigate away from a page using a link, and it opens in a new page, forcing me to go back to close the tab. But we're power users, I'm not sure everyone knows how to open links in a new tab (especially on mobile, not everyone gets the long-press interaction!). As for why I still use target blank basically for all external links, you know, business reasons. Almost every client sees red when they encounter a link that leads them away from their site. Not sure why everyone expects their audience to have the attention span of a mouse, but oh well ... it's not something I want to spend energy discussing every time. I can see both sides though.
  6. @adrian @horst @szabesz Thanks! Interesting how those solutions are different yet similar. I usually do something like this for footer menus that tend to be more custom, since it only contains a cherry-picked selection of the most important pages. I have tried a couple different combinations of fields, with different levels of control. Since we're doing screenshots, here's the latest iteration that I find quite flexible: Sorry it's in German. Basically, there's a repeater "Footer regions", each containing a headline and a repeater with links. The regions get displayed as individual columns in the footer. Each link has a radio selection between "Internal page", "External URL" and "Download", and a "Link-Text" field. Depending on the radio selection, the respective field get displayed (page reference, URL or file Upload). If the Link-Text is empty, the link is displayed with a reasonable default (Page title for internal pages, domain for external URLs, file basename for files). I initially disliked having too use an additional field for the link-type, but it provides better usability for the client in my experience. @horst I like the solution with the show_only_if fields, though it might not be clear to clients how to switch it back? I found that the interaction with fields being only visible when other fields are empty/filled is not so intuitive for clients. @szabesz Interesting, is the "Open blank" option something your clients actively use? I usually just handle that in the template, i.e. all URLs to different hosts get target="_blank" rel="noopener" automatically ...
  7. In this tutorial I want to write about handling special cases and change requests by clients gracefully without introducing code bloat or degrading code quality and maintainability. I'll use a site's navigation menu as an example, as it's relatable and pretty much every site has one. I'll give some examples of real situations and change requests I encountered during projects, and describe multiple approaches to handling them. However, this post is also about the general mindset I find useful for ProcessWire development, which is more about how to handle special cases and still keep your code clean by making the special case a normal one. The problem: Special cases everywhere Since ProcessWire has a hierarchical page tree by default, as a developer you'll usually write a function or loop that iterates over all children of the homepage and displays a list of titles with links. If the site is a bit more complex, maybe you additionally loop over all grandchildren and display those in drop-down menus as well, or you even use a recursive function to iterate over an arbitrary amount of nested child pages. Something like this: function buildRecursiveMenu(Page $root): string { $markup = ['<ul class="navigation">']; foreach ($root->children() as $child) { $link = '<a class="navigation__link" href="' . $child->url() . '">' . $child->title . '</a>'; $children = $child->hasChildren() ? buildRecursiveMenu($child) : ''; $markup[] = "<li class="navigation__item">{$link}{$children}</li>"; } $markup[] = '</ul>'; return implode(PHP_EOL, $markup); } But then the requests for special cases come rolling in. For example, those are some of the requests I've gotten from clients on my projects (by the way, I'm not saying the clients were wrong or unreasonable in any of those cases - it's simply something I needed to handle in a sensible way): The homepage has the company's name as it's title, but the menu link in the navigation should just say "Home". The first page in a drop-down menu should be the top-level page containing the drop-down menu. This was requested because the first click on the top-level item opens the sub-navigation instead of navigating to that page (espcially on touch devices, such as iPads, where you don't have a hover state!), so some visitors might not realize it's a page itself. Some top-level pages should be displayed in a drop-down menu of another top-level page, but the position in the page tree can't change because of the template family settings. The menu needs to contain some special links to external URLs. For one especially long drop-down menu, the items should be sorted into categories with subheadings based on a taxonomy field. In general, my solutions to those requests fall into three categories, which I'll try to elaborate on, including their respective benefits and downsides: Checking for the special case / condition in the code and changing the output accordingly (usually with hard-coded values). Separating the navigation menu from the page tree completely and building a custom solution. Utilizing the Content Management Framework by adding fields, templates and pages that represent special states or settings. Handling it in the code This is the simplest solution, and often the first thing that comes to mind. For example, the first request (listing the homepage as "Home" instead of it's title in the navigation) can be solved by simply checking the template or ID of the current page inside the menu builder function, and changing the output accordingly: // ... $title = $child->template->name === 'home' ? 'Home' : $child->title; $link = '<a class="navigation__link" href="' . $child->url() . '">' . $title . '</a>'; // ... This is definitely the fastest solution. However, there are multiple downsides. Most notably, it's harder to maintain, as each of those special cases increases the complexity of the menu builder function, and makes it harder to change. As you add more special conditions, it becomes exponentially harder to keep changing it. This is the breeding ground for bugs. And it's much harder to read, so it takes longer for another developer to pick up where you left (or, as is often cited, for yourself in six months). Also, now we have a hard-coded value inside the template, that only someone with access to and knowledge of the template files can change. If the client want's the link to say "Homepage" instead of "Home" at some point, they won't be able to change it without the developer. Also, each special case that is hidden in the code makes it harder for the client to understand what's going on in terms of template logic - thus increasing your workload in editorial support. That said, there are definitely some times where I would go with this approach. Specifically: For smaller projects that you know won't need to scale or be maintained long-term. If you are the only developer, and/or only developers will edit the site, with no "non-technical" folk involved. For rapid prototyping ("We'll change it later") Building a custom solution My initial assumption was that the main navigation is generated based on the page tree inside ProcessWire. But of course this isn't set in stone. You can just as easily forgo using the page tree hierarchy at all, and instead build a custom menu system. For example, you could add a nested repeater where you can add pages or links on a general settings page, and generate the menu based on that. There are also modules for this approach, such as the Menu Builder by @kongondo. This approach is not the quickest, but gives the most power to the editors of your site. They have full control over which pages to show and where. However, with great power comes great responsibility, as now each change to the menu must be performed manually. For example, when a new page is added, it won't be visible in the menu automatically. This is very likely to create a disconnect between the page tree and the menu (which may be what you want, after all). You may get ghost pages that are not accessible from the homepage at all, or the client may forgot to unpublish pages they don't want to have any more after they've removed them from the menu. I would only go with this approach if there are so many special cases that there hardly is a "normal case". However, even then it might not be the best solution. The direct relationship between the page tree, the menu structure and page paths are one of the strongest features of ProcessWire in my opinion. If many pages need to be placed in special locations without much structure in regards to what templates go where, maybe you only need to loosen up the template family settings. I have built one site without any template family restrictions at all - any page of any template can go anywhere. It's definitely a different mindset, but in this case it worked well, because it allowed the client to build custom sections with different page types grouped together. It's a trade-off, as it is so often, between flexibility and workload. Weigh those options carefully before you choose this solution! Utilizing the CMF This is the middle ground between the two options above. Instead of building a completely custom solution, you keep with the basic idea of generating a hierarchical menu based on the page tree, but add fields and templates that allow the editor to adjust how and where individual pages are displayed, or to add custom content to the menu. of course, you will still write some additional code, but instead of having hard-coded values or conditions in the template, you expose those to the client, thereby making the special case one of the normal cases. The resulting code is often more resilient to changing requirements, as it can not one handle that specific case that the client requested, but also every future change request of the same type. The key is to add fields that enable the client to overwrite the default behaviour, while still having sensible defaults that don't require special attention from the editor in most cases. I'll give some more examples for this one, as I think it's usually the best option. Example 1: Menu display options This is probably the first thing you thought of for the very first change request I mentioned (displaying the homepage with a different title). Instead of hard-coding the title "Home" in the template, you add a field menu_title that will overwrite the normal title, if set. This is definitely cleaner than the hard-coded value, since it allows the client to overwrite the title of any page in the menu. I'll only say this much in terms of downsides: Maybe the menu title isn't really what the client wanted - instead, perhaps they feel limited because the title is also displayed as the headline (h1) of the page. In this case, the sensible solution would be an additional headline field that will overwrite the h1, instead of the menu_title field. Which fields are really needed is an important consideration, because you don't want to end up with too many. If each page has fields for the title, a headline, a menu title and an SEO-title, it's much more complicated than it needs to be, and you will have a hard time explaining to the client what each field is used for. Another example in this category would be an option to "Hide this page in the menu". This could be accomplished by hiding the page using the inbuilt "hidden" status as well, but if it's hidden it won't show up in other listings as well, so separating the menu display from the hidden status might be a good idea if your site has lots of page listings. Example 2: "Menu link" template One solution that is quite flexible in allowing for custom links to pages or external URLs is creating a menu-link template that can be placed anywhere in the page tree. This templates can have fields for the menu title, target page and/or external target URL. This way, you can link to another top-level page or an external service inside a drop-down menu, by placing a Menu Link page at the appropriate position. This is also a clean solution, because the navigation menu will still reflect the page tree, making the custom links visible and easily editable by the editors. A minor downside is that those templates are non-semantical in the sense that they aren't pages with content of their own. You'll need to make sure not to display them in listings or in other places, as they aren't viewable. It may also require loosening up strict family rules - for example, allowing for Menu Link pages to be placed below the news index page, which normally can only hold news pages. Example 3: Drop-down menu override This one is a more radical solution to override drop-down menus. You add a repeater field to top-level pages, similar to the one mentioned as a custom solution, where you can add multiple links to internal pages or URLs. If the repeater is empty, the drop-down menu is generated normally, based on the sub-pages in the page tree. But if the repeater contains some links, it completely overrides the drop-down menu. It's similar to the fully custom solution in that as soon as you override a sub-menu for a top-level page, you have to manually manage it in case the page structure changes. But you can make that decision for each top-level page individually, so you can leave some of them as is and only have to worry about the ones that you have overwritten. Again, this offers sensible defaults with good customizability. A downside is that the mixed approach may confuse the client, if some changes to the page tree are reflected in the drop-down menu directly, while others don't seem to have any effect (especially if you have multiple editors working on a site). Finding the right solution So how do you choose between the approaches? It depends on the client, the requirements, and on what special cases you expect and want to handle. Sometimes, a special request can be turned down by explaining how it would complicate editorial workflows or have a negative impact on SEO (for example, if you risk having some pages not accessible from the homepage at all). Also, make sure you understand the actual reason behind a change request, instead of just blindly implementing the suggestion by the client. Often, clients will suggest solutions without telling you what the actual problem is they're trying to solve. For example: In one case, I implemented the drop-down override mentioned in example three. However, what the client really wanted was to have the top-level page as the first item in the drop-down menu (see the example requests mentioned above). So they ended up overwriting every single drop-down menu, making the menu harder to maintain. In this case, it would have been better to go with a more specialized solution, such as adding a checkbox option, or even handling it in the code, since it would have been consistent throughout the menu. Another example was mentioned above: If the client requests an additional "Menu title" field, maybe what they really need is a "Headline" field. I recommend reading Articulating Design Decisions by Tom Greever; it includes some chapters on listening to the client, finding out the real reason behind a change request, and responding appropriately. It's written from a design perspective, but is applicable to development as well, and since UX becomes more important by the day, the lines between the disciplines are blurred anyway. Conclusion I realize now this reads more like a podcast (or worse, a rant) than an actual tutorial, but hopefully I got my point across. ProcessWire is at is greatest if you utilize it as a Content Management Framework, creating options and interfaces that allow for customizability while retaining usability for the client / editor. I usually try to hit a sweet spot where the editors have maximum control over the relevant aspects of their site, while requiring minimal work on their part by providing sensible defaults. Above, I listed some examples of requests I've gotten and different solutions I came up with to handle those with custom fields or templates. Though in some cases the requirements call for a custom solution or a quick hack in the template code as well! What are some of the special requests you got? How did you solve them? I'd love to get some insights and examples from you. Thanks for reading!
  8. @valan You need to include both the autoloader from Composer and the ProcessWire bootstrap file, see Bootstrapping ProcessWire CMS. Assuming your autoloader lives under prj/vendor/autoload.php and the webroot with the ProcessWire installation under prj/web/, you can use the following at the top of your script: # prj/console/myscript.php <?php namespace ProcessWire; # include composer autoloader require __DIR__ . '/../vendor/autoload.php'; # bootstrap processwire require __DIR__ . '/../web/index.php'; ProcessWire will detect that it is being included in this way and automatically load all the API variables (and the functions API, if you are using that). Keep in mind that there will be no $page variable, as there is no HTTP request, so there is no current page.
  9. @iipa You need to use the correct namespace by either aliasing the class with the use statement, or by using a fully qualified class name. As others have said though, it's much easier to use Composer with it's autoloader, since you only need to include it once and all classes will be autoloaded. It's also better for performance, as only the classes you actually use get loaded for each request. If you need help setting up Composer and the autoloader, check out my tutorial on Composer + ProcessWire πŸ™‚
  10. @stanoliver Assuming the text from your datarow field looks something like this: 100,200,300,400,500 You can use the explode function to split the string into an array using the commas as a delimiter. For example: $prices = explode(',', $page->datarow); // ["100", "200", "300", "400", "500"]
  11. @Pixrael Thanks, that makes perfect sense. Are you sure the query parameter doesn't work? It really should, since it's a different request and may return different results for some services. Maybe Chrome is employing some heuristics to determine that it's always the same image ... though it isn't in your case ... I don't know, sounds curious. In any case, your HTTP-header method is probably the best approach for this scenario! Though you really only need the Cache-Control header; Expires, ETag and and Pragma are superfluous except for the most legacy of legacy browsers πŸ˜› @dragan Firefox Developer Edition master race! 😜 Though I don't always have the Developer Tools open while writing my templates, and as you said I frequently need to test on other devices, so I prefer the caching busting approach. I usually have a $config->theme_version parameter in my config that gets appended to each CSS / JS URL, this way I can also easily invalidate caches on live sites when I push an update. During development (coupled to $config->debug) I just append the current timestamp, so the parameter changes for each request.
  12. @Pixrael A simpler approach that doesn't require any server-side adjustments at all would be to include the cache-busting parameter as a query variable instead. For example: /site/downloads/9VefFf6vstUR0q1ywzPgjXw4PfAgYqGp.png?v=1562618833 I use something like this during development for my CSS / JS assets, so the browser downloads those anew for each request and I see all changes immediately ... The browser will not use the cached image if the query string differs. This way you don't need to rewrite any URLs in Apache. I would also strongly advise not to go with the second approach (using HTTP-headers to disable caching), as this way the images can never be cached and reused, which means your site takes a major performance hit. Can I ask why you need to do this at all? If the browser has already loaded the image, why force it to load it again?
  13. @stanoliver I don't quite understand your situation, but if you have some data in an array, you have a couple of methods to output it. A simple foreach loop will keep the code at the same length regardless of how many columns you need: $prices = [ '100', '200', '300', '400', '500' ]; foreach ($prices as $price) { echo $price . ' '; } // output: // 100 200 300 400 500 // note there's one final space after "500" If you need to have something in between each item, for example a comma for CSV-style notation, you can use implode: $prices = [ '100', '200', '300', '400', '500' ]; echo implode(', ', $prices); // output: // 100, 200, 300, 400, 500 Finally, if you need to add something before or after each item or manipulate the items in some way, you can use array_map, which applies a callback function to each element of the array and returns a new array with the return values. For example, to wrap each element in double quotes for the CSV delimiters: $prices = [ '100', '200', '300', '400', '500' ]; echo implode(',', array_map(function ($price) { return '"' . $price . '"'; }, $prices)); // output: // "100","200","300","400","500"
  14. @stanoliver Great πŸ™‚ Array elements that are declared without a key are implicitly numeric in PHP, so the following declarations are equivalent: $colors = [ 'red', 'green', 'blue', ]; $colors = [ 0 => 'red', 1 => 'green', 2 => 'blue', ]; You can even mix numerical and associative arrays, but that only leads to confusion in my opinion, so I would avoid it.
  15. Just to clarify, which part don't you understand? The $data object is an associative array, so you can access the colors using the respective key: $colors = $page->meta('myData')['colors']; // ['red', 'green', 'blue'] The $colors array is an indexed / numerical array (i.e. it's not associativ), so you can access each of the colors using the numerical key of the position you want: $colors = $page->meta('myData')['colors']; // ['red', 'green', 'blue'] echo $colors[0]; // red echo $colors[2]; // blue Or are you stuck on how to use the meta method itself?
Γ—
Γ—
  • Create New...