Jump to content

Detect changes made to repeater field


Harmen
 Share

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:

756090769_Schermafbeelding2018-11-26om16_24_04.thumb.png.2407971d0fb8ac9830fcc492449c02ec.png

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;
	$row->save();
	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;

		$featuresRow->save();
	}
	$row->save();
}
$featuresPage->save();

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

$form->add($inputfield);

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

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){
        $form->processInput($this->input->post);
        if (count($form->getErrors())) return false;

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

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

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

                if ($group["id"] == 0) {
                    continue;
                } 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) {
                        $this->message($feature);
                        $attribute = $feature->feature_attribute_selector;
                        $value = $feature->feature_value_selector;

                        if ($attribute["id"] == 0 || $value["id"] == 0) {
                            continue;
                        } 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));
        }
        $product->save();

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

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

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

    }

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!

 

~Harmen

Link to comment
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
 Share

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By Joachim
      Long time user and huge fan of PW, but this time I can't find an answer to my question this time:
      For my social media buttons, I have a Repeater field called var_link_web with two fields: one is for the URL, and the other is an Images field containing two images that are used as a background-image for a <div>, of which the second is the ':hover' version (although activated through JavaScript here). 
      There are four instances of this Repeater, of which two are 'turned off'.
      I use the following PHP in my _main.php to call them, wrapped in <p><?php == ?></p>:
      $s_m_button = $variables->var_link_web; foreach($s_m_button as $button){ $button_image = $button->var_link_image->first->height(80); $button_image2 = $button->var_link_image->eq(1)->height(80); echo " <a href='$button->var_link_url'> <div class='image_link' style='background-image:url({$button_image->url})' onMouseOver='this.style.backgroundImage=url({$button_image2->url})' onMouseOut='this.style.backgroundImage=url({$button_image->url})'> </div> </a>"; }; ($variables leads to an unpublished page with several fields I want to have easy access to, and is defined in _init.php.)
      However, this gives me the following result:

      I have no idea where the extra <p>'s come from. The URL field has the 'HTML Entity Encoder' turned on. What's even weirder is that the HTML source file seemingly renders correctly:
      <p> <a href='https://www.facebook.com/'> <div class='image_link' style='background-image:url(/site/assets/files/1045/icons-facebook-square.0x80.png)' onMouseOver='this.style.backgroundImage="url(/site/assets/files/1045/icons-facebook-square2.0x80.png)"' onMouseOut='this.style.backgroundImage="url(/site/assets/files/1045/icons-facebook-square.0x80.png)"'> </div> </a> <a href='https://www.instagram.com/'> <div class='image_link' style='background-image:url(/site/assets/files/1046/icons-instagram-square.0x80.png)' onMouseOver='this.style.backgroundImage="url(/site/assets/files/1046/icons-instagram-square2.0x80.png)"' onMouseOut='this.style.backgroundImage="url(/site/assets/files/1046/icons-instagram-square.0x80.png)"'> </div> </a> </p> Removing the JavaScript has no effect. I'm probably missing something obvious, but am at a loss here.
       
      Thank you in advance!
    • By Robin S
      This module lets you add some custom menu items to the main admin menu, and you can set the dropdown links dynamically in a hook if needed.
      Sidenote: the module config uses some repeatable/sortable rows for the child link settings, similar to the ProFields Table interface. The data gets saved as JSON in a hidden textarea field. Might be interesting to other module developers?
      Custom Admin Menus
      Adds up to three custom menu items with optional dropdowns to the main admin menu.
      The menu items can link to admin pages, front-end pages, or pages on external websites.
      The links can be set to open in a new browser tab, and child links in the dropdown can be given an icon.
      Requires ProcessWire v3.0.178 or newer.
      Screenshots
      Example of menu items

      Module config for the menus

      Link list shown when parent menu item is not given a URL

      Advanced
      Setting child menu items dynamically
      If needed you can set the child menu items dynamically using a hook.
      Example:
      $wire->addHookAfter('CustomAdminMenus::getMenuChildren', function(HookEvent $event) { // The menu number is the first argument $menu_number = $event->arguments(0); if($menu_number === 1) { $colours = $event->wire()->pages->findRaw('template=colour', ['title', 'url', 'page_icon']); $children = []; foreach($colours as $colour) { // Each child item should be an array with the following keys $children[] = [ 'icon' => $colour['page_icon'], 'label' => $colour['title'], 'url' => $colour['url'], 'newtab' => false, ]; } $event->return = $children; } }); Create multiple levels of flyout menus
      It's also possible to create multiple levels of flyout submenus using a hook.

      For each level a submenu can be defined in a "children" item. Example:
      $wire->addHookAfter('CustomAdminMenus::getMenuChildren', function(HookEvent $event) { // The menu number is the first argument $menu_number = $event->arguments(0); if($menu_number === 1) { $children = [ [ 'icon' => 'adjust', 'label' => 'One', 'url' => '/one/', 'newtab' => false, ], [ 'icon' => 'anchor', 'label' => 'Two', 'url' => '/two/', 'newtab' => false, 'children' => [ [ 'icon' => 'child', 'label' => 'Red', 'url' => '/red/', 'newtab' => false, ], [ 'icon' => 'bullhorn', 'label' => 'Green', 'url' => '/green/', 'newtab' => false, 'children' => [ [ 'icon' => 'wifi', 'label' => 'Small', 'url' => '/small/', 'newtab' => true, ], [ 'icon' => 'codepen', 'label' => 'Medium', 'url' => '/medium/', 'newtab' => false, ], [ 'icon' => 'cogs', 'label' => 'Large', 'url' => '/large/', 'newtab' => false, ], ] ], [ 'icon' => 'futbol-o', 'label' => 'Blue', 'url' => '/blue/', 'newtab' => true, ], ] ], [ 'icon' => 'hand-o-left', 'label' => 'Three', 'url' => '/three/', 'newtab' => false, ], ]; $event->return = $children; } }); Showing/hiding menus according to user role
      You can determine which menu items can be seen by a role by checking the user's role in the hook.
      For example, if a user has or lacks a role you could include different child menu items in the hook return value. Or if you want to conditionally hide a custom menu altogether you can set the return value to false. Example:
      $wire->addHookAfter('CustomAdminMenus::getMenuChildren', function(HookEvent $event) { // The menu number is the first argument $menu_number = $event->arguments(0); $user = $event->wire()->user; // For custom menu number 1... if($menu_number === 1) { // ...if user does not have some particular role... if(!$user->hasRole('foo')) { // ...do not show the menu $event->return = false; } } });  
      https://github.com/Toutouwai/CustomAdminMenus
      https://processwire.com/modules/custom-admin-menus/
    • By tcnet
      This module for ProcessWire sends a notification email for each failed login attempt. Similar modules exists already in the module directory of ProcessWire. However, this module is designed to notify, even if specified user doesn't exist.
      Settings
      The settings for this module are located in the menu Modules=>Configure=>LoginFailNotifier.
      Notification email
      Specifies the email address to which the notification emails should be sent.
        Email subject
      Specifies the subject line for the notification email.
        Post variables
      Specifies the $_POST variables to be included in the notification email. Each variable must be separated by a comma. For example: login_name,login_pass
        Server variables
      Specifies the $_SERVER variables to be included in the notification email. Each variable must be separated by a comma. For example: REMOTE_ADDR,HTTP_USER_AGENT
      Link to ProcessWire module directory:
      https://processwire.com/modules/login-fail-notifier/
      Link to github.com:
      https://github.com/techcnet/LoginFailNotifier
    • By Fokke
      ProcessWire 3.x markup module for rendering meta tags in HTML document head section. Note that this module is not a full-blown SEO solution, but rather a simple tool for rendering meta tags based on module configuration. Adding custom meta tags is also supported.
      Built-in meta tags
      The following meta tags are supported out-of-the-box:
      Document title consisting of page title and site name Character set Canonical Viewport Description Keywords Hreflang tags Open Graph og:title og:site_name og:type og:url og:description og:image og:image:width og:image:height Twitter meta tags twitter:card twitter:site twitter:creator twitter:title twitter:description twitter:image Facebook meta tags fb:app_id The full documentation with configurable options can be found here: https://github.com/Fokke-/MarkupMetadata
       
      Requirements:
      ProcessWire>=3.0.0 PHP >=7.1 Installation using Composer
      composer require fokke/markup-metadata Manual installation
      Download latest version from https://github.com/Fokke-/MarkupMetadata/archive/master.zip Extract module files to site/modules/MarkupMetadata directory.
    • By m.sieber
      ITRK-Service for ProcessWire
      Module for the automated transfer of imprint, data protection declaration and terms and conditions from IT-Recht Kanzlei to your ProcessWire installation
      What is ITRK Service for ProcessWire?
      ITRK-Service for ProcessWire is a free module for ProcessWire CMS. It provides an interface to the update service of IT-Recht Kanzlei, via which the legal texts of your online presence are automatically updated. In this way, the texts remain legally secure and warning-proof in the long term. Imprint, data protection declaration, revocation and general terms and conditions are currently supported.
      You can find our documentation (in german language) here: https://www.pupit.de/itrk-service-for-processwire/dokumentation/

      Download: https://www.pupit.de/itrk-service-for-processwire/
      Github: https://github.com/pupit-de/pwItrkServiceConnector
×
×
  • Create New...