Support

Account

Home Forums Add-ons Flexible Content Field Unique ID for Flexible Content row Reply To: Unique ID for Flexible Content row

  • You have to generate your own unique ID.

    I do this with the sites I am working on to have an ID for generation of dynamic CSS and to allow clients the ability to link to portions of the page using #{ID}.

    What I have is a group with a single field called layout_id. This group is cloned into all of my flex layouts.

    I add a filter to this field to make it readonly.

    
    add_filter('acf/load_field/key=field_5dd6ea9c6325c'.$key, 'readonly_field', 20, 1);
    function readonly_field($field) {
      $field['readonly'] = true;
      return $field;
    }
    

    Then I have a bit of JS in my custom admin.js file that generates the unique ID values. I do this in the JS to ensure that the id is unique on the page. It is potentially possible for the ID value to change, but this is rare. This cannot be done with prepare field because all of the rows would end up with the same ID.

    
    (function($){
      if (typeof acf != 'undefined') {
        acf.add_action('ready append', function($el) {
          // array to hold list of existing ID values
          var layout_ids = [];
          // selector targets id field butnot hidden clones of layouts
          var fields = $('[data-key="field_5dd6ea9c6325c"] .acf-input input').not('.clones [data-key="field_5dd6ea9c6325c"] .acf-input input');
          if (fields.length) {
            for (i=0; i<fields.length; i++) {
              var field = $(fields[i]);
              var value = field.val();
              if (value == '' || layout_ids.indexOf(value) != -1) {
                value = 'pnl-'+acf.uniqid();
                field.val(value);
                field.trigger('change');
              }
              layout_ids.push(value);
            }
          }
          
        });
      }
    })(jQuery);
    

    If yo wanted to not use the JS method then you’d need to construct an acf/save_post action that did the generation after the fields are saved to ensure that they are unique on the page.