Jump to content
MarkE

Module for conditional expressions?

Recommended Posts

I'm looking for an inputfield module that might allow the entry and evaluation of a conditional expression (following php syntax).

My use case is an admin function for writing pro-forma emails/letters where some components of the pro-forma are dependent on conditions determined by an admin user. The pro-forma is then cloned for use and the relevant components are included depending on the runtime value of the conditions. The conditions usually include hanna codes as the items to be compared. This is implemented in a parent-child structure, where the main mail body is in the parent and each child then has a condition (textarea) field and a body textarea field for the optional text relating to that condition.

As an interim solution on my dev machine, I am just using eval() to evaluate the conditions, but I really don't want to use this in the live environment. My idea is to use an approach similar to that for hanna codes to store the php and render it. This would be (somehow) wrapped in a new inputfield module (extending InputfieldTextarea?) with an evaluate() method that would return true or false as appropriate. It would be placed inside a try...except structure to catch syntax errors etc.

It seemed to me that this might be quite a useful utility module and that someone might have developed something similar, but I can't find anything. Does anyone have any pointers, or will I need to start from scratch? If the latter, then I'd appreciate some help along the way as I am a bit of a novice in these matters.

Share this post


Link to post
Share on other sites

I built the following function which seems to work (borrowing heavily from the Hanna code approach). Not sure if its worth building a module around it.

/**
 * @param $condition
 * @param $pageId - page id holding the condition
 * @return bool
 * @throws WireException
 */
function evaluate_condition($condition, $pageId) {
    if ($condition and $pageId) {
        bd($condition, 'raw expression');
        $condition = html_entity_decode(strip_tags($condition), ENT_QUOTES | ENT_XML1, 'UTF-8'); // need extra params to catch   so that it can be removed by str_replace
        bd($condition, 'orig expression decoded');
        $condition = str_replace(' ', ' ', $condition);
        $condition = str_replace(' ', '', $condition);

        $cachePath = wire('config')->paths->cache . 'MailCondition/';
        $name = 'condition' . $pageId;
        if(!is_dir($cachePath)) if(!wireMkdir($cachePath)) {
            throw new WireException("Unable to create cache path: $cachePath");
        }

        $file = $cachePath . $name . '.php';

        $code = 'if (' . $condition . ') {echo "Y";} else {echo"N";}';
        $openPHP = '<' . '?php';
        $firstLine = 'if(!defined("PROCESSWIRE")) die("no direct access");';

        if(substr($code, 0, strlen($openPHP)) !== $openPHP) {
            // prepend open PHP tag to code if not already present
            $code = "$openPHP\n$firstLine\n$code";
        } else {
            // otherwise insert our $firstLine security check
            $code = str_replace($openPHP, "$openPHP\n$firstLine\n", $code);
        }

        if(is_file($file) && file_get_contents($file) === $code) {
            // file already there and same as what's in the DB
        } else {
            // write new file or overwrite existing
            if(!file_put_contents($file, $code, LOCK_EX)) throw new WireException("Unable to write file: $file");
            if(wire('config')->chmodFile) chmod($file, octdec(wire('config')->chmodFile));
        }

        $t = new TemplateFile($file);
        try {
            $result = $t->render();
            return ($result == "Y");
        } catch (\Error $e) {
            throw new WireException("Error in condition - cannot evaluate");
        }
    } else {
        throw new WireException("Incomplete parameters (condition, pageId) supplied - cannot evaluate");
    }
}

 

Share this post


Link to post
Share on other sites
5 hours ago, MarkE said:

Not sure if its worth building a module around it.

IMHO it's almost always worth building a module:

  • You can share it across projects
  • You can fix bux and add features in a central place
  • You can easily share it with the community
  • You can add documentation easily via readme file

And it's really almost no extra effort:

hQ9m9mQ.gif

  • Like 1

Share this post


Link to post
Share on other sites
6 minutes ago, bernhard said:

And it's really almost no extra effort:

Maybe for whizzos like you @bernhard, but I have only ever built simple process modules, using your excellent tutorial, and have struggled to find clear instructions for building Inputfield modules. It looks like there also needs to be a Fieldtype module, but I'm not sure why, or what should go in each.

Share this post


Link to post
Share on other sites
19 minutes ago, MarkE said:

Maybe for whizzos like you @bernhard, but I have only ever built simple process modules, using your excellent tutorial, and have struggled to find clear instructions for building Inputfield modules. It looks like there also needs to be a Fieldtype module, but I'm not sure why, or what should go in each.

Sorry - didn't get that you are talking about Fieldtype/Inputfield modules! They are definitely not that easy to grasp! 😄 It also took me really long to understand how they work and what the important parts are... The problem is that it's quite easy once you know how things work, but it's quite hard to understand what's going on when and where when you look at the code of a finished module (like the events fieldtype that was intended to be a tutorial module...).

Having said that, I'm still not sure if you really need a fieldtype/inputfield module. Also a basic module comes with the benefits mentioned above and it's as simple as that:

class YourModule extends WireData implements Module {

  public static function getModuleInfo() {
    return [
      'title' => 'YourModule',
      'version' => '0.0.1',
      'summary' => 'Your module description',
    ];
  }

  function evaluate_condition($condition, $pageId) {
    // your code here
  }
}

Then you can call your function:

$modules->get('YourModule')->evaluate_condition('foo', 123);

That's very little effort for lots of benefits. Maybe you don't even need to create a full blown Inputfield/Fieldtype module. You could maybe just make it autoload and add a hook to your module:

class YourModule extends WireData implements Module {

  public static function getModuleInfo() {
    return [
      'title' => 'YourModule',
      'version' => '0.0.1',
      'summary' => 'Your module description',
      'autoload' => true, // added this
    ];
  }

  public function init() {
    $this->addHookAfter("Inputfield::render", function($event) {
      $event->return .= "<div>My modified Inputfield</div>";
    });
  }

  function evaluate_condition($condition, $pageId) {
    // your code here
  }
}

Or even better, since you always check the condition for a single page, attach the method to the page object:

class YourModule extends WireData implements Module {

  public static function getModuleInfo() {
    return [
      'title' => 'YourModule',
      'version' => '0.0.1',
      'summary' => 'Your module description',
      'autoload' => true,
    ];
  }

  public function init() {
    $this->addHookAfter("Page::evaluate_condition", $this, "evaluate_condition");
  }

  function evaluate_condition(HookEvent $event) {
    $page = $event->object;
    $condition = $event->arguments(0);

    // your code here
    // instead of return 'foo' use $event->return = 'foo'
  }
}

Then you can do this on any processwire $page

$page->evaluate_condition("foo");

PS: The boilerplate code for every module is always the same. It might look frightening at first sight, but using vscode snippets for example it's really just typing "pwmodule" and filling in the placeholders (like shown in the gif above). https://marketplace.visualstudio.com/items?itemName=baumrock.pwsnippets

  • Like 1

Share this post


Link to post
Share on other sites

Thanks for the ideas. I decided to use a class for the template (MailConditional) and put the method in there. This simplifies things a bit for me - just need to call $mailPage->evaluate_condition().

<?php
namespace ProcessWire;

class MailConditionalPage extends DefaultPage
{
    /**
     * Create a new MailConditional page in memory.
     *
     * @param Template $tpl Template object this page should use.
     */
    public function __construct(Template $tpl = null) {
        if(is_null($tpl)) $tpl = $this->templates->get('MailConditionalPage');
        parent::__construct($tpl);
    }

    /**
     * @param $codes
     * @return bool
     * @throws WireException
     */
    public function evaluate_condition($codes=[]) {
...
}

 

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 d'Hinnisdaël
      Happy new year, everybody 🥬
      I've been sitting on this Dashboard module I made for a client and finally came around to cleaning it up and releasing it to the wider public. This is how it looks.
      ProcessWire Dashboard

      If anyone is interested in trying this out, please go ahead! I'd love to get some feedback on it. If this proves useful and survives some real-world testing, I'll add this to the module directory.
      Download
      You can find the latest release on Github.
      Documentation
      Check out the documentation to get started. This is where you'll find information about included panel types and configuration options.
      Custom Panels
      My goal was to make it really simple to create custom panels. The easiest way to do that is to use the panel type template and have it render a file in your templates folder. This might be enough for 80% of all use cases. For anything more complex (FormBuilder submissions? Comments? Live chat?), you can add new panel types by creating modules that extend the DashboardPanel base class. Check out the documentation on custom panels or take a look at the HelloWorld panel to get started. I'm happy to merge any user-created modules into the main repo if they might be useful to more than a few people.
       Disclaimer
      This is a pre-release version. Please treat it as such — don't install it on production sites. Just making sure 🍇
      Roadmap
      These are the things I'm looking to implement myself at some point. The wishlist is a lot longer, but those are the 80/20 items that I probably won't regret spending time on.
      Improve documentation & add examples ⚙️ Panel types Google Analytics ⚙️ Add new page  🔥 Drafts 🔥 At a glance / Page counter 404s  Layout options Render multiple tabs per panel panel groups with heading and spacing between ✅ panel wrappers as grid item (e.g. stacked notices) ✅ Admin themes support AdminThemeReno and AdminThemeDefault ✅ Shortcuts panel add a table layout with icon, title & summary ✅ Chart panel add default styles for common chart types ✅ load chart data from JS file (currently passed as PHP array) Collection panel support image columns ✅ add buttons: view all & add new ✅
    • By Pip
      Hi everyone!
      I'm trying out the Login/Register module for my site. Noted that the module assigns the newly registered user to login-register role. 
      Once you modify the login-register role's permissions, particularly adding page-edit, the new member role will be set to guest. 
      Thing is I'd like to grant my new users the power to create their own pages. Any advice? 
      Thanks. 
    • By Juergen
      Hello @ all,
      I am creating a new inputfield/fieldtype to store opening hours, but I am struggeling to save values from multiple dynamic created inputfields in 1 column of the database.
      Scenario:
      The user can enter one or more opening times per day in a UI.
      Fe:
      Monday open from 08:00 to 12:00 and from 14:00 to 17:00 Tuesday open from 08:00 to 12:00 and from 14:00 to 19:00 and so on
      Via a little JavaScript you can add as much opening times as you need per day - the additional inputfield will be created dynamically.
      After form submission all the values are in the POST array -> this works (see example below):
      ProcessWire\WireInputData Object ( [openinghours_mo-0-start] => 09:00 [openinghours_mo-0-finish] => 13:00 [openinghours_mo-1-start] => 14:00 [openinghours_mo-1-finish] => 18:00 [openinghours_mo-2-start] => 21:00 [openinghours_mo-2-finish] => 23:00 [openinghours_tu-0-start] => 09:00 [openinghours_tu-0-finish] => 13:00 [openinghours_tu-1-start] => 14:00 [openinghours_tu-1-finish] => 18:00 [openinghours_we-0-start] => 09:00 [openinghours_we-0-finish] => 13:00 [openinghours_we-1-start] => 14:00 [openinghours_we-1-finish] => 18:00 [openinghours_th-0-start] => 09:00 [openinghours_th-0-finish] => 13:00 [openinghours_th-1-start] => 14:00 [openinghours_th-1-finish] => 18:00 [openinghours_fr-0-start] => 09:00 [openinghours_fr-0-finish] => 13:00 [openinghours_fr-1-start] => 14:00 [openinghours_fr-1-finish] => 18:00 [openinghours_sa-0-start] => [openinghours_sa-0-finish] => [openinghours_so-0-start] => [openinghours_so-0-finish] => ) The property name is always the name attribute of the field 😉 . If the property is empty means closed on that day.
      Now I need to combine all those values into 1 array (or json array) and store it in the database in 1 column called 'hours' in my case (see screenshot below):

      In my ___processInput(WireInputData $input) method I have tried to make it work like this:
      public function ___processInput(WireInputData $input): self { $name = $this->attr('name'); $value = $this->attr('value'); //input object includes always every input on the page, so lets filter out only inputs from this field //we need to do this, because the number of values is variable - so extract only values that starts with $name.'_' $nameAttributes = []; foreach($input as $key=>$value){ if(substr($key, 0, strlen($name.'_')) === $name.'_'){ $nameAttributes[$key] = $value; } } // loop through all inputfields of this fieldtype $time_values = []; foreach($nameAttributes as $nameAttr => $value) { $time_values[$nameAttr] = $value; } } //save it in the database $input->set('hours', serialize($time_values)); return $this; } The only important part of this code is the last part with the serialize function.
      After saving it will create a record in the database, but the value is always NULL (default value) (see below).

      Checking $time_values returns all the values, but printing out "$this" shows me that the property "hours" inside the Openinghours object is empty (see below) - so the mistake must be there, but I dont know where?!?!?!?
      [title] => Home [openinghours] => ProcessWire\OpeningHours Object ( [data] => Array ( [hours] => ) ) If I check the sleepValue() method or the sanitizeValue() - they are also empty. So it seems that the values will not reach these methods. I havent found a clear documentation of whats going on behind the saving process of an inputfield.
      As far as I know the saving process starts with the form submission. The values are in the POST array and will be processed by the processInput() method. Before they will be saved in the database they will be sanitized by the sanitizeValue() mehtod and afterwards they will be prepared for storage in the sleepValue() method.  The last step is the storage itself.
      Has someone an idea what is missing by storing values from multiple fields into 1 database column or has someone a working example of such a scenario on github to help me out.
      A clear explanation of the storage process will be also helpful.
      Thanks and best regards
    • By Gadgetto
      SnipWire - Snipcart integration for ProcessWire
      Snipcart is a powerful 3rd party, developer-first HTML/JavaScript shopping cart platform. SnipWire is the missing link between Snipcart and the content management framework ProcessWire.
      With SnipWire, you can quickly turn any ProcessWire site into a Snipcart online shop. The SnipWire plugin helps you to get your store up and running in no time. Detailed knowledge of the Snipcart system is not required.
      SnipWire is free and open source licensed under Mozilla Public License 2.0! A lot of work and effort has gone into development. It would be nice if you could donate an amount to support further development:

      Status update links (inside this thread) for SnipWire development
      2020-07-03 -- SnipWire 0.8.7 (beta) released! Fixes some small bugs and adds an indicator for TEST mode 2020-04-06 -- SnipWire 0.8.6 (beta) released! Adds support for Snipcart subscriptions and also fixes some problems 2020-03-21 -- SnipWire 0.8.5 (beta) released! Improves SnipWires webhooks interface and provides some other fixes and additions 2020-03-03 -- SnipWire 0.8.4 (beta) released! Improves compatibility for Windows based Systems. 2020-03-01 -- SnipWire 0.8.3 (beta) released! The installation and uninstallation process has been heavily revised. 2020-02-08 -- SnipWire 0.8.2 (beta) released! Added a feature to change the cart and catalogue currency by GET, POST or SESSION param 2020-02-03 -- SnipWire 0.8.1 (beta) released! All custom classes moved into their own namespaces. 2020-02-01 -- SnipWire is now available via ProcessWire's module directory! 2020-01-30 -- SnipWire 0.8.0 (beta) first public release! (module just submitted to the PW modules directory) 2020-01-28 -- added Custom Order Fields feature (first SnipWire release version is near!) 2020-01-21 -- Snipcart v3 - when will the new cart system be implemented? 2020-01-19 -- integrated taxes provider finished (+ very flexible shipping taxes handling) 2020-01-14 -- new date range picker, discount editor, order notifiactions, order statuses, and more ... 2019-11-15 -- orders filter, order details, download + resend invoices, refunds 2019-10-18 -- list filters, REST API improvements, new docs platform, and more ... 2019-08-08 -- dashboard interface, currency selector, managing Orders, Customers and Products, Added a WireTabs, refinded caching behavior 2019-06-15 -- taxes provider, shop templates update, multiCURL implementation, and more ... 2019-06-02 -- FieldtypeSnipWireTaxSelector 2019-05-25 -- SnipWire will be free and open source Plugin Key Features
      Fast and simple store setup Full integration of the Snipcart dashboard into the ProcessWire backend (no need to leave the ProcessWire admin area) Browse and manage orders, customers, discounts, abandoned carts, and more Multi currency support Custom order and cart fields Process refunds and send customer notifications from within the ProcessWire backend Process Abandoned Carts + sending messages to customers from within the ProcessWire backend Complete Snipcart webhooks integration (all events are hookable via ProcessWire hooks) Integrated taxes provider (which is more flexible then Snipcart own provider) Useful Links
      SnipWire in PW modules directory SnipWire Docs (please note that the documentation is a work in progress) SnipWire @GitHub (feature requests and suggestions for improvement are welcome - I also accept pull requests) Snipcart Website  

       
      ---- INITIAL POST FROM 2019-05-25 ----
       
    • By Juergen
      Hello @ all!
      I want to share a simple fieldtype and inputfield to store address data with you.
      I have created this inputfield for learning purposes and it has no fancy functionality. It is simply for storing address data such as street, number, postalcode and so on in one table. As an addition you can store latitude and longitude too, so you can use them in maps.
      Here is a screenshot of what it looks like:

      You can select which fields are mandatory and you can choose if the inputs for longitude and latitude should be displayed. These settings can be configured in the field configuration.
      If you find this inputfield useful you can download it at https://github.com/juergenweb/FieldtypeSimpleAddress
      There you will find a detailed explanation. If you have an idea of an usefull feature that can be added or you have detected a bug, please report it in my github account.
       
×
×
  • Create New...