Leaderboard
Popular Content
Showing content with the highest reputation on 04/23/2021 in all areas
-
The latest version on the dev branch will actually get the version bump tomorrow, as I'm currently on a 7-day work schedule with shorter days (factors outside my control). So what I'd usually be doing Friday is happening Saturday or Sunday instead. But the updates in 3.0.176 are well enough defined to write about here, and everything is there already, it's primarily just additional testing that remains before the version bump. Relative to 3.0.175 version 3.0.176 contains about 25 commits or so with most of the focus being resolution of minor issue reports. However, 25 commits is a lot so there are also some new things here too. First off, as requested, PW now supports multiple database read-only configuration settings rather than just one. When more than one is present, it will select one randomly. To use multiple read-only connections, simply specify a regular PHP array of 2 or more associative arrays in your /site/config.php file, like this: $config->dbReader = [ [ 'host' => 'mydb1.domain.com' ], [ 'host' => 'mydb2.domain.com' ], [ 'host' => 'mydb3.domain.com' ], ]; In each array item, you can specify 'host' (as above), along with any other setting (name, user, pass, port, etc.) that differs from the primary DB connection. There's another benefit to having multiple dbReader hosts as well: If the connection for one fails, it'll move on to the next, and keep moving on till it either finds a working connection or finishes the list. Next up, ProcessTemplate (Setup > Templates) gained a "Manage Tags" feature just like the one you have in ProcessField (Setup > Fields). So now it's a lot easier than before to define and manage tags for multiple templates as a group. In addition to this, both ProcessField and ProcessTemplate now have an actual Tags field (like the one available for files/images) rather than just a plain text input. The Template class also gained several new API functions for working with tags on templates. Templates in PW have supported tags for a long time, but now they are backed up by a much better API and admin interface to them. In order to support the new tags inputs in ProcessTemplate and ProcessField, a Tags Inputfield module was developed, named InputfieldTextTags (the name InputfieldTags was already taken). This module is now in the core, and it uses the existing Selectize tags functionality already present in the core, but previously only used by file and image fields. While developing this, I found it was a nice alternative to AsmSelect for sortable multiple selection, so made it available as an additional input option for both Page and Options fields. When used in a multiple-selection context, it ends up being a multiple selection input that takes up no more space than a text input, which can be quite handy for a lot of situations, and more space friendly then AsmSelect or even PageAutocomplete. I've noticed travel websites using a similar solution for multiple selection of destinations or amenities in search forms, and perhaps this one has some front-end potential as well. Since it's just an Inputfield without a dedicated Fieldtype, it is likely to work just as well on front-end forms (like FormBuilder) as it does on admin forms. Longer term I imagine we'll have an optional FieldtypeTextTags module as well, which will be useful for supporting user-entered tags sharable between pages. Currently it does support user entered tags if you choose it as an input option for a regular "text" field (see bottom of Details tab in field editor), and it can optionally be combined with predefined selectable tags as well. While all of these updates are on the dev branch now, look for the version bump this weekend after I've had a little more time testing. Though if you'd like to help test, feel free to grab it now. Thanks for reading and have a great weekend!16 points
-
Thanks! Currently "id", "name", and "title" are indexed automatically for page reference fields. If a programmatic approach is easy enough, you can modify this behaviour and add more fields by hooking before Indexer::getPageReferenceIndexValue() and modifying the $indexed_fields argument. Alternatively you could hook into this method and in specific cases replace the behaviour completely, for an example by returning the output of the indexPage() method for each individual page instead (here's a loosely related example). Let me know if you need additional pointers and I can provide some sample code.2 points
-
I guess a curious question will be for Modules developers any of your modules breaking with PHP 8 and great to be back to this forum.2 points
-
ConnectPageFields Allows the connecting of two related Page fields so that changing one updates the other. Purpose of module An example: suppose your website is about movies. You have a template "movie" with Page field "actors". For each movie you add the actors that appear in the movie. All good, but what if you want to find results like... the 10 actors who have appeared in the most movies actors who haven't appeared in any movies since 1990 You cannot retrieve these pages with a single efficient $pages->find() query, and must load a large PageArray into memory in order to iterate or filter it. For the sake of making these types of queries more efficient you could structure your templates/fields so that movies are added to actors instead, but this may be a less comfortable workflow and can run into equivalent problems (e.g. "find the 10 movies with the largest cast"). The solution is to have a two-way relationship so that movie pages have an "actors" Page field and actor pages have a "movies" Page field. This module will keep these two Page fields in sync so that adding "Ryan Gosling" to "Drive" automatically adds "Drive" to "Ryan Gosling". Also, you can select the same Page field in both Page field A and Page field B. For example, create a "Related" Page field for related pages. Choose "Related" for both fields in a pair in the module config. Now when you add "Orange buffoon" to Related for "Donald Trump", "Donald Trump" is automatically added to Related for "Orange buffoon". Usage Install the ConnectPageFields module. If you haven't already done so, create the two Page fields you want to connect and add them to templates. In the module config select the two Page fields in a "Connected field pair" row as Page field A and Page field B. You can add rows as needed using the "Add another row" button. Troubleshooting Make sure you have set the "Selectable Pages" settings for each Page field correctly: The settings for Page field A should allow pages using the template(s) that Page field B has been added to. The settings for Page field B should allow pages using the template(s) that Page field A has been added to. http://modules.processwire.com/modules/connect-page-fields/ https://github.com/Toutouwai/ConnectPageFields Module config: Demo showing how changing one Page field updates the other:1 point
-
I've been meaning to revise PageimageSrcset for a while now, to remove some features that I felt were unnecessary and to implement a better rendering strategy. The result is PageimageSource. What does it do? It provides a configurable srcset method/property for Pageimage It allows WebP to be enabled for images it generates. It allows Pageimage:render() to return a <picture> element It provides a Textformatter that replaces <img> elements with the output of Pageimage:render() Although it is based on a current module, this should still be considered beta and not used in production without a prior development stage. Here's the README: PageimageSource Extends Pageimage with a srcset property/method plus additional rendering options. Overview The main purpose of this module is to make srcset implementation as simple as possible in your template code. For an introduction to srcset, please read this Mozilla article about responsive images. Installation Download the zip file at Github or clone the repo into your site/modules directory. If you downloaded the zip file, extract it in your sites/modules directory. In your admin, go to Modules > Refresh, then Modules > New, then click on the Install button for this module. ProcessWire >= 3.0.165 and PHP >= 7.3 are required to use this module. Configuration To configure this module, go to Modules > Configure > PageimageSource. Default Set Rules These are the default set rules that will be used when none are specified, e.g. when calling the property: $image->srcset. Each set rule should be entered on a new line, in the format {width}x{height} {inherentwidth}w|{resolution}x. Not all arguments are required - you will probably find that specifying the width is sufficient for most cases. Here's a few examples of valid set rules and the sets they generate: Set Rule Set Generated Arguments Used 320 image.320x0-srcset.jpg 320w {width} 480x540 image.480x540-srcset.jpg 480w {width}x{height} 640x480 768w image.640x480-srcset.jpg 768w {width}x{height} {inherentwidth}w 2048 2x image.2048x0-srcset.jpg 2x {width} {resolution}x How you configure your rules is dependent on the needs of the site you are developing; there are no prescriptive rules that will meet the needs of most situations. This article gives a good overview of some of the things to consider. When you save your rules, a preview of the sets generated and an equivalent method call will be displayed to the right. Invalid rules will not be used, and you will be notified of this. WebP If enabled, WebP versions of the image and srcset variations will be generated and these will be returned by Pageimage::srcset(). As with the default implementation, the image with the smaller file size is returned. In most cases this is the WebP version, but sometimes can be the source. Make sure to experiment with the quality setting to find a value you find suitable. The default value of 90 is fine, but it is possible that lower values will give you excellent kB savings with little change in overall quality. For more information on WebP implementation please read the blog posts on the ProcessWire website. Rendering These settings control how the output of Pageimage::render() is modified. Use Lazy Loading? When enabled this adds loading="lazy" to the <img> attributes. It is useful to have this on by default, and you can always override it in the options for a specific image. Use the <picture> element? When enabled, the <img> element is wrapped in a <picture> element and <source> elements for original and WebP variations are provided. This requires WebP to be enabled. For more information on what this does, have a look at the examples in Pageimage::render() below. Remove Variations If checked, the image variations generated by this module are cleared on Submit. On large sites, this may take a while. It makes sense to run this after you have made changes to the set rules. Please note that although the module will generate WebP versions of all images if enabled, it will only remove the variations with the 'srcset' suffix. Usage Pageimage::srcset() // The property, which uses the set rules in the module configuration $srcset = $image->srcset; // A method call, using a set rules string // Delimiting with a newline (\n) would also work, but not as readable $srcset = $image->srcset('320, 480, 640x480 768w, 1240, 2048 2x'); // The same as above but using an indexed/sequential array $srcset = $image->srcset([ '320', '480', '640x480 768w', '1240', '2048 2x', ]); // The same as above but using an associative array // No rule checking is performed $srcset = $image->srcset([ '320w' => [320], '480w' => [480], '768w' => [640, 480], '1240w' => [1240], '2x' => [2048], ]); // The set rules above are a demonstration, not a recommendation! Image variations are only created for set rules which require a smaller image than the Pageimage itself. This may still result in a lot of images being generated. If you have limited storage, please use this module wisely. Pageimage::render() This module extends the options available to this method with: srcset: When the module is installed, this will always be added, unless set to false. Any values in the formats described above can be passed. sizes: If no sizes are specified, a default of 100vw is assumed. lazy: Pass true to add loading=lazy, otherwise false to disable if enabled in the module configuration. picture: Pass true to use the <picture> element, otherwise false to disable if enabled in the module configuration. Please refer to the API Reference for more information about this method. // Render an image using the default set rules // WebP and lazy loading are enabled, and example output is given for <picture> disabled and enabled echo $image->render(); // <img src='image.webp' alt='' srcset='image.jpg...' sizes='100vw' loading='lazy'> /* <picture> <source srcset="image.webp..." sizes="100vw" type="image/webp"> <source srcset="image.jpg..." sizes="100vw" type="image/jpeg"> <img src="image.jpg" alt="" loading="lazy"> </picture> */ // Render an image using custom set rules echo $image->render(['srcset' => '480, 1240x640']); // <img src='image.webp' alt='' srcset='image.480x0-srcset.webp 480w, image.1240x640-srcset.webp 1240w' sizes='100vw' loading='lazy'> /* <picture> <source srcset="image.480x0-srcset.webp 480w, image.1240x640-srcset.webp 1240w" sizes="100vw" type="image/webp"> <source srcset="image.480x0-srcset.jpg 480w, image.1240x640-srcset.jpg 1240w" sizes="100vw" type="image/jpeg"> <img src="image.jpg" alt="" loading="lazy"> </picture> */ // Render an image using custom set rules and sizes // Also use the `markup` argument // Also disable lazy loading // In this example the original jpg is smaller than the webp version echo $image->render('<img class="image" src="{url}" alt="Image">', [ 'srcset' => '480, 1240', 'sizes' => '(min-width: 1240px) 50vw', 'lazy' => false, ]); // <img class='image' src='image.jpg' alt='Image' srcset='image.480x0-srcset.webp 480w, image.1240x0-srcset.webp 1240w' sizes='(min-width: 1240px) 50vw'> /* <picture> <source srcset="image.480x0-srcset.webp 480w, image.1240x0-srcset.webp 1240w" sizes="(min-width: 1240px) 50vw" type="image/webp"> <source srcset="image.480x0-srcset.jpg 480w, image.1240x0-srcset.jpg 1240w" sizes="(min-width: 1240px) 50vw" type="image/jpeg"> <img class='image' src='image.jpg' alt='Image'> </picture> */ // Render an image using custom set rules and sizes // These rules will render 'portrait' versions of the image for tablet and mobile // Note the advanced use of the `srcset` option passing both `rules` and image `options` // WebP is disabled // Picture is disabled echo $image->render([ 'srcset' => [ 'rules' => '320x569, 640x1138, 768x1365, 1024, 1366, 1600, 1920', 'options' => [ 'upscaling' => true, 'hidpi' => true, ], ], 'sizes' => '(orientation: portrait) and (max-width: 640px) 50vw', 'picture' => false, ]); // <img src='image.jpg' alt='' srcset='image.320x569-srcset-hidpi.jpg 320w, image.640x1138-srcset-hidpi.jpg 640w, image.768x1365-srcset-hidpi.jpg 768w, image.1024x0-srcset-hidpi.jpg 1024w, image.1366x0-srcset-hidpi.jpg 1366w, image.1600x0-srcset-hidpi.jpg 1600w, image.jpg 1920w' sizes='(orientation: portrait) and (max-width: 768px) 50vw' loading="lazy"> TextformatterPageimageSource Bundled with this module is a Textformatter largely based on TextformatterWebpImages by Ryan Cramer. When applied to a field, it searches for <img> elements and replaces them with the default output of Pageimage::render() for each image/image variation. Assuming a default set of 480, 960 and lazy loading enabled, here are some examples of what would be returned: Example <figure class="align_right hidpi"> <a href="/site/assets/files/1/example.jpg"> <img alt="" src="/site/assets/files/1/example.300x0-is-hidpi.jpg" width="300" /> </a> </figure> WebP enabled <figure class="align_right hidpi"> <a href="/site/assets/files/1/example.jpg"> <img alt="" src="/site/assets/files/1/example.300x0-is-hidpi.webp" width="300" srcset="/site/assets/files/1/example.300x0-is-hidpi.webp 480w" sizes="100vw" loading="lazy" /> </a> </figure> <picture> enabled <figure class="align_right hidpi"> <a href="/site/assets/files/1/example.jpg"> <picture> <source srcset="/site/assets/files/1/example.300x0-is-hidpi.webp 480w" sizes="100vw" type="image/webp"> <source srcset="/site/assets/files/1/example.300x0-is-hidpi.jpg 480w" sizes="100vw" type="image/jpeg"> <img alt="" src="/site/assets/files/1/example.300x0-is-hidpi.jpg" width="300" loading="lazy" /> </picture> </a> </figure> Because the variation is small - 300px wide - the srcset only returns the source image variation at the lowest set width (480w). If the source image was > 1000px wide, there would be a variation at both 480w and 960w. PageimageSrcset This module is built upon work done for PageimageSrcset, which can be considered a first iteration of this module, and is now deprecated. Migration PageimageSource is a simplified version of PageimageSrcset with a different approach to rendering. Most of the features of the old module have been removed. If you were just using $image->srcset(), migration should be possible, as this functionality is essentially the same albeit with some improvements to image variation generation.1 point
-
Kerim Pamuk https://www.kerimpamuk.de/ Client details Kerim Pamuk a turkish/german author and cabaret artist with such a kind of detailed humor for details you have to listen very closely and think twice to really appreciate his Wortspiele (en: puns) and anecdotes. Some more details about Kerim Pamuk (one of our first clients with a personal Wikipedia page): https://de.wikipedia.org/wiki/Kerim_Pamuk Design details As you can see... Bright colors, big typo, and subtle animations to emphasize the already bold visual statement. No miss but a lot of hits wherever you watch, like the stage program performed by Kerim Pamuk himself. The original design and the entire frontend were built in Webflow by the designer but was migrated over to ProcessWire later on. Some tweaks were made during the migration process to keep things a bit more flexible and easier to maintain on the long run. Technical details There is not that much in the backend to show or tell. Only a few tweaks and hooks in order to maintain all events automatically. Adding additional press statements, books or any other kind of content is simple and straightforward as always in ProcessWire. Modules used: Cookie Management Banner: for the obvious reason FieldtypeColor: for custom colors on sub-pages if needed PageHitCounter: as alternative to Google Analytics and Matomo ImportPagesfromCSV: importing new events to the site with ease (maintained by the client) Markup Sitemap XML: you know why Jumplinks: in case things change or someone needs a nice pretty link ProCache (Pro): ProcessWire is fast - with ProCache even faster VerifiedURL (Pro): to keep track of all linked event locations The team behind this: Muskaat for the technical part (yes, I'm part of Muskaat) https://www.muskaat.de/ Polimorf for the design part https://www.polimorf.de/ I hope you'll enjoy this site as much as I do!1 point
-
This week I didn't get as much time as I'd hoped to work on the core, but still managed to get a few things done. I did get some small core updates in place, but not enough for a version bump, and got the second covid vaccine, kids back to in-person school (3 hours a day, after a year of being away), and a couple more major module upgrades released. In last week's post, someone asked for an update to the ProcessWireUpgrade module, and I had a look and a realized it was long overdue for one, so I tried to cover a lot of ground there. The new version is now out and improved throughout. Grab this latest version of ProcessWireUpgrade if you are interested. It's always been pretty useful, but it's even more so now. I've also updated the modules directory feed so that it can let you know when Pro module upgrades are available as well (as requested). The ProcessWireUpgrade module reports this Pro module information in a clear manner too. Some improvements have also been made to the core version updating features as well. The other module updated was FieldtypeEvents, a module that demonstrates how to create simple a Fieldtype+Inputfield module pair that has repeatable rows of multiple columns. The last version was made for PW 2.x, so I largely rewrote the module while updating it for PW 3.x. It's been simplified quite a bit so that it can be even more clear how to adapt it to create your own custom module. Being PW 3.x exclusive also opened more doors in keeping it simple but powerful. If you don't mind doing a little customization in adapting the code for your purposes, this module can be every bit as powerful in solving custom needs as Repeaters, but without Repeater overhead. I updated this module because another ProcessWire user was asking about how to store multiple columns of repeatable data for 20-million pages. Repeaters would be too much overhead at that scale, though FieldtypeTable could fit the bill. But at such a large scale, I thought a custom Fieldtype would be even better. So FieldtypeEvents shows you how to do it, and it's [hopefully] simpler than you might think. This has nothing to do with PW, but to follow up from last week, that second dose of the covid vaccine was an interesting experience. I got the shot (jab?) and strangely didn't feel a thing. I walked home and took the band-aid off my arm and noticed there was no sign of anything, no little pin prick or red spot, and a completely clean band-aid. I started to wonder if I'd been fooled or something. If someone sticks a needle in your arm, you should feel it right? And there should be some evidence of it? Well there wasn't (and no I didn't watch the needle, who would do that?). They also told me I'd feel ill for a day or two, and I felt completely fine even the next morning. But then 10 am rolled around and my arm started feeling sore and I was suddenly very tired. So tired that it was laborious to walk, sit at the computer, or do anything other than chill on the couch. That might sound undesirable, but it wasn't uncomfortable, and it was kind of funny being so ridiculously tired, but also really relieved. It meant it was working and my body was getting a download on how to battle covid, and putting all its resources into taking it seriously. It was fascinating, so I just crashed on the couch, relaxed and let it do its thing. By the next day, full energy was back, batteries recharged, upgrades installed. From what I understand, some people have no side effects, but I was one of those that did. Though if anything I enjoyed the different experience for a day, and the comfort of clear evidence it was working.1 point
-
I found another solution and it works for me. First I loop through my pages and save the needed content into a helper-textarea-field. I added this helper-field into the indexed fields and this works. I guess this is not the best for the performance but it works for me. Thanks again1 point
-
Great — let me know if you run into any trouble and I'll be happy to help! If you mean which file, for this purpose (saving pages in the admin) you could put the hook into site/templates/admin.php, but site/init.php is likely just as good (and also catches page saves that occur outside the admin).1 point
-
Thanks @teppo This exact text in a textarea with a HTML Entity Encoder textformatter should allow you to replicate the issue. After attending a former colleague's birthday party, Bill Dennison recounts fond memories of time he spent with Tony Larkum in Australia and the United States that spanned from the 80's through early 2000's. Yes, sorry about that ?1 point
-
Seems reasonable. In fact I had similar issues earlier, but those were fixed by switching from substr() to mb_substr(). This case seems a bit different, though. I'll try to set up a test case and see what I can do about that; so far I've only managed to end up with a partial encoded entity, 80& instead of 80' and so on ? Meanwhile I noticed that in some cases the new auto desc feature generates odd looking "......" character sequences and other weird results, so there's more to tweak anyway. I'll try to dedicate some time to this in the next few days. Just to make sure: did you mean HTML Entity Encoder?1 point
-
In v0.1.2 I've added support for columns to be saved in bookmarks. See the updated readme for details, and the screenshot for how you can easily copy/paste a bookmark string from the bottom of the Lister Selector results. Are you able to do this in the core Lister or Lister Pro? This module uses Lister/ListerPro internally and doesn't do anything different with the results section. So maybe a question for the general forum or Lister Pro board rather than for this module thread.1 point
-
It seems that the columns are not saved with the bookmark. Are you planning to add that feature?1 point
-
v0.0.56 Today I had some troubles migrating field labels. Changes simply did not show up on the related page edit screen... turned out that some field setting overrides have been activated! Removing them via API is not that simple, so I added the feature to RM: ?1 point
-
Hi @Robin S That's a very useful module. Thank you. Any idea how to get the values instead of the titles on a specific options field with a hook?1 point
-
In this tutorial I will cover how to use clsource's REST Helper classes to create a RESTful API endpoint within a PW-powered site and how to connect to it from the outside world with a REST client. This is a quite lengthy tutorial. If you follow all along and make it through to the end, you should get both, a working REST API with ProcessWire and hopefully some more basic understanding how these APIs work. As always with PW, there are many ways you could do this. My way of implementing it and the code examples are loosely based on a real world project that I am working on. Also, this is the first tutorial I am writing, so please bear with me if my instructions and examples are not that clear to understand. And please let me know if something is missing or could be made more clear. The steps covered: create templates and pages in the PW backend to get an API endpoint (an URL where the API can be accessed at) copy and save the REST Helper classes to your site create a template file and write some logic to receive and process data through our endpoint and send data back to the REST client test the whole setup with a Browser REST Client Addon I will not go into fundamentals and technical details on how RESTful APis are supposed to work. I assume that you have already read up on that and have a basic understanding of the principles behind that technology. Some helpful resources to brush up your knowledge: https://en.wikipedia.org/wiki/Representational_state_transfer http://www.restapitutorial.com/lessons/whatisrest.html The complete pages.php template is attached to this post for copy/paste. Lets get started. 1. create templates and pages in the PW backend to get an API endpoint (an URL where the API can be accessed) First we need to create some templates and pages in the PW backend to make our REST API accessible from the outside world through an URL (API endpoint). In my example this URL will be: https://mysite.dev/api/pages/ Note the "https" part. While this is not mandatory, I strongly recommend having your API endpoint use the https protocol, for security reasons. Further down in step 3 we will use this URL to create new pages / update and get data of existing pages. Go to your PW test site admin and: create 2 new templates: one is called "api", the other one "pages". For a start, they both have only a title field assigned. Just create the templates. We will create the corresponding files later, when we need them. enable "allow URL segments" for the "pages" template. We will need this later to access data sent by the requests from the client. in the Files tab of the "pages" template check "Disable automatic append of file: _main.php" create a new page under the home page with title, name and template "api" and set it to hidden create a child page for the "api" page with title, name and template "pages" The pagetree should look somewhat like this: Ok, now we're all set up for creating our API endpoint. If you browse to https://mysite.dev/api/pages/ you will most likely get a 404 error or will be redirected to your home page as we do not have a template file yet for the "pages" template. We will add that later in step 3. 2. copy and save the REST Helper classes to your site I have the REST Helper class sitting in site/templates/inc/Rest.php and include it from there. You could save it in any other location within your site/templates folder. I forked clsource's original code to add basic HTTP authentication support. Click here to open my raw gist, copy the contents and save them to /site/templates/inc/Rest.php In the next step we will include this file to make the classes "Rest" and "Request" available to our template file. 3. create a template file and write some logic to receive and process data through our endpoint and send data back to the client This will be the longest and most complex part of the tutorial. But I will try to present it in small, easy to follow chunks. Since we access our API at https://mysite.dev/api/pages/, we need to create a template file called "pages.php" for our "pages" template and save it to /site/templates/pages.php. Go ahead and create this file (if you're lazy, copy the attached file). Now right at the top of pages.php, we start with <?php require_once "./inc/Rest.php"; to include the REST Helper classes. Next, we initialize some variables that we will keep using later on // set vars with the default output $statuscode = 200; $response = []; $header = Rest\Header::mimeType('json'); 3.1 retrieve data with a GET request Now that we have the basics set up, we will next create the code for handling the easiest request type, a GET request. With the GET request we will ask the API to return data for an existing page. To let the API know which page it should return data for, we need to send the page id along with our request. I am attaching the page id as an url segment to the API endpoint. So the URL that the client will use to retrieve data for a page will look like: https://mysite.dev/api/pages/1234 where 1234 is the unique page id. Add following code to pages.php // if we have an urlsegment and it is a numeric string we get data from or update an existing page: handle GET and PUT requests if($input->urlSegment1 && is_numeric($input->urlSegment1)) { $pageId = $input->urlSegment1; // GET request: get data from existing page if(Rest\Request::is('get')) { // get the page for given Id $p = $pages->get($pageId); if($p->id) { $pdata = ["id" => $pageId]; // array for storing page data with added page id $p->of(false); // set output formatting to false before retrieving page data // loop through the page fields and add their names and values to $pdata array foreach($p->template->fieldgroup as $field) { if($field->type instanceof FieldtypeFieldsetOpen) continue; $value = $p->get($field->name); $pdata[$field->name] = $field->type->sleepValue($p, $field, $value); } $response = $pdata; } else { //page does not exist $response["error"] = "The page does not exist"; $statuscode = 404; // Not Found (see /site/templates/inc/Rest.php) } } } else { // no url segment: handle POST requests } // render the response and body http_response_code($statuscode); header($header); echo json_encode($response); Lets brake this down: First we check for a numeric url segment which is our $pageId. Then the Rest Request class comes into play and checks what type of request is coming in from the client. For the GET request, we want to return all data that is stored for a page plus the page id. This is all good old PW API code. I am using the $pdata array to store all page data. Then I am handing this array over to the $response variable. This will be used further down to render the JSON response body. If the page does not exist, I am setting an error message for the $response and a status code 404 so the client will know what went wrong. The else statement will later hold our POST request handling. The last 3 lines of code are setting the header and status code for the response and print out the response body that is sent back to the client. You can now browse to https://mysite.dev/api/pages/1 where you should see a JSON string with field names and values of your home page. If you enter a page id which does not exist you should see a JSON string with the error message. Lets move on to updating pages through a PUT request 3.2 update pages with a PUT request Since our API needs to know the id of the page we want to update, we again need to append an id to our endpoint url. In this example we will update the title and name of our homepage. So the request url will be: https://mysite.dev/api/pages/1. For the GET request above, anyone can connect to our API to retrieve page data. For the PUT request this is not a good idea. Thus we will add basic authentication so that only authorized clients can make updates. I use basic HTTP authentication with username and password. In combination with the https protocol this should be fairly safe. To set this up, we need an API key for the password and a username of our choosing. We add the API key in the PW backend: add a new text field "key" and assign it to the "api" template. edit the "api" page, enter your key and save. (I am using 123456 as key for this tutorial) Now add following code right after the if(Rest\Request::is('get')) {...} statement: // PUT request: update data of existing page if(Rest\Request::is('put')) { // get data that was sent from the client in the request body + username and pass for authentication $params = Rest\Request::params(); // verify that this is an authorized request (kept very basic) $apiKey = $pages->get("template=api")->key; $apiUser = "myapiuser"; if($params["uname"] != $apiUser || $params["upass"] != $apiKey) { // unauthorized request $response["error"] = "Authorization failed"; $statuscode = 401; // Unauthorized (see /site/templates/inc/Rest.php) } else { // authorized request // get the page for given Id $p = $pages->get($pageId); if($p->id) { $p->of(false); $p->title = $sanitizer->text($params["title"]); $p->name = $sanitizer->pageName($params["name"]); $p->save(); $response["success"] = "Page updated successfully"; } else { // page does not exist $response["error"] = "The page does not exist"; $statuscode = 404; // Not Found (see /site/templates/inc/Rest.php) } } } Breakdown: We check if the request from the client is a put request. All data that was sent by the client is available through the $params array. The $params array also includes $params["uname"] and $params["upass"] which hold our API user and key. We set API key and user and check if they match with the values that were sent by the client. If they don't match we store an error message to the response body and set the appropriate status code. If authentication went through ok, we get the page via PW API and update the values that were sent in the request body by the client. Then we put out a success message in the response body. If the page does not exist, we send the appropriate response message and status code, just like in the GET request example above. Now you might wonder how the client sends API user/key and new data for updating title and name. This is covered further down in step 4. If you want to test the PUT request right now, head down there and follow the instructions. If not, continue reading on how to setup a POST request for creating new pages. 3.2 create new pages with a POST request Final part of the coding part is creating new pages through our API. For this to work we need to implement a POST request that sends all the data that we need for page creation. We will do this at our endpoint: https://mysite.dev/api/pages/ Paste following code within the else statement that has the comment "// no url segment: handle POST requests": // POST request: create new page if(Rest\Request::is('post')) { // get data that was sent from the client in the request body + username and pass for authentication $params = Rest\Request::params(); // verify that this is an authorized request (kept very basic) $apiKey = $pages->get("template=api")->key; $apiUser = "myapiuser"; if($params["uname"] != $apiUser || $params["upass"] != $apiKey) { // unauthorized request $response["error"] = "Authorization failed"; $statuscode = 401; // Unauthorized (see /site/templates/inc/Rest.php) } else { // authorized request // create the new page $p = new Page(); $p->template = $sanitizer->text($params["template"]); $p->parent = $pages->get($sanitizer->text($params["parent"])); $p->name = $sanitizer->pageName($params["name"]); $p->title = $sanitizer->text($params["title"]); $p->save(); if($p->id) { $response["success"] = "Page created successfully"; $response["url"] = "https://mysite.dev/api/pages/{$p->id}"; } else { // page does not exist $response["error"] = "Something went wrong"; $statuscode = 404; // just as a dummy. Real error code depends on the type of error. } } } You already know what most of this code is doing (checking authorisation etc.). Here's what is new: We create a page through the PW API and assign it a template, a parent and basic content that was sent by the client. We check if the page has been saved and update our response body array with a success message and the URL that this page will be accessible at through the API for future requests. The client can store this URL for making GET or PUT requests to this page. If you're still reading, you have made it through the hard part of this tutorial. Congratulations. Having our code for reading, updating and creating pages, we now need a way to test the whole scenario. Read on to find out how this can be done. 4. test the whole setup with a Browser REST Client Addon The link in the heading will take you to a place from which you can install the very useful RESTClient addon to your favorite browser. I am using it with Firefox which is still the dev browser of my choice. Open a RESTClient session by clicking the little red square icon in the browsers addon bar. The UI is pretty straightforward and intuitive to use. 4.1 test the GET request Choose Method GET and fill in the URL to our endpoint. If you do not have a SSL setup for testing, just use http://yourrealtestdomain.dev/api/pages/1. If you happen to have a SSL test site with a self signed certificate, you need to point your browser to the URL https://yourrealtestdomain.dev/api/pages/ first in your test browser and add the security exception permanently. Otherwise RESTClient addon won't be able to retrieve data. If you have a test site with a 'real' SSL certificate, everything should be fine with using the https://... URL Hit send. In the Response Headers tab you should see a Status Code 200 and in the Response Body tabs a JSON string with data of your page. now change the 1 i the URL to some id that does not exist in your site and hit send again. You should get a 404 Status Code in the Response Headers tab and an error message "{"error":"The page does not exist"}" in the Response Body (Raw) tab. If you get these results, congrats! The GET request is working. For further testing you can save this request through the top menu Favorite Requests->Save Current Request. 4.1 test the PUT request Choose Method PUT and fill in the URL to our endpoint ending with 1 (http://yourrealtestdomain.dev/api/pages/1). In the top left click Headers->Content-Type: application/json to add the right content type to our request. If you miss this step, the request will not work. You will now see a "Headers" panel with all your headers for this request Click on Authentication->Basic Authentication. In the modal window that pops up, fill in user (myapiuser) and password (your API key). Check "Remember me" and hit Okay. You now should see Content-Type and Authorization headers in the "Headers" panel. Next, we need to send some data in the request body for updating our page title and name. Since we're using JSON, we need to create a JSON string that contains the data that we want to send. As I will update the home page for this example, my JSON reads { "title" : "Newhome", "name" : "newhome" } Be careful that you have a well formed string here. Otherwise you will get errors. Paste this into the "Body" panel of the REST Client addon. Hit send. In the Response Headers tab you should see a Status Code 200 and in the Response Body tabs a JSON string "{"success":"Page updated successfully"}". Now go to the PW backend and check if title and name of your page have been updated. If yes, congrats again. 4.2 test the POST request Choose Method POST and fill in the URL to our endpoint without any page id (http://yourrealtestdomain.dev/api/pages/). In the top left click Headers->Content-Type: application/json to add the right content type to our request. If you miss this step, the request will not work. You will now see a "Headers" panel with all your headers for this request Click on Authentication->Basic Authentication. In the modal window that pops up, fill in user (myapiuser) and password (your API key). Check "Remenber me" and hit Okay. You now should see Content-Type and Authorization headers in the "Headers" panel. Next, we need to send some data in the request body for updating our page title and name. Since we're using JSON, we need to create a JSON string that contains the data that we want to send. I will create a new page with template basic-page and parent /about/ for this example, my JSON reads { "template" : "basic-page", "parent" : "/about/", "title" : "New Page created through api", "name" : "newapipage" } Be careful that you have a well formed string here. Otherwise you will get errors. Paste this into the "Body" panel of the REST Client addon. Hit send. In the Response Headers tab you should see a Status Code 200 and in the Response Body tabs a JSON string "{"success":"Page created successfully","url":"https:\/\/mysite.dev\/api\/pages\/1019"}". Now go to the PW backend and check if title and name of your page have been updated. If yes, you're awesome! Summary By now you have learned how to build a simple REST API with ProcessWire for exchanging data with mobile devices or other websites. Notes I tested this on a fresh PW 2.7.2 stable install with the minimal site profile and can confirm the code is working. If you experience any difficulties in getting this to work for you, let me know and I will try to help. There purposely is quite a lot of repetion in the example code to make it easier to digest. In real life code you might not want to use procedural coding style but rather separate repeating logic out into classes/methods. Also, in life applications you should do more sanity checks for the authentication of clients with the API / for the data that is delivered by the client requests and more solid error handling. I skipped these to make the code shorter. RESTful services are by definition stateless (sessionless). My implementation within PW still opens a new session for each request and I haven't found a way around that yet. If anyone can help out this would be much appreciated. And finally big thanks to clsource for putting the Rest.php classes together. pages.php.zip1 point
-
Just a searchable note here in case s.o. else runs into the same problem ? You suddenly cannot log in any more with TFA/2FA (Two Factor Authentification)? After the step two (inserting the 2FA code) the server responds with an ERROR 500? There is no corresponding entry in the server logs? Check this: Open your site files with FTP, go to /site/assets/logs/ and look into the file exceptions.txt If you find an entry there, like so: ... Invalid base32 string (in /site/modules/TfaTotp/TwoFactorAuth/lib/TwoFactorAuth.php line 190) This indicates that the 2FA code got messed up. Two ways to fix this: Via FTP, move TfaTotp out of /modules/ Login and go to User/Profile While the login session is active, via FTP, move TfaTotp back to /modules/ Disable TfaTotp - and then save your profile page Re-enable TfaTotp - and then save your profile page again. …or (tip from @adrianj): Create a new superuser via the API and login via that and then disable and re-enable 2FA for the affected user via Access > Users. --- More in depth info from @ryan at Github: 2FA login error 500.1 point
-
I've heard from a few people in the last weeks, which seemed not to happy about by decision in regards to this module and especially the suggestion of RockMigrations as an alternative. Therefore I'll leave a few more thought. The module has been in it's current state for years. The last commit from my side was from Juli 2017. Just like the module continued to work till today it'll likely do in the future. There might be things to change with new PHP versions or PW versions – but maintaining working condition should be a fairly simple job. Given that I don't have any active projects anymore using the module (to the most part even for processwire in general) I personally can't and won't deal with keeping the module maintained. My suggestion for supporting RockMigration was mostly based on the fact that it's way more actively maintained and I feel it's better to group efforts behind a single project – especially given the processwire community being on the smaller end – but if RockMigration doesn't work for someone and this module does, feel free to use it. I'd be happy for anyone to pick this up and maintain it going forward, it just won't be me. /cc @Sascha Nos @elabx1 point
-
Thanks, but not necessary. Pretty much all my modules get created because I have a need for them in work that I get paid to do, and it doesn't cost me anything to make them available for others to use too.1 point
-
Thanks @dragan I had solved this with a hook into the processInput of the corresponding Inputfield. It kinda feels dirty but it does the job. It checks at first if all languages are empty. If all languages are empty, it gets the old values of the page and gives the data to the incoming post request, so that the old values are still in place. And also an error message is returned on the field. $wire->addHookAfter("InputfieldPageTitle::processInput", function(HookEvent $event) { if(wire('user')->hasRole("partner")){ $field = $event->object; $page = $this->modules->ProcessPageEdit->getPage(); $allowedTemplates = array( "event", "partner", ); if(in_array($page->template->name, $allowedTemplates)){ $errorCounter = 0; foreach($this->languages as $lang){ $lname = $lang->isDefault() ? "" : "__".$lang->id; if($this->wire('input')->post("title$lname") == ""){ $errorCounter++; } } // If all multi-language Fields are empty if($errorCounter == 4) { // Needs to be done like this for the default language. Somehow id doesn't work inside the foreach loop underneath $default = $this->languages->getDefault(); $oldvalue = $page->getLanguageValue($default, 'title'); $field->value = $oldvalue; // iterate through all languages except default foreach($this->languages as $lang){ if(!$lang->isDefault()){ // Get value which is already in db / on page $oldvalue = $page->getLanguageValue($lang, 'title'); // Overwrite incoming post with old data from the db $postvar = "title__{$lang->id}"; $this->wire('input')->post->$postvar = $oldvalue; } } // Populate Error to field $field->error("You must fill in at least one language"); } } } }); $wire->addHookAfter("InputfieldTextarea::processInput", function(HookEvent $event) { if(wire('user')->hasRole("partner")){ $field = $event->object; $page = $this->modules->ProcessPageEdit->getPage(); $allowedTemplates = array( "event", "partner", ); $allowedFields = array( "body", "about_us", "why_we_join" ); // If field is already required, abort the hook if($field->required) return; $f = $this->wire('fields')->get($field->name); if(in_array($page->template->name, $allowedTemplates) && in_array($field->name, $allowedFields) && $f instanceof Field && $f->type instanceof FieldtypeLanguageInterface){ // Check if field is empty in all languages $errorCounter = 0; foreach($this->languages as $lang){ $lname = $lang->isDefault() ? "" : "__".$lang->id; if($this->wire('input')->post("{$field->name}$lname") == ""){ $errorCounter++; } } // If all multi-language Fields are empty if($errorCounter == 4) { // Needs to be done like this for the default language. Somehow id doesn't work inside the foreach loop underneath $default = $this->languages->getDefault(); $oldvalue = $page->getLanguageValue($default, $field->name); $field->value = $oldvalue; // iterate through all languages except default foreach($this->languages as $lang){ if(!$lang->isDefault()){ // Get value which is already in db / on page $oldvalue = $page->getLanguageValue($lang, $field->name); // Overwrite incoming post with old data from the db $postvar = "{$field->name}__{$lang->id}"; $this->wire('input')->post->$postvar = $oldvalue; } } // Populate Error to field $field->error("You must fill in at least one language"); } } } }); Kind Regards Orkun1 point
-
Ha!! Didn't know that one The module is not active by default. And there is also a Newlines to Unordered List handy! edit: why aren't they active by default?1 point
-
Diogo is right. There is also textformatter for nl2br, so just use regular textarea and edit it details page and add "Newlines to XHTML line breaks" textformatter. You probably need to install the required module first: Newlines to XHTML Line Breaks1 point
-
you can use Markdown or Textile: http://processwire.c...text-formatter/ or, if the only thing you want is the <br> where there is a new line; you can use "nl2br" on a regular text area: http://php.net/manua...ction.nl2br.php <?php echo nl2br($page->field); ?>1 point