Jump to content
jploch

JSON structure with direct access to key

Recommended Posts

Hey folks,

for a module (a pagebuilder based on PageTable) I need to save some settings as JSON. The values are saved for each page table item (a pw page). It's working well, but I am looking for ways to improve the structure I have. As I'm not that experienced with JSON, maybe someone more experienced can take a look and tell me if my approach is good practice. 

My goal is to make all the items accessible by page id, without looping over them (using objects instead of arrays):

// access from template with pw page var
$jsonObject->items->{$page}->cssClass;

Her is an example of my JSON structure:

{
  "items": {
    "3252": {
      "id": "3252",
      "cssClass": "pgrid-main",
      "breakpoints": {
        "base": {
          "css": {
            "grid-column-end": "auto",
            "grid-row-end": "auto",
            "grid-column-start": "auto",
            "grid-row-start": "auto",
            "align-self": "auto",
            "z-index": "auto",
            "padding-left": "60px",
            "padding-right": "60px",
            "padding-top": "60px",
            "padding-bottom": "60px",
            "background-color": "rgb(255, 255, 255)",
            "color": "rgb(0, 0, 0)"
          },
          "size": "@media (min-width: 576px)",
          "name": "base"
        }
      }
    },
    "3686": {
      "id": "3686",
      "cssClass": "test_global",
      "breakpoints": {
        "base": {
          "css": {
            "grid-column-end": "-1",
            "grid-row-end": "span 1",
            "grid-column-start": "1",
            "grid-row-start": "auto",
            "align-self": "auto",
            "z-index": "auto",
            "padding-left": "0px",
            "padding-right": "0px",
            "padding-top": "0px",
            "padding-bottom": "0px",
            "background-color": "rgba(0, 0, 0, 0)",
            "color": "rgb(0, 0, 0)"
          },
          "size": "@media (min-width: 576px)",
          "name": "base"
        }
      }
    },
    "3687": {
      "id": "3687",
      "cssClass": "block_editor-3687",
      "breakpoints": {
        "base": {
          "css": {
            "grid-column-end": "span 2",
            "grid-row-end": "span 1",
            "grid-column-start": "auto",
            "grid-row-start": "auto",
            "align-self": "auto",
            "z-index": "auto",
            "padding-left": "0px",
            "padding-right": "0px",
            "padding-top": "0px",
            "padding-bottom": "0px",
            "background-color": "rgba(0, 0, 0, 0)",
            "color": "rgb(0, 0, 0)"
          },
          "size": "@media (min-width: 576px)",
          "name": "base"
        }
      }
    },
    "3696": {
      "id": "3696",
      "cssClass": "block_editor-3696",
      "breakpoints": {
        "base": {
          "css": {
            "grid-column-end": "span 2",
            "grid-row-end": "span 1",
            "grid-column-start": "auto",
            "grid-row-start": "auto",
            "align-self": "auto",
            "z-index": "auto",
            "padding-left": "0px",
            "padding-right": "0px",
            "padding-top": "0px",
            "padding-bottom": "0px",
            "background-color": "rgba(0, 0, 0, 0)",
            "color": "rgb(0, 0, 0)"
          },
          "size": "@media (min-width: 576px)",
          "name": "base"
        }
      }
    }
  },
  "breakpointActive": "base",
  "breakpointActiveSize": "@media (min-width: 576px)"
}

 

Share this post


Link to post
Share on other sites

 @ukyo Thanks! Your module looks great! However I already have a way to build my JSON based on inputfields, wich is just needed to save some internal css of my module. All the real content is saved in the database with regular pw fields. I would like to keep it that way, but was looking to get some feedback on my JSON structure. Specially I'm not sure if it's valid to have numerical keys (page id)? Everything is working fine, so if it's not bad practise for some reason, I will just keep it that way.
 
Doing it all in JSON (including the content) with your module would have the benefit of being able to transfer the templates to other installations without importing the database and also have it version controlled, right? But the downside is that it's not searchable as well as native fields and also that not all fields are supported?
 

Share this post


Link to post
Share on other sites

I have builder system with PageTable input field,403366945_EkranResmi2021-02-1118_05_03.thumb.png.8096e1b2386cc436515063dae0893644.png

Text field is InputfieldText Field (Searchable)

Properties field is Mystique Field (Limited search support)

581196593_EkranResmi2021-02-1118_08_40.thumb.png.41109564644bdc5d9c5cec3c8e60f625.png

Current Mystique field version support search limited. Working with next version on my side and it will support searching.

  • Like 1

Share this post


Link to post
Share on other sites

cool! but still can someone look at my code and tell me if the JSON structure is fine?

Share this post


Link to post
Share on other sites

@jploch You're mixing up storage and public API, which is not a good idea. JSON is a storage / transport format, it's always a string which contains a serialization of data. The purpose of JSON is to store or transmit data in different formats between systems – like your database, your server and the client's browser. JSON is also language-independent – you can decode a JSON-string in JavaScript and in PHP. But as soon as you do that, the result is that language's default representation of that JSON string. For PHP, this means you get either a stdClass object or arrays (depending on the flags you give to json_decode).

So you need to ask two different questions: What is the best way to store my data, and what is the best way to present it to a user of your module?

Data representation

Of course you can just json_decode the JSON string and pass the result to the user of your module. But that's a bad idea:

  • You have zero guarantees regarding the structure of your data. You won't notice if your data is missing a specific field, some field is an integer instead of a string, your items are indexed by page name instead of key or whatever else. This will cause errors that are very hard to track down.
  • The user has no indication how your data is structured – to figure that out, I will either have to refer to the documentation for everything or have to dump stdClass objects and figure things out from there ...
  • You can't have nice things like code completion, proper IDE support etc.

Instead, you want to parse that unstructured data into a representation (usually, a set of classes) that guarantees a specific structure and has a proper public API for access and modification of the data. Using proper objects with type-hinting will also allow you to find any errors in the structure and abort the process at parse time with an appropriate error message (see Parse, don't validate for an in-depth explanation). For example, to represent your data, you might use classes like PageBuilderEntry and PageBuilderItem to represent a list of items with meta data (the breakpoint fields, in your example) and individual items, respectively. The you can provide utility methods for different use cases – for example, methods to get a list of items indexed by key or by any other field.

If you want to build closer to ProcessWire, you can also use a class that extends WireArray to represent a list of items, this will give you many helpful methods (like getting an item by key) out of the box. For the items themselves, you might just reuse the page itself (if the IDs correspond to 'real' pages in your system) or extend the Page class.

Data storage

Separating the representation from the storage makes the specific structure you store your data in less important, since only your module will interact with it. Just build a static helper method to build the appropriate representation based on a JSON string (e.g. PageBuilderEntry::fromJSON) and a method to encode that representation back to JSON (PageBuilderEntry::toJSON). The fromJSON method is responsible for parsing the data and throwing the appropriate error when it's not in the expected format.

That said, personally I usually prefer regular arrays instead of maps for storage, because it's easier to parse and massage into different formats. But again, it depends on how you want to represent the data.

  • Like 8

Share this post


Link to post
Share on other sites

@MoritzLost Thanks for your explanation! Helps me to understand this a little bit better.

2 hours ago, MoritzLost said:

Of course you can just json_decode the JSON string and pass the result to the user of your module. But that's a bad idea:

Iam not sure the data will ever be relevant to the user, for now I just use the JSON internally (creating JSON with js and decoding it with PHP). What I meant with "using objects instead of arrays" here is just how I decode the JSON in php: json_decode($jsonString) instead of (json_decode($jsonString, true). This gives me easy access to the items (which are just pages, so I thought it would be nice to be able to access them by page id like the pw api works). To be able to do this I also need to create the JSON structure like in the example above (with JS). Hope that makes sense. Not sure if the cons you listed matter that much in this case. I will think about it.

2 hours ago, MoritzLost said:

If you want to build closer to ProcessWire, you can also use a class that extends WireArray to represent a list of items, this will give you many helpful methods (like getting an item by key) out of the box. For the items themselves, you might just reuse the page itself (if the IDs correspond to 'real' pages in your system) or extend the Page class.

This sounds interesting. Maybe you can provide an example how to extend WireArray?

 

Share this post


Link to post
Share on other sites

here is another possible structure

{
  "items": [{
    "id": "3252",
    "cssClass": "pgrid-main",
    "breakpoints": {
      "base": {
        "css": {
          "grid-column-end": "auto",
          "grid-row-end": "auto",
          "grid-column-start": "auto",
          "grid-row-start": "auto",
          "align-self": "auto",
          "z-index": "auto",
          "padding-left": "60px",
          "padding-right": "60px",
          "padding-top": "60px",
          "padding-bottom": "60px",
          "background-color": "rgb(255, 255, 255)",
          "color": "rgb(0, 0, 0)"
        },
        "size": "@media (min-width: 576px)",
        "name": "base"
      }
    }
  }, {
    "id": "3686",
    "cssClass": "test_global",
    "breakpoints": {
      "base": {
        "css": {
          "grid-column-end": "-1",
          "grid-row-end": "span 1",
          "grid-column-start": "1",
          "grid-row-start": "auto",
          "align-self": "auto",
          "z-index": "auto",
          "padding-left": "0px",
          "padding-right": "0px",
          "padding-top": "0px",
          "padding-bottom": "0px",
          "background-color": "rgba(0, 0, 0, 0)",
          "color": "rgb(0, 0, 0)"
        },
        "size": "@media (min-width: 576px)",
        "name": "base"
      }
    }
  }, {
    "id": "3687",
    "cssClass": "block_editor-3687",
    "breakpoints": {
      "base": {
        "css": {
          "grid-column-end": "span 5",
          "grid-row-end": "span 2",
          "grid-column-start": "2",
          "grid-row-start": "2",
          "align-self": "auto",
          "z-index": "98",
          "padding-left": "0px",
          "padding-right": "0px",
          "padding-top": "0px",
          "padding-bottom": "0px",
          "background-color": "rgb(255, 204, 204)",
          "color": "rgb(0, 0, 0)"
        },
        "size": "@media (min-width: 576px)",
        "name": "base"
      }
    }
  }, {
    "id": "3696",
    "cssClass": "block_editor-3696",
    "breakpoints": {
      "base": {
        "css": {
          "grid-column-end": "span 2",
          "grid-row-end": "span 1",
          "grid-column-start": "auto",
          "grid-row-start": "auto",
          "align-self": "auto",
          "z-index": "auto",
          "padding-left": "0px",
          "padding-right": "0px",
          "padding-top": "0px",
          "padding-bottom": "0px",
          "background-color": "rgba(0, 0, 0, 0)",
          "color": "rgb(0, 0, 0)"
        },
        "size": "@media (min-width: 576px)",
        "name": "base"
      }
    }
  }],
  "breakpointActive": "base",
  "breakpointActiveSize": "@media (min-width: 576px)"
}


 

Share this post


Link to post
Share on other sites
Quote

Iam not sure the data will ever be relevant to the user, for now I just use the JSON internally (creating JSON with js and decoding it with PHP).

Then the user is your own module. All the points in my post above still apply – your module has to make some assumptions about the structure of the JSON data. Even if the data is only consumed internally, passing unstructred data around can cause unexpected errors at any point. So it's still better to parse the data into a representation that makes guarantees a specific data structure, and raise errors during parsing (as opposed to a random error anywhere in your module's lifecycle that's hard to track down). Also, will your module not allow customization through, for example, custom page builder elements or hooks? As soon as that's the case, developers using your module will have to use your data, so it should provide a uniform interface to accessing that data.

Quote

This sounds interesting. Maybe you can provide an example how to extend WireArray?

Basically, any ProcessWire class representing some sort of collection, so you can check out those. For example, check out Pagefiles, FieldsArray and PageArray which all extend WireArray. See how they make use of all the utility methods WireArray provides and override just the methods they need to customize to adapt the WireArray to a specific type of data? For example, check out FieldsArray::isValidKey only allows Field objects to be added to it, so adding anything else will immediately throw an error. You can use this to map your pagebuilder items to a specific class and then have a class like PageBuilderItems extending WireArray that only accepts this class as items. This will go a long way towards having a uniform data structure.

Quote

What I meant with "using objects instead of arrays" here is just how I decode the JSON in php: json_decode($jsonString) instead of (json_decode($jsonString, true). This gives me easy access to the items (which are just pages, so I thought it would be nice to be able to access them by page id like the pw api works).

Again, don't mix up storage and representation. For storage, I would prefer the second example you posted, with items being an array instead of a map and the ID being just a regular property. Simply because arrays are more convenient to create, parse and map (in JS especially, but also in PHP). Though again, it doesn't matter as soon as you parse the data. The representation your module (or others, see above) uses to access the data can provide utility methods, like accessing an item by key.

Regarding the last point specifically, WireArray can help you with this. The documentation is kind of handwaivy about how WireArrays handle item keys – WireArray::add doesn't take the key as an argument, but WireArray::get allows you to get an item by key, so where does the key come from? If you check the source code, turns out WireArray automatically infers a key based on the item – see WireArray::getItemKey. Your custom class can extend this to use the ID property of a given item as the key. For example, FieldsArray::getItemKey does exactly this. This allows you to use page IDs to access items without having to store your data specifically as a map. On top of that, you can use all the other utility methods WireArray provides to access elements in the any way you like.

  • Like 4

Share this post


Link to post
Share on other sites

@MoritzLost Thank you for the detailed answer! I'm still at a very beginner level with php, all I know about it, I basically learned from using PW and it's api. Doing mainly frontend development, this is the first bigger module I'm building. So I'm still new to how classes work. Now that I have another look at it, what you sad makes a lot of sense. I will try to implement the class approach with my own utility methods.

I will also have a look at WireArray, this seems like a nice solution.
Thanks again for your help. I might come back at you if I hit another roadblock.

  • Like 1

Share this post


Link to post
Share on other sites

I'm still a little lost on how to implement my JSON decode method and use WireArray as a representation of my data.
My module builds a dynamic stylesheet, based on the JSON file. This dynamic stylesheet is just a php file that the user can include in his/her main template file. The JSON is saved in one field, that live on the page holding all the PageTable items.

Since I need the CSS to be rendered  in the backend and frontend and I wanted to give the user more freedom on where to include the CSS I thought this is a good approach. Not sure if it's really clever to have this in a separate file instead of my module file. 

This is my working code I have in the dynamic stylesheet file:

<style>
<?php 
namespace ProcessWire; 
$backend = 0; 
$p = $this->page;

if($isAdmin = $this->page->rootParent->id == 2) {
$p = $this->pages->get((int) wire('input')->get('id'));
$backend = 1; 
}

$css='';
$settingsArrayPage=json_decode($p->pgrid_settings);

  if( !(empty($settingsArrayPage))) {

       foreach($settingsArrayPage->items as $item) { 
           
           foreach($item->breakpoints as $breakpoint) { 
             
             if ($backend) {
               $css.='.breakpoint-'. $breakpoint->name . ' ';
             } else {
               $css .= $breakpoint->size . '{ ';
             }
            
            $css .= '.' . $item->cssClass. '{ ';
          foreach($breakpoint->css as $style=> $val) {
                   $css .= $style . ': ' . $val . '; ';
               }
             
           $css .= ' } ';
             if (!$backend) {
           $css .= ' } ';
             }
         }
            
       }
  
  echo $css;
    }
 ?>

</style>

First of all where would you put the WireArray code? Is it better to have this in my module file or in the dynamic stylesheet file?
Here is my code so far.

 class PageGridData extends WireArray {
    
   public function getItemKey($item) {
// here I would place the JSON decode method from above and return the items?
		return $item->id;
	}
    
    }

Sorry this is a bit outside of my comfortzone 🙂

Share this post


Link to post
Share on other sites

@jploch Ok, so currently you have a procedural approach, which is fine for a fixed use-case. My proposed solution might be overkill for what you're trying to achieve. And it will definitely be more work - and maybe the more general application for your module (which I don't even know the scope or precise purpose of) that I'm imagining isn't even what you're trying to achieve. So before you start refactoring, consider if it will actually be of benefit to your module! And of course, if you have to use code that you don't fully understand the purpose of, it won't help you in the end. If what you have is working fine for your use-case, maybe you don't need all that stuff. So just take my approach with a grain of salt 🙂

I would start by creating classes that represent the building blocks of your page builder. That would probably include a class that represents a list of CSS rules (that can use WireArray), a class for individual items (with a reference to a list of CSS rules) and a class for a list of items (this again can use WireArray). Decoding JSON would probably be the responsibility of the latter. Though of course you can also go with a more eleborate approach to transforming JSON to classes like the builder pattern.

Here's a start (I wrote this in the browser, so it will need some polish and might include some errors, but hopefully it communicates the idea behind it):

// this class represents a list of CSS rules, as included in your JSON data
class PageGridCSS extends WireArray {
	/** This class gets methods to set, get and remove CSS rules, and render them to CSS. */
}

class PageGridItem {
	// PHP 7.4+, for older PHP versions use a protected property with getters and setters
	public int $id;

	// each item holds a reference to a set of rules
	public PageGridCSS $cssRules;

	/** This class gets properties and methods corresponding to the data it represents */
}


class PageGridData extends WireArray {
    // guarantee that this can only hold PageGridItem objects
    public isValidItem ($item) {
        return $item instanceof PageGridItem;
    }

    // make PageGridItems accessible by their ID
    public function getItemKey($item) {
        return $item->id;
    }

    // convert json to the appropriate classes
    public static fromJSON (string $json): PageGridData {
        $items = json_deocde($data)['items'];
        $dataList = new self();
        foreach ($items as $item) {
            $dataItem = new PageGridItem();
			$dataItem->id = $item->id;
			/** Add all the properties to the item, catching missing or malformed data */
            $dataList->add($dataItem);
        }
        return $dataList;
    }

    public renderCSS() {
        // render the CSS for the items this instance contains
    }
}

Why even do all this? Currently, your dynamic template makes a couple of assumptions that I, as a user of your module, may not agree with. For example:

  • It always includes style tags. What if I want to save the output in a CSS file and serve it statically?
  • You infer the context (backend / frontend) which doesn't always work reliably. I also can think of some reasons why I would like to get the code for the frontend in the backend - for example, to save it to a field.
  • Your ".breakpoint-{...}" classes may interfere with my own stylesheets, so I could use a way to rename them.
  • Maybe I want only a part of the stylesheet, like the rules for a specific breakpoint.
  • ...

Making all this modular and giving users access to the functionality through a well-defined API with utility methods allows me to customize all this and access the parts that I want to use, changing those that I need to.

Though again, maybe I'm totally wrong regarding the intent and scope of your module. This way a fun exercise to think through anyway, hopefully it will be helpful to you or others looking for something similar 🙂 Hm, maybe that stuff would make a good article for processwire.dev ... 🙃

  • Like 1

Share this post


Link to post
Share on other sites

@MoritzLost Thanks again! This seems to be the best way to handle it. I will further investigate if it complicates my current setup too much. But I get the benefits now. Hopefully this will help others too. 

I'm generally ok with making some assumptions in my case, because you can change the CSS stuff inside the backend for each item (and the breakpoints you want) anyway, also its easy enough to overwrite some css rules with plane css/scss. Maybe I provide some api options and helper functions along the way, so this is definitely helpful. Here is a preview of the module I'm developing to give you a little more context:

 

  • Like 1

Share this post


Link to post
Share on other sites

One more question to finally understand php classes a little bit better:
If I have this simple class:

class PageGridCSS {

    public $cssClasses = 'test classes';

    public function getCssClasses() {
        return $this->cssClasses;
    }
}

How can I call the function getCssClasses from outside the file it is declared in?
So far I was able  to call it from within the same file only by doing this:

$PageGridCSS = new PageGridCSS();
$PageGridCSS->getCssClasses();

 

Share this post


Link to post
Share on other sites

You need a reference to the instance, so the $PageGridCSS variable in your case. That's because there can be different instances of the same class with different states and holding different data. So yes, if you create a new instance in a specific context, only that context has access to the variable. If you want to pass it around, you need to provide utility methods or pass specific instances of a class as parameters. Usually, the instances of a set of classes are linked together by properties referencing each other. For example, in my example code above, the PageGridData contains a list of PageGridItem instances, which can be accessed by key or iterated over using the utility methods provided by WireArray. Each PageGridItem then has a reference to the PageGridCSS instance belonging to it (that's the $cssRules property in my example code). For example:

function doStuff(PageGridData $data) {
	$key = 1234;
	// $item will be an instance of PageGridItem
	$item = $data->get($key);
	// $cssRules will be an instance of PageGridCSS
	$cssRules = $item->cssRules;
	// ...
}

Does that help? The best way to pass around data depends on the application flow. For ProcessWire modules, the main module class will usually have helper methods to access specific classes of the module. For example, my module TrelloWire contains a separate class (ProcessWire\TrelloWire\TrelloWireAPI) that handles all requests to the Trello API. The main module file has a utility method to get an instance of that class with the API key and token configured in the module settings. Another example is the TrelloWireCard class, which holds all the data used to create a Trello card through the API. This one is also a module, so you can access it using $modules->get() to get an empty instance. But the main module class also has a utility method to create an instance populated with data from a regular page and the module configuration. This method is used by the module internally, but can be hooked to overwrite specific fields or used to build your own application or business logic on top of the module.

  • Like 1

Share this post


Link to post
Share on other sites

thx! it's working now calling the function like this. Cool!  

$CssClasses = $modules->get('InputfieldPageGrid')->getCssClasses();

 

  • Like 2

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By robert
      I often had the need for an overview of all used fields and their contents for a specific page/template while developing new websites without switching to the backend, so I made a small module which lists all the needed information in a readable manner (at least for me):
      Debug Page Fields
      https://github.com/robertweiss/ProcessDebugPageFields
      It adds two new properties to all pages:
      $page->debugFieldValues – returns an object with all (sub-)fields, their labels, fieldtypes and values $page->debugFieldTypes – returns an object with all fieldtypes and their corresponding fields // List all values of a pages $page->debugFieldValues // List a specific field $page->debugFieldValues->fieldname // List all used fieldtypes of a page $page->debugFieldTypes I recommend using it in combination with Tracy Debugger, Ray, Xdebug etc. as it returns an object and is only meant for developing/debugging uses. 
      For now, the fieldtype support includes mostly fieldtypes I use in my projects, but can easily be extended by adding a new FieldtypeFIELDNAME method to the module. I use it with five different client installations (all PW 3.0.*), but of course there might be some (or more) field configurations which are not covered correctly yet.
      Supported fieldtypes
      Button Checkbox Color Combo Datetime Email FieldsetPage * File FontIconPicker Functional Image ImageReference MapMarker Multiplier Mystique Options Page PageIDs PageTitle Radio Repeater * RepeaterMatrix * RockAwesome SeoMaestro Table Text Textarea Textareas Toggle URL * The fields with complete subfield-support also list their corresponding subfields.
      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. As this is my first ›public‹ module, I hope I did not miss any important things to mention here.
    • By horst
      Wire Mail SMTP

      An extension to the (new) WireMail base class that uses SMTP-transport

      This module integrates EmailMessage, SMTP and SASL php-libraries from Manuel Lemos into ProcessWire. I use this continously evolved libraries for about 10 years now and there was never a reason or occasion not to do so. I use it nearly every day in my office for automated composing and sending personalized messages with attachments, requests for Disposition Notifications, etc. Also I have used it for sending personalized Bulkmails many times.

      The WireMailSmtp module extends the new email-related WireMail base class introduced in ProcessWire 2.4.1 (while this writing, the dev-branch only).
       
      Here are Ryans announcement.



      Current Version 0.6.0
      Changelog: https://github.com/horst-n/WireMailSmtp/blob/master/CHANGELOG.md
      get it from the Modules Directory Install and Configure

      Download the module into your site/modules/ directory and install it.

      In the config page you fill in settings for the SMTP server and optionaly the (default) sender, like email address, name and signature.
      You can test the smtp settings directly there. If it says "SUCCESS! SMTP settings appear to work correctly." you are ready to start using it in templates, modules or bootstrap scripts.


      Usage Examples
      The simplest way to use it:
      $numSent = wireMail($to, $from, $subject, $textBody); $numSent = wireMail($to, '', $subject, $textBody); // or with a default sender emailaddress on config page This will send a plain text message to each recipient.
       
      You may also use the object oriented style:
      $mail = wireMail(); // calling an empty wireMail() returns a wireMail object $mail->to($toEmail, $toName); $mail->from = $yourEmailaddress; // if you don't have set a default sender in config // or if you want to override that $mail->subject($subject); $mail->body($textBody); $numSent = $mail->send(); Or chained, like everywhere in ProcessWire:
      $mail = wireMail(); $numSent = $mail->to($toEmail)->subject($subject)->body($textBody)->send(); Additionaly to the basics there are more options available with WireMailSmtp. The main difference compared to the WireMail BaseClass is the sendSingle option. With it you can set only one To-Recipient but additional CC-Recipients.
      $mail = wireMail(); $mail->sendSingle(true)->to($toEmail, $toName)->cc(array('person1@example.com', 'person2@example.com', 'person3@example.com')); $numSent = $mail->subject($subject)->body($textBody)->send(); The same as function call with options array:
      $options = array( 'sendSingle' => true, 'cc' => array('person1@example.com', 'person2@example.com', 'person3@example.com') ); $numSent = wireMail($to, '', $subject, $textBody, $options); There are methods to your disposal to check if you have the right WireMail-Class and if the SMTP-settings are working:
      $mail = wireMail(); if($mail->className != 'WireMailSmtp') { // Uups, wrong WireMail-Class: do something to inform the user and quit echo "<p>Couldn't get the right WireMail-Module (WireMailSmtp). found: {$mail->className}</p>"; return; } if(!$mail->testConnection()) { // Connection not working: echo "<p>Couldn't connect to the SMTP server. Please check the {$mail->className} modules config settings!</p>"; return; }  
      A MORE ADVANCED DEBUG METHOD!
      You can add some debug code into a template file and call a page with it:
      $to = array('me@example.com'); $subject = 'Wiremail-SMTP Test ' . date('H:i:s') . ' äöü ÄÖÜ ß'; $mail = wireMail(); if($mail->className != 'WireMailSmtp') { echo "<p>Couldn't get the right WireMail-Module (WireMailSmtp). found: {$mail->className}</p>"; } else { $mail->from = '--INSERT YOUR SENDER ADDRESS HERE --'; // <--- !!!! $mail->to($to); $mail->subject($subject); $mail->sendSingle(true); $mail->body("Titel\n\ntext text TEXT text text\n"); $mail->bodyHTML("<h1>Titel</h1><p>text text <strong>TEXT</strong> text text</p>"); $dump = $mail->debugSend(1); } So, in short, instead of using $mail->send(), use $mail->debugSend(1) to get output on a frontend testpage.
      The output is PRE formatted and contains the areas: SETTINGS, RESULT, ERRORS and a complete debuglog of the server connection, like this one:
       
      Following are a ...


      List of all options and features


      testConnection () - returns true on success, false on failures


      sendSingle ( true | false ) - default is false

      sendBulk ( true | false ) - default is false, Set this to true if you have lots of recipients (50+)


      to ($recipients) - one emailaddress or array with multiple emailaddresses

      cc ($recipients) - only available with mode sendSingle, one emailaddress or array with multiple emailaddresses

      bcc ($recipients) - one emailaddress or array with multiple emailaddresses

       
      from = 'person@example.com' - emailaddress, can be set in module config (called Sender Emailaddress) but it can be overwritten here

      fromName = 'Name Surname' - optional, can be set in module config (called Sender Name) but it can be overwritten here


      priority (3) - 1 = Highest | 2 = High | 3 = Normal | 4 = Low | 5 = Lowest

      dispositionNotification () or notification () - request a Disposition Notification


      subject ($subject) - subject of the message

      body ($textBody) - use this one alone to create and send plainText emailmessages

      bodyHTML ($htmlBody) - use this to create a Multipart Alternative Emailmessage (containing a HTML-Part and a Plaintext-Part as fallback)

      addSignature ( true | false ) - the default-behave is selectable in config screen, this can be overridden here
      (only available if a signature is defined in the config screen)

      attachment ($filename, $alternativeBasename = "") - add attachment file, optionally alternative basename


      send () - send the message(s) and return number of successful sent messages


      debugSend(1) - returns and / or outputs a (pre formatted) dump that contains the areas: SETTINGS, RESULT, ERRORS and a complete debuglog of the server connection. (See above the example code under ADVANCED DEBUG METHOD for further instructions!)


      getResult () - returns a dump (array) with all recipients (to, cc, bcc) and settings you have selected with the message, the message subject and body, and lists of successfull addresses and failed addresses,


      logActivity ($logmessage) - you may log success if you want

      logError ($logmessage) - you may log warnings, too. - Errors are logged automaticaly
       
       
      useSentLog (true | false) - intended for usage with e.g. third party newsletter modules - tells the send() method to make usage of the sentLog-methods - the following three sentLog methods are hookable, e.g. if you don't want log into files you may provide your own storage, or add additional functionality here

      sentLogReset ()  - starts a new LogSession - Best usage would be interactively once when setting up a new Newsletter

      sentLogGet ()  - is called automaticly within the send() method - returns an array containing all previously used emailaddresses

      sentLogAdd ($emailaddress)  - is called automaticly within the send() method
      Changelog: https://github.com/horst-n/WireMailSmtp/blob/master/CHANGELOG.md
       
       
    • By Cybermano
      Food Allergens Module
      A simple List of Food Allergens
      My needs were to provide a simple list of food allergens for our clients with restaurant related activity.
      The idea was to simply output the list (to speed up the data entry) without leaving the food menu editing, eg. opening another page in new tab or window.
      This isn't a perfect solution, but it works fine for my needs and I decided to share the base idea.
      This could also be easily used to show little notes or short "vademecum", not only for the list of food allergens.
      ---
      Main features
      The basis
      All moves from a short editing of the module in this tutorial: How to create custom admin pages by @bernhard
      First of all it creates an empty admin page, with a dedicated permission to let safe-user to see it (this permission has to be created as a new ones, manually or by the module).
      Once the page is created, I have hooked its behaviour into the ready.php, to show the content (basically a list).
      A step further
      With the tips of  @bernhard, @Soma (and many others), see here , the magic happens. 
      The new page will be shown as a panel, so editors will not abandon their data entry to have a quick view to the list.
      A little further
      Why scroll to the top of the page to click a link?
      The next step was to create a sticky button only in the food menu pages.
      Again with a @bernhard tip I moved into the customization of this simple module and the related hook.
      ---
      How to use this module
      After installed, it creates the page /admin/page/allergens/ and the module is to be setted up. The first field is a CKEditor with multi-language. This is the place where to write the informations that will be shown into the page. The next field is a simply text-area where to place a bit of JS that will be appended to the markup of the text (omit the 'script' tags). I also putted a checkbox with a silly statement: this to think at least twice on the safety of the written JS. Now comes the first way to display the link to the page
      Field Note with Link. Enable and save it. The module will display a new row with 4 selects (1 standard and 3 ASM):
      View mode (to show the page as Panel or as Modal PopUp); Templates to select: select one or more and save before proceed, so the  asm-select of the pages will be populated showing all the pages of the selected templates. Pages to select: also here select at least one and save before proceed to populate the asm-select for fields only with the ones that belong to the selected pages. Select the fields where to place the note and save again. That's all: now you will find into the notes of the selected fields the link "See the List of Allergens".
      At the same way, the option for the sticky button, but with a plus
      The field select is obviously unnecessary, but you could play with the last row: the inline styles to fix your sticky button where you like. Here you could set the sticky position of the <div> and the absolute ones of the <a>.

      Video Explanation
      In these screencasts you could see a custom JS that show a "copy" button near a "hanna-code" call.
      This because I've set a specific one for each allergen to show up a tooltip in the front end.

      Registrazione #33.mp4  

      Registrazione #34.mp4 ---
      Last but not the least
      Actually it works fine for my needs, even if it's much improvable: I'm working on the permissions creation, the uninstall section, a separate configs and defaults and how to include the hook into the module leaving free the ready.php. According to a simpler uninstall. Also I would make the link text as a dynamic text field, so it will be more flexible.
      I always learn a lot here, so I would share my code for whom it could be interested.
      I removed the hanna code references, but I provide you the html list of the allergens, English and Italian too, so you can paste them into the "source" of the CKEditor field to have a ready to use module.
      Obviously you are free to modify the code as per your needs.
      Please, keep in mind that I'm not a pro coder and I beg your pardon for my verbosity (speaking and coding). 😉
      I hope be helpful or for inspiration.
      Bye
      ready.phpList-ITA.htmlList-ENG.htmlAllergens.module
      README.md
    • By Robin S
      This module is sort of an upgrade to my earlier ImageToMarkdown module, and might be useful to anyone working with Markdown in ProcessWire.
      Copy Markdown
      Adds icons to images and files that allow you to copy a Markdown string to the clipboard. When you click the icon a message at the top left of the screen notifies you that the copying has occurred.
      Screencast

      Note: in the screencast an EasyMDE inputfield is used to preview the Markdown. It's not required to use EasyMDE - an ordinary textarea field could be used.
      Usage: Images
      When you hover on an item in an Images field an asterisk icon appears on the thumbnail. Click the icon to copy an image Markdown string to clipboard. If the "Description" field is populated it is used as the alt text.
      You can also open the "Variations" modal for an image and click the asterisk icon to copy an image Markdown string for an individual variation.
      Usage: Files
      When you hover on an item in a Files field an asterisk icon appears next to the filename. Click the icon to copy a link Markdown string to the clipboard. If the "Description" field is populated it is used as the link text, otherwise the filename is used.
       
      https://github.com/Toutouwai/CopyMarkdown
      https://processwire.com/modules/copy-markdown/
    • By BitPoet
      I've realized that I've been jumping back and forth between the PW API docs and the source code for site modules far too much. The idea to hold all necessary documentation locally in one place has occurred to me before, but getting PHPDocumentor et al set up and running reliably (and producing readable output) as always been too much of a hassle. Today I was asked how I find the right hooks and their arguments, and that inspired me to finally get my backside down on the chair and whip something up, namely the
      Module Api Doc Viewer
      ProcessModuleApiDoc
      It lets you browse the inline documentation and public (optionally also protected) class/method/property information for all modules, core classes and template files in the ProcessWire instance. The documentation is generated on the fly, so you don't have to remember to update your docs whenever you update a module.
      The module is quite fresh, so expect some bugs there. Behind the scenes it uses PHP-Parser together with a custom class that extracts the information I needed, and the core TextformatterMarkdownExtra module for rendering the description part in the phpdoc style comments.
      This is not a replacement / competitor to the API Viewer included in the commercial ProDevTools package. There is quite some information included in the inline documentation that my module can't (and won't) parse, but which makes up parts of the official ProcessWire API docs.
      This, instead, is a kind of Swiss army knife to view PHPDoc style information and get a quick class or function reference.
      If you feel daring and want to give it a spin, or if you just want to read a bit more, visit the module's GitHub repository.
      This is the overview page under "Setup" -> "Module API Docs":

      And this is what the documentation for an individual class looks like:

      The core module documentation can of course be found online, but it didn't make sense not to include them.
      Let me know what you think!

×
×
  • Create New...