Jump to content

Leaderboard

Popular Content

Showing content with the highest reputation on 12/29/2022 in all areas

  1. It's essential to my PW work as well so would definitely love to see it maintained, or at least some of its key features incorporated into the PW core which is probably the better approach. Maybe we should start a list of the features we all need and put together PRs for Ryan to get them into the core?
    2 points
  2. Hello all, I wanted to share a proof of concept approach on how we can have an infinite scroll pattern without writing Javascript. We can achieve this with htmx. What you will get An overview page with a list of posts (PW pages). On initial page load 5 posts will be shown. When scrolling down and reaching the last post, another 5 posts will be loaded via AJAX in the background and appended after the last post until no more pages are found. Prerequisites You are using the delayed output strategy, with a _main.php appended. Just like using the default site profile when installing ProcessWire You are using markup regions, in my _main.php I have a div#content that will be used for the output of the posts Inside site/config.php $config->useMarkupRegions = true; Inside site/templates/_main.php <!-- main content --> <div id='content'> </div> For script loading I am using a custom $config->bodyScripts FilenameArray Inside site/config.php $config->bodyScripts = new FilenameArray(); Inside site/templates/_main.php before the closing </body> tag <?php foreach ($config->bodyScripts as $file) : ?> <script src="<?= $file ?>"></script> <?php endforeach ?> </body> PW page structure for this tutorial In the page tree I have a parent page "Posts" with template "posts". All child pages of that page have template "post" In the template "posts" settings in the "URLs" tab, check "Allow Page Numbers" and save. Needed for pagination. When viewing the page "Posts" all logic happens inside site/templates/posts.php site/templates/posts.php <?php namespace ProcessWire; // posts.php template file // add htmx js from site/templates/scripts $config->bodyScripts->add($config->urls->templates . 'scripts/htmx.min.js'); $limit = 5; $posts = $pages->find("template=post, limit={$limit}"); $lastPost = $posts->last(); $nextPageUrl = $page->url . $input->pageNumStr((int) $input->pageNum() + 1); $hxAttributes = array(); $hxAttributes[] = 'hx-get="' . $nextPageUrl . '"'; $hxAttributes[] = 'hx-trigger="revealed"'; $hxAttributes[] = 'hx-swap="afterend"'; ?> <?php if (!$config->ajax) : ?> <section pw-append="content" class="posts" hx-headers='{"X-Requested-With": "XMLHttpRequest"}'> <?php endif ?> <?php foreach ($posts as $post) : ?> <article class="post" <?php if ($post == $lastPost) echo implode(' ', $hxAttributes) ?>> <header> <h3><?= $post->title ?></h3> </header> </article> <?php endforeach ?> <?php if ($config->ajax) return $this->halt() ?> <?php if (!$config->ajax) : ?> </section> <?php endif ?> And that is all there is to it. Not a single line of Javascript, thanks to htmx. I followed the infinite scroll pattern from the official htmx examples. Now let's break the code down into easily digestible chunks // add htmx js from site/templates/scripts $config->bodyScripts->add($config->urls->templates . 'scripts/htmx.min.js'); This adds site/templates/scripts/htmx.min.js to our custom $config->bodyScripts FilenameArray so it will be loaded in _main.php. You can get the script here from unpkg.com. $limit = 5; $posts = $pages->find("template=post, limit={$limit}"); Sets our pagination limit to 5 and loads the correct set of posts. $lastPost = $posts->last(); Saves the last post of each set. We use this later to determine whether the htmx attributes should be rendered. $nextPageUrl = $page->url . $input->pageNumStr((int) $input->pageNum() + 1); We are building the link to the next "page" with the next set of posts. Will result in something like "/posts/page2", "/posts/page3" etc. $hxAttributes = array(); $hxAttributes[] = 'hx-get="' . $nextPageUrl . '"'; $hxAttributes[] = 'hx-trigger="revealed"'; $hxAttributes[] = 'hx-swap="afterend"'; Define our htmx attributes as an array. They will be added to every last post's HTML. Note the hx-get attribute which will be the URL for the AJAX call in the background. That request is triggered whenever the last post becomes visible inside the viewport while scrolling down. hx-swap afterend tells htmx to append the next batch of posts after the last post. <?php if (!$config->ajax) : ?> <section pw-append="content" class="posts" hx-headers='{"X-Requested-With": "XMLHttpRequest"}'> <?php endif ?> // and <?php if (!$config->ajax) : ?> </section> <?php endif ?> Renders the wrapping section tag only on initial page load which is a none AJAX request. Note the hx-headers='{"X-Requested-With": "XMLHttpRequest"}'. This adds an additional header to all AJAX requests with htmx. We need this header so ProcessWire understands that it is an AJAX request. Otherwise $config->ajax would always return false. See https://htmx.org/attributes/hx-headers/ for more info <?php foreach ($posts as $post) : ?> <article class="post" <?php if ($post == $lastPost) echo implode(' ', $hxAttributes) ?>> <header> <h3><?= $post->title ?></h3> </header> </article> <?php endforeach ?> Render each posts's HTML. If it is the last post, also render our htmx attributes. For brevity in this example I only output the post title. <?php if ($config->ajax) return $this->halt() ?> For AJAX requests stop execution of the template file and everything that follows. This prevents appending of _main.php for ajax calls. So we only get the desired HTML for the list of posts and no head, footer etc. Summary Compared to other approaches, htmx lets us control all our AJAX logic with a few html attributes. Really neat and concise. Easypeasy. I like that and will surely use an approach like this in future when infinite scroll is needed. What I like in particular is how easy this is implemented with ProcessWire's powerful pagination capabilities. If you have the same page structure, the code in site/templates/posts.php is working out of the box as is. I have this running on a standard PW multilang site profile with additions/amendments mentioned above under "Prerequisites". Here's a visual of the result:
    2 points
  3. You are making a good and important point here. My short tutorial serves as a proof of concept like stated in the introduction. For a full fledged implementation UX has to be taken in account. To improve upon my example, we can add browser history support by adding the hx-push-url attribute. So the hxAttributes part of my code would look like $hxAttributes = array(); $hxAttributes[] = 'hx-get="' . $nextPageUrl . '"'; $hxAttributes[] = 'hx-push-url="' . $nextPageUrl . '"'; $hxAttributes[] = 'hx-trigger="revealed"'; $hxAttributes[] = 'hx-swap="afterend"'; Now if a user follows a link to a single post and then returns to the overview via browser back button, they'd land on the same page they left off. To make this behaviour smarter and have the previous pages (batches) load on scrolling up, we could expand the whole logic by placing htmx attributes on the first post of every page (batch) with hx-swap="beforebegin". If a user came to /posts/page6 through a shared link, they could scroll up until they reach /posts/page1. IMHO you cannot compare htmx to jQuery since they serve completely different purposes. I think it leverages PW pagination capabilities quite well. I don't think there is a "best" solution for this use case. It depends very much on the context. It may fit well with some projects and might not be a good solution for others.
    2 points
  4. ChatGPT will teach us something ... We really need a ProcessWire Conference ?
    2 points
  5. With all the hype about ChatGPT, I wanted to see how useful it could be for us ProcessWire lovers. In a word: wow! It's pretty darn impressive for such early public testing and for such targeted subject. I love how it proposes code with comments, then proceeds to explain it. (Note: I've been getting more impressive and consistent results on mobile for some reason.) Prompt: Filter blog post by category in ProcessWire To filter blog posts by category in ProcessWire, you can use the find method of the $pages object, along with the category field and the equals operator, like this: // Get the category slug from the URL $category_slug = $input->urlSegment1; // Find all blog posts in the given category $posts = $pages->find("template=blog-post, category.slug=$category_slug"); // Loop through the posts and output their titles foreach ($posts as $post) { echo "<h2>$post->title</h2>"; } This code will find all blog posts that are in the category with the given slug, and output their titles. You can modify this code to output other information about the posts, such as their content, images, or dates. To make it easier for users to filter posts by category, you can also create a navigation menu that lists all the available categories, like this: // Find all categories $categories = $pages->find("template=blog-category"); // Output a link for each category echo "<ul>"; foreach ($categories as $category) { echo "<li><a href='/blog/$category->slug'>$category->title</a></li>"; } echo "</ul>"; This code will find all blog categories and output a link for each one, using the category slug as the URL parameter. When a user clicks on a link, they will be taken to the blog page with the posts filtered by that category. Prompt: Login form in ProcessWire To create a login form in ProcessWire, you can use the following code: // Check if form has been submitted if ($input->post->submit) { // Sanitize user input $email = $sanitizer->email($input->post->email); $password = $sanitizer->text($input->post->password); // Check if user exists and password is correct $user = $users->get("email=$email"); if ($user && $user->matches($password)) { // Login user $session->login($user); // Redirect to home page $session->redirect("/"); } else { // Output error message $error = "Invalid email or password."; } } // Output login form echo "<form method='post'>"; echo "<label>Email:</label>"; echo "<input type='email' name='email' value='$email'>"; echo "<label>Password:</label>"; echo "<input type='password' name='password' value='$password'>"; echo "<input type='submit' name='submit' value='Login'>"; echo "</form>"; // Output any errors if ($error) { echo "<p class='error'>$error</p>"; } This code creates a login form that accepts an email and password. When the form is submitted, it checks if a user with the given email exists, and if the password is correct. If the email and password are valid, it logs in the user and redirects to the home page. If the email and password are invalid, it outputs an error message. Prompt: User registration class in ProcessWire with email, password of at least 10 characters and age over 18. Check if email is unique. To create a user registration class in ProcessWire with email, password of at least 10 characters, and age over 18, you can use the following code: class UserRegistration { public function register($email, $password, $age) { // Sanitize user input $email = $sanitizer->email($email); $password = $sanitizer->text($password); $age = (int) $age; // Validate user input if ($age < 18) { $errors[] = "You must be over 18 to register."; } if (strlen($password) < 10) { $errors[] = "Your password must be at least 10 characters long."; } if ($users->get("email=$email")) { $errors[] = "A user with this email already exists."; } // If no errors, create user account if (!$errors) { // Create new user $user = new User(); $user->email = $email; $user->password = $password; $user->age = $age; // Save user to database $user->save(); // Redirect to confirmation page $session->redirect("/confirmation"); } } } This code creates a UserRegistration class with a register method that takes an email, password, and age as arguments. The method sanitizes and validates the input, and creates a new user if the input is valid. It also checks if a user with the given email already exists in the database, and outputs an error if one does. To use this class, you would first instantiate it: $registration = new UserRegistration(); Then, you can call the register method to create a new user: $registration->register($email, $password, $age); Prompt (similar to previous one): User registration form in ProcessWire with first name, last name, email, password of at least 10 characters and age over 18. To create a user registration form in ProcessWire with first name, last name, email, password of at least 10 characters, and age over 18, you can use the following code: // Check if form has been submitted if ($input->post->submit) { // Sanitize user input $first_name = $sanitizer->text($input->post->first_name); $last_name = $sanitizer->text($input->post->last_name); $email = $sanitizer->email($input->post->email); $password = $sanitizer->text($input->post->password); $age = (int) $input->post->age; // Validate user input if ($age < 18) { $errors[] = "You must be over 18 to register."; } if (strlen($password) < 10) { $errors[] = "Your password must be at least 10 characters long."; } // If no errors, create user account if (!$errors) { // Create new user $user = new User(); $user->first_name = $first_name; $user->last_name = $last_name; $user->email = $email; $user->password = $password; $user->age = $age; // Save user to database $user->save(); // Redirect to confirmation page $session->redirect("/confirmation"); } } // Output registration form echo "<form method='post'>"; echo "<label>First Name:</label>"; echo "<input type='text' name='first_name' value='$first_name'>"; echo "<label>Last Name:</label>"; echo "<input type='text' name='last_name' value='$last_name'>"; echo "<label>Email:</label>"; echo "<input type='email' name='email' value='$email'>"; echo "<label>Password:</label>"; echo "<input type='password' name='password' value='$password'>"; echo "<label>Age:</label>"; echo "<input type='number' name='age' value='$age'>"; echo "<input type='submit' name='submit' value='Submit'>"; echo "</form>"; // Output any errors if ($errors) { foreach ($errors as $error) { echo "<p class='error'>$error</p>"; } } Watch out, this is addictive ?
    1 point
  6. Working! ? with this: <script type="text/plain" data-type="text/javascript" data-category="statistics"> /* piwik/matomo code */ </script> same if js is in an external file: <script type="text/plain" data-type="text/javascript" data-category="statistics" data-src="<?= $config->urls->templates ?>scripts/piwik.js"></script> And the best: I can reduce to "Accept all Cookies" and "Essential Cookies only" and it works! Same with the "Statistics" included as an Cookie group. All variants working! @ngrmmcan I contribute something for your help? (I work on a web server)
    1 point
  7. From my experience you have to remove type="text/javascript" or leave it empty.
    1 point
  8. Merry Christmas, Happy Hanukkah, and Happy Holidays! The plan is to release a newyear main/master core version. I'm not currently aware of any showstopper issues specific to the current dev branch, but if you are aware of any, please report them in the GitHub issues repo (or reply to an existing issue report), as the dev branch will soon become the master branch. There's not yet a hard deadline, so whether it's end of December or the 1st week of January, we'll have a new release out shortly. The dev branch is very stable right now (likely more stable than the master branch) so it's a good time to get a new version out. I've also been holding off on several larger updates to the dev branch in anticipation of this merge to master and new release, so I've likewise been holding back on any commits that would add more to test. Once we get a new main/master release out there, the dev branch will then get InputfieldTinyMCE merged into it and there will be some JS library updates, along with other larger updates, and those that would need dev branch testing. Thanks for reading and I hope that you have a great holiday weekend and week ahead
    1 point
  9. The problem: how to refresh a page's frontend content in real time without a page refresh when the page has been edited in the backend. This is an alternative approach to the one discussed in the topic below. The above topic attempts to solve the problem using SSE. The solution in this topic instead relies on Local Storage and htmx. There is no ajax polling. Please note that auto-refresh here refers to a page refresh during the same session and in the same domain. It is not cross-site. The solution can be summarised as follows: Use a hook in ready.php to inject custom JavaScript to the ProcessWire backend admin, specifically in ProcessPageEdit. This can be a JavaScript file or inline script. The purpose of this file is to update a given Local Storage key after a page has been edited. Instead of listening to the Save Button click, the script just checks on load if a certain hidden input whose value matches the page currently being edited is present. This hidden input is placed inside ProcessPageEdit form using a hook as detailed below. The hook in this step #1 can be: $this->addHookAfter('AdminTheme::getExtraMarkup', null, 'hookAddCustomScriptsToAdmin'); In ready.php, add a hook to listen to saveReady(), e.g. $this->addHookAfter('Pages::saveReady', null, 'hookNotifyFrontendOfBackendPageSave');. When the page is saved, the handler method hookNotifyFrontendOfBackendPageSave will check if there are changed fields. It will then write to a temporary session variable for the current page with the names of the fields that have changed. On page load/reload, there is a hook in ready.php that monitors ProcessPageEdit, i.e. $this->addHookAfter('ProcessPageEdit::execute', null, 'hookAddMarkupToNotifyFrontendOfBackendPageSave'); The handler hookAddMarkupToNotifyFrontendOfBackendPageSave will check if there is a session variable set in #2 indicating that the page has had recent changes in the fields names set to that session variable. If this is true (that there have been changes), this hook will simply append the hidden input in #1 to the ProcessPageEdit form. The JavaScript in #1 will detect the presence of the hidden input. It will then amend the Local Storage value in #1. It cannot simply set the value to the ID of the page being edited as that will not be construed as a change. It will instead append a timestamp to the id of the page as well and set that as the value. This will enable a listener in the frontend, described in the following steps, to detect that change. In the frontend, we have a simple JavaScript file that listens to changes to the Local Storage storage Event. The frontend also has a simple hidden input in the template file whose pages we want to refresh. This hidden input has htmx attributes. Its trigger is a custom event 'autorefreshpage'. It will listen for this event before firing a message to the server. This hidden input also has hx-swap=none as nothing will be swapped to it. Instead, the server will send back results of changed fields in various markup with hx-swap-oob=true. That will enable swapping markup in any parts of the frontend html in one go. When the Script at #4 detects that a given Local Storage value has changed, it first checks if the page ID for that Local Storage value matches the page ID of the page currently being viewed in the frontend. If the answer is yes, it will fire the custom event autorefreshpage. This will make htmx fire a message to the server whose only value is the page ID it has been passed. On the server, in home.php, we have code that is listening to ajax requests. If it detects an ajax request, it checks if the page ID that htmx sent matches an available session that was recently updated. This would be the temporary session detailed in #2 above. If a match is found, it calls a function in _func.php that will set variables for fields for that page. These use partial templates (optional). These partial templates are for different outputs of the page, e.g. images, headline, etc and all their markup have hx-swap-oob='true' in appropriate places. All these content is sent back as one output back to htmx. It will read the hx-swap-oob and find the markup to replace in the DOM using the html IDs of the markup with the hx-swap-oob. This approach allows the developer to have maximum control over what to send back to htmx and over the markup. In this step, we also delete the temporary session, ready for the next updates. The result is as demonstrated below. A simple and effective DOM swap that places very little strain on the server. I'll clean up the code for this and upload to GitHub. This approach will not work with Save + Exit and similar :-).
    1 point
  10. AI is great in producing text, that looks plausible, but it's not concerned with actual correctness. I'm working with elixir nowadays and there have been many examples posted, where responses claimed some API to exist in the stdlib, which just didn't. Looked totally fine on paper until you looked into the actual stdlib and found nothing. So really AI can be useful, but in the case of ChatGPT you really want someone chatting, who can actually validate the responses. Languages evolve and that's not a new thing at all. Take for example computer, which used to be a human doing math, and now is a machine. There's a good reason why we don't use natural language for programming our – now machine – computers. They're messy and not at all strictly defined.
    1 point
  11. Thank you! I already did it. My code was the following (in search view): <?php if($q = $sanitizer->selectorValue($input->get('q'))): ?> <?php if($pages->find('search_index%=' . $q)->count): ?> <?= $searchEngine->renderResults() ?> <?php else: ?> <?= $searchEngine->renderResults([], $searchEngine->find(Utils::handleSearch($q))) ?> <?php endif; ?> <?php endif; ?> I check first if there are search results in normal keyboard layout and then invert keyboard layout using Utils::handleSearch() method if there aren't any results.
    1 point
  12. One step closer, yes. But realistically, that's still not very close at all. Someone always needs to enter those prompts, after all. And while I've heard some people say an AI will always create more secure code than a human being, I don't believe that at all. So any code created by an AI should always be double-checked by a human being. The code examples ChatGPT is giving us right now is only snippets. There's still a lot of manual work needed in creating, say, a new Fieldtype and Inputfield. I've asked ChatGPT to create a Fieldtype and Inputfield and it wasn't able to show me a fully working example that didn't need a lot of manual editing. It always "forgot" some things, like the constructor, or it used a wrong parameter signature. Of course this will get better, but the more complex your prompts are becoming, the higher the risk the code simply will not work out of the box. The way I'm seeing it, AI is a great and valuable TOOL. It can save you from having to Google an answer for 30 minutes. It can give you some inspiration. But it's still just a tool, and for the foreseeable future, our jobs will be safe, because it's going to be US who will write the prompts and incorporate the code created. We shouldn't ignore it, and we need to learn to use it correctly. If all goes well, it might make our jobs a little easier, but shhh, don't tell our clients! Seriously though, yes, it's probably going to change things in the long term. See it as an evolution of our jobs. It might make SOME jobs obsolete. But frankly, comparing the clean elegance of ProcessWire with the convoluted mess of some other web frameworks and content management systems that keep reinventing the wheel every six months, you could argue if some web developers maybe should become obsolete. But finally, there's the issue that's been debated when it comes to art AI and Github Copilot already: copyright. AIs are always trained on existing material, and there will always be the risk that it simply lifts some code/art that has been released under an incompatible license. That's something a human will need to have an eye on, too.
    1 point
  13. Just to elaborate on another possible method, since getOptions() returns a SelectableOptionArray inheriting from WireArray, you could also do: $columns = $options->slices(3); https://processwire.com/api/ref/wire-array/slices/
    1 point
×
×
  • Create New...