Support

Account

Home Forums Front-end Issues Javascript API: Set data-conditions manually?

Solving

Javascript API: Set data-conditions manually?

  • I wonder whether this is possible, as I couldn’t find any documentation on it: I’d like to manually set the data-conditions attribute with Javascript, so that the ACF script handles the display of a field.

    data-conditions='[[{"field":"field_5ac0da6acf4b7","operator":"!=","value":"my_value"}]]'

    I assume I’d have to call some kind of registration function so that the ACF script is aware of this condition as I’d probably set the condition attribute on document.ready.

    The reason I want to do this is that I’d like to use the available functionality to show/hide fields for a is in a different field group than the conditional field it is supposed to depend on.

  • You can do this using an acf/load_field or an acf/prepare_field filter. In either of these functions you can set the conditional logic and base it on any field using the field’s key.

    You could probably also do this using JavaScript by accessing the data value of the field. The value looks like a json encoded array. However I do not know if this will work, I don’t know it this need to be there before ACF initializes or not or if there is a way to reinitialize it if it does not.

    
    $('[data-key="YOUR FIELD KEY"]').data('conditions', 'JSON ENCODED ARRAY');
    
  • Sounds like a great idea using the PHP filters. I’ll check for the correct implementation and post the code.

    For the JS solution, I tried adding a condition from the browser inspector which doesn’t seem to work. So, I assume this needs to happen before the initialization.

  • Basically, what I do is I create a field group with a similar set of fields and use the export to PHP to see how the conditional logic should look. Then you just have to replace the field key with the key of the field you actually want to use. This can’t be done when building a field, but like I said, any field that exists on the same page will do the trick, even if it is in a different group. Or it did the last time I tried it.

Viewing 4 posts - 1 through 4 (of 4 total)

The topic ‘Javascript API: Set data-conditions manually?’ is closed to new replies.