Jump to content

Detect changes made to repeater field

Recommended Posts

Hi All,

I've made a previous regarding an issue which I solved but I stumbled across a new issue :). Below again the explanation needed.

You need a short introduction for this. The company I am working for has approx. 80 products on their website and they all have their own features. The features are imported from an older system which isn't used anymore. Back then, when they changed from the old system to PW, we imported the features into the product pages as a JSON-array so the pages could load a bit faster as exploding a JSON array is a bit faster than loading in a lot of items from a table or a repeater field.

How the JSON array looks like: 

    "2": { 										// The ID of the group that contains the actual features
        "name": "Model and function",			// The name of the group
        "features": {
            "43": {								// Attribute ID
                "name": "Resolution (DPI)",		// Attribute name
                "values": {						
                    "896": "500-1500-2000-3500" // Value ID and value name

Now we are adding a few more products to the catalog with new features and some that are already in use by other products but I am really struggling to assign the right ID's with the correct values in 7 different languages without messing up filters etc. So I decided to develop a module that lets you easily add feature groups, attributes and values as pages and connect these to the product using a repeater. This started by exporting all the current groups, attributes and values and import them as pages in the following structure:

- Features
	- Feature Groups
		- Group 1
		- Group 2
		- ...
	- Feature Attributes
		- Attribute 1
		- Attribute 2
		- ...
	- Feature Values
		- Value 1
		- Value 2
		- ...

Secondly, I created a repeater field that I assigned to the 'Features'-page that can handle the JSON structure explained above by seeing each item of the repeater field as a group. Inside each item you can select the group page and you will find another repeater which contains 2 page selectors to select an attribute and a value. A single repeater field looks like this:


Next step was to create a module that gets this field as an Inputfield from the Features page. Once the user has finished adding groups, attributes and values he can click on save and I export all the values in the same JSON array structure as earlier but now the ID's of the groups, attributes and values are just the page ID's. This works great to add new features to new products. 

BUT, sometimes the features of a product change or need to be changed and you don't want to change the JSON array manually.

So my idea was to do the same thing as adding the features, but now you grab the values from the product first and populate the items of the repeater field.

$featuresPage = wire("pages")->get("template=features");
$featureGroups = json_decode($product->features, true);
foreach ($featureGroups as $featureGroupID => $featureGroup){
	$row = $featuresPage->features_repeater->getNewItem();
	$groupPage = wire("pages")->get($featureGroupID);
	$row->feature_group_selector = $groupPage;
	foreach ($featureGroup["features"] as $featureID => $feature){
		$featuresRow = $row->feature_repeater->getNewItem();
		$attributePage = wire("pages")->get($featureID);
		$valuePage = wire("pages")->get(key($feature['values']));

		$featuresRow->feature_attribute_selector = $attributePage;
		$featuresRow->feature_value_selector = $valuePage;


$f = wire('fields')->get('features_repeater');
$inputfield = $f->getInputfield($featuresPage);


$f = $this->modules->get("InputfieldSubmit");
$f->name = 'updateFeatures';
$f->label = 'Update Features';
$f->icon = 'plus';
$f->value = 'Update Features';

Then the user can change / add features, click save and done!

It is possible to update the feature attributes and values, but when I change the feature group value, it seems like PW creates a new field behind the scenes and keeps the old value as well. So let's say I have the following feature structure:

- Feature Group 1
	- Feature attribute 1	- Feature value 1

Now I want to update Feature Group 1 to Feature Group 2, below is the desired result and the actual result:

// === Desired result
- Feature Group 2
	- Feature attribute 1	- Feature value 1
// === Actual result    
- Feature Group 2
	- Feature attribute 1	- Feature value 1
- Feature Group 1
	- Feature attribute 1	- Feature value 1


I am using the following function to update the features:

    private function processForm5_UpdateFeatures(InputfieldForm $form){
        if (count($form->getErrors())) return false;

        $pageID = $this->session->selectedProduct;
        $product = wire('pages')->get($pageID);

        $repeater = $form->get("features_repeater")->value;

        $languages = wire("languages");
        foreach ($languages as $language) {
            $return_array = [];
            $i = 0;
            foreach ($repeater as $repeaterItem) {
                $group = $repeaterItem->feature_group_selector;

                if ($group["id"] == 0) {
                } else {
                    $group = wire("pages")->get($group["id"]);
                    $feature_group_name = &$return_array[$group->id]['name'];
                    if (!isset($feature_group_name)) $feature_group_name = $group->title->getLanguageValue($language);

                    $features = $repeaterItem->feature_repeater;

                    foreach ($features as $feature) {
                        $attribute = $feature->feature_attribute_selector;
                        $value = $feature->feature_value_selector;

                        if ($attribute["id"] == 0 || $value["id"] == 0) {
                        } else {
                            $attribute = wire("pages")->get($attribute["id"]);
                            $value = wire("pages")->get($value["id"]);

                            $return_array[$group->id]['features'][$attribute->id]['name'] = $attribute->title->getLanguageValue($language);
                            $return_array[$group->id]['features'][$attribute->id]['values'][$value->id] = $value->title->getLanguageValue($language);
            $product->features->setLanguageValue($language->name, json_encode($return_array, JSON_UNESCAPED_UNICODE));

        $featuresPage = wire("pages")->get("template=features");

/*        $this->messages("clear all");
        $this->errors("clear all");*/

        $this->message("Updated all features for {$product->title}");


Is there a way to avoid the current result and get the desired result? Why is there even a new repeater page created for the new value? Anything that can help me is greatly appreciated!



Share this post

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By Robin S
      A community member raised a question and I thought a new sanitizer method for the purpose would be useful, hence...
      Sanitizer Transliterate
      Adds a transliterate method to $sanitizer that performs character replacements as defined in the module config. The default character replacements are based on the defaults from InputfieldPageName, but with uppercase characters included too.
      Install the Sanitizer Transliterate module.
      Customise the character replacements in the module config as needed.
      Use the sanitizer on strings like so:
      $transliterated_string = $sanitizer->transliterate($string);
    • By dimitrios
      this module can publish content of a Processwire page on a Facebook page, triggered by saving the Processwire page.
      To set it up, configure the module with a Facebook app ID, secret and a Page ID. Following is additional configuration on Facebook for developers:
      Minimum Required Facebook App configuration:
      on Settings -> Basics, provide the App Domains, provide the Site URL, on Settings -> Advanced, set the API version to 2.10, add Product: Facebook Login, on Facebook Login -> Settings, set Client OAuth Login: Yes, set Web OAuth Login: Yes, set Enforce HTTPS: Yes, add "http://www.example.com/processwire/page/" to field Valid OAuth Redirect URIs. This module is configurable as follows:
      Templates: posts can take place only for pages with the defined templates. On/Off switch: specify a checkbox field that will not allow the post if checked. Specify a message and/or an image for the post.
      edit the desired PW page and save; it will post right after the initial Facebook log in and permission granting. After that, an access token is kept.
      PW module directory: http://modules.processwire.com/modules/auto-fb-post/ Github: https://github.com/kastrind/AutoFbPost   Note: Facebook SDK for PHP is utilized.

    • By Peter Knight
      I have 2 repeater types working with the Repeater Matrix.
      To keep things simple, I have
      image gallery a downloads gallery. I can't quite figure out how to echo the contents from within a product_gallery. 
      I can get the code below to display the text 'An image gallery' but not the bunch of images within this.
      I'm not sure though if it's my variable trail or my nested echo statement.
      <?php foreach($page->components as $item) { if($item->type == 'product_gallery') { echo " An image gallery..."; foreach($product_gallery->images as $photo) { echo " An image <image src='{$photo->url}'> "; } } else if($item->type == 'downloads') { echo " A download gallery... "; } } ?> Thanks
    • By thomasaull
      I created a little helper module to trigger a CI pipeline when your website has been changed. It's quite simple and works like this: As soon as you save a page the module sets a Boolean via a pages save after hook. Once a day via LazyCron the module checks if the Boolean is set and sends a POST Request to a configurable Webhook URL.
      Some ideas to extend this:
      make request type configurable (GET, POST) make the module trigger at a specified time (probably only possible with a server cronjob) trigger manually Anything else? If there's interest, I might put in some more functionality. Let me know what you're interested in. Until then, maybe it is useful for a couple of people 🙂
      Github Repo: https://github.com/thomasaull/CiTrigger
    • By Robin S
      I created this module a while ago and never got around to publicising it, but it has been outed in the latest PW Weekly so here goes the support thread...
      Unique Image Variations
      Ensures that all ImageSizer options and focus settings affect image variation filenames.

      When using methods that produce image variations such as Pageimage::size(), ProcessWire includes some of the ImageSizer settings (height, width, cropping location, etc) in the variation filename. This is useful so that if you change these settings in your size() call a new variation is generated and you see this variation on the front-end.
      However, ProcessWire does not include several of the other ImageSizer settings in the variation filename:
      upscaling cropping, when set to false or a blank string interlace sharpening quality hidpi quality focus (whether any saved focus area for an image should affect cropping) focus data (the top/left/zoom data for the focus area) This means that if you change any of these settings, either in $config->imageSizerOptions or in an $options array passed to a method like size(), and you already have variations at the requested size/crop, then ProcessWire will not create new variations and will continue to serve the old variations. In other words you won't see the effect of your changed ImageSizer options on the front-end until you delete the old variations.
      The Unique Image Variations module ensures that any changes to ImageSizer options and any changes to the focus area made in Page Edit are reflected in the variation filename, so new variations will always be generated and displayed on the front-end.
      Install the Unique Image Variations module.
      In the module config, set the ImageSizer options that you want to include in image variation filenames.
      Installing the module (and keeping one or more of the options selected in the module config) will cause all existing image variations to be regenerated the next time they are requested. If you have an existing website with a large number of images you may not want the performance impact of that. The module is perhaps best suited to new sites where image variations have not yet been generated.
      Similarly, if you change the module config settings on an existing site then all image variations will be regenerated the next time they are requested.
      If you think you might want to change an ImageSizer option in the future (I'm thinking here primarily of options such as interlace that are typically set in $config->imageSizerOptions) and would not want that change to cause existing image variations to be regenerated then best to not include that option in the module config after you first install the module.
  • Create New...