diff --git a/assets/js/wp-graphql-acf.js b/assets/js/wp-graphql-acf.js new file mode 100644 index 0000000..983609b --- /dev/null +++ b/assets/js/wp-graphql-acf.js @@ -0,0 +1,34 @@ +/* global jquery */ +'use strict'; + +(function ($) { + $(document).ready(function () { + + /** + * Toggle “GraphQL Field Name” rqeuirement based on “Show in GraphQL” toggle. + */ + $('#acf_field_group-show_in_graphql').on('change', function () { + var graphqlFieldNameWrap = $('.acf-field[data-name="graphql_field_name"]'), + graphqlLabel = graphqlFieldNameWrap.find('label'), + graphqlInput = $('#acf_field_group-graphql_field_name'); + + if ($(this).is(':checked')) { + + // Add span.acf-required if necessary. + if (graphqlFieldNameWrap.find('.acf-required').length === 0) { + graphqlLabel.append('*'); + } + + // Toggle required attributes and visual features. + graphqlFieldNameWrap.addClass('is-required'); + graphqlLabel.find('.acf-required').show(); + graphqlInput.attr('required', true); + } else { + graphqlFieldNameWrap.removeClass('is-required'); + graphqlLabel.find('.acf-required').hide(); + graphqlInput.attr('required', false); + } + + }); + }); +}(jQuery)); diff --git a/src/class-acfsettings.php b/src/class-acfsettings.php index ae19d78..a7257bb 100644 --- a/src/class-acfsettings.php +++ b/src/class-acfsettings.php @@ -31,6 +31,17 @@ public function init() { */ add_action( 'acf/render_field_settings', [ $this, 'add_field_settings' ], 10, 1 ); + /** + * Register admin scripts. + */ + add_action( 'admin_enqueue_scripts', [ $this, 'register_assets' ] ); + } + + /** + * Register admin JS. + */ + public function register_assets() { + wp_register_script( 'wp-graphql-acf', plugin_dir_url( WPGRAPHQL_ACF_FILE ) . 'assets/js/wp-graphql-acf.js', array( 'jquery' ), WPGRAPHQL_ACF_VERSION, true ); } /** @@ -49,6 +60,11 @@ public function add_field_settings( $field ) { return; } + /** + * Enqueue the admin JS. + */ + wp_enqueue_script( 'wp-graphql-acf' ); + /** * Render the "show_in_graphql" setting for the field. */ @@ -103,7 +119,7 @@ public function add_field_group_settings( $field_group ) { 'type' => 'text', 'prefix' => 'acf_field_group', 'name' => 'graphql_field_name', - 'required' => true, + 'required' => isset( $field_group['show_in_graphql'] ) ? (bool) $field_group['show_in_graphql'] : false, 'placeholder' => ! empty( $field_group['graphql_field_name'] ) ? $field_group['graphql_field_name'] : null, 'value' => ! empty( $field_group['graphql_field_name'] ) ? $field_group['graphql_field_name'] : null, ] diff --git a/wp-graphql-acf.php b/wp-graphql-acf.php index 083dda7..80f1a8d 100644 --- a/wp-graphql-acf.php +++ b/wp-graphql-acf.php @@ -26,6 +26,9 @@ */ const WPGRAPHQL_REQUIRED_MIN_VERSION = '0.3.2'; +const WPGRAPHQL_ACF_VERSION = '0.2.1'; // Used for JS cache-busting. +const WPGRAPHQL_ACF_FILE = __FILE__; + /** * Initialize the plugin *