Skip to content

RelationshipControl

Junaid Bhura edited this page Jun 1, 2023 · 2 revisions

This component is used to create custom relationships in a block. It inherits BaseControl.

Usage

import { RelationshipControl } = gumponents.components;

<RelationshipControl
	label="Select offices"
	value={ attributes.offices }
	searchApiPath="/offices/search"
	getItemsApiPath="/offices/get"
	onSelect={ ( offices ) => setAttributes( { offices } ) }
/>

Props

label

The label for the control.

  • Type: String
  • Required: No

help

The help text for the control.

  • Type: String
  • Required: No

searchApiPath

A path to a WordPress REST API endpoint, excluding wp-json/. A POST request is sent to this endpoint with a string: query. It contains the search query the user has typed into the search box. This value may be empty, in which case, it is recommended to still return results so the initial render can contain some results. See "REST API Values" below.

  • Type: String
  • Required: Yes

getItemsApiPath

A path to a WordPress REST API endpoint, excluding wp-json/. A POST request is sent to this endpoint with an array: items. It contains the values (IDs) that the user has selected. Return a list of values that match these IDs. See "REST API Values" below.

  • Type: String
  • Required: Yes

buttonLabel

The label for the select button.

  • Type: String
  • Required: No

value

The selected IDs for this control.

  • Type: Array
  • Required: Yes

onSelect

A function that receives the values of the control.

  • Type: Function
  • Required: Yes

max

The maximum number of selections that can be made with this control.

  • Type: Number
  • Required: No

REST API Values

This control expects the following responses:

Flat Values

If values are flat, the value must match the ID.

[
	[
		'id'    => '1',
		'value' => '1',
		'label' => 'Item 1',
	],
	[
		'id'    => '2',
		'value' => '2',
		'label' => 'Item 2',
	],
	[
		'id'    => '3',
		'value' => '3',
		'label' => 'Item 3',
	],
]

Values As An Object

If values are passed as an object, an ID parameter must be sent along with the value. This way we can set the values as the ID:

onSelect={ ( offices ) => setAttributes( { offices: offices.map( ( office ) => office.id ) } ) }

[
	[
		'id'    => '1',
		'value' => [
			'id'        => '1',
			'something' => 'something',
		],
		'label' => 'Item 1',
	],
	[
		'id'    => '2',
		'value' => [
			'id'        => '2',
			'something' => 'something',
		],
		'label' => 'Item 2',
	],
	[
		'id'    => '3',
		'value' => [
			'id'        => '3',
			'something' => 'something',
		],
		'label' => 'Item 3',
	],
]