Make WordPress Core

Opened 3 years ago

Last modified 3 years ago

#56368 new enhancement

Unable to use enum with array data type - REST API

Reported by: picocodes's profile picocodes Owned by:
Milestone: Awaiting Review Priority: normal
Severity: normal Version:
Component: REST API Keywords:
Focuses: rest-api Cc:

Description

I would like to be able to specify enums when creating a REST schema property that accepts an array of values.

For example:

<?PHP
   $query_schema['orderby'] = array(
        'description'       => __( 'Sort collection by object attribute.' ),
         'type'             => array( 'string', 'array' ),
         'default'          => 'id',
         'items'            => array(
              'type' => 'string',
         ),
         'enum'              => array( 'id', 'title', 'date', 'include' ),
         'validate_callback' => 'rest_validate_request_arg',
   );           

Change History (3)

#1 @anna.bansaghi
3 years ago

Hi @picocodes, thank you for your report!

This modified schema will accept both string values like 'id', and array values like ['id', 'title']:

<?php
   $query_schema['orderby'] = array(
    'description'       => __( 'Sort collection by object attribute.' ),
    'default'           => 'id',
    'oneOf'             => array(
        array(
            'type' => 'string',
            'enum' => array(
                'id',
                'title',
                'date',
                'include'
            )
        ),
        array(
            'type'  => 'array',
            'items' => array(
                'type' => 'string',
                'enum' => array(
                    'id',
                    'title',
                    'date',
                    'include'
                )
            )
        )
    ),
    'validate_callback' => 'rest_validate_request_arg',
);
Version 1, edited 3 years ago by anna.bansaghi (previous) (next) (diff)

#2 @anna.bansaghi
3 years ago

  • Keywords reporter-feedback added

#3 @anna.bansaghi
3 years ago

  • Keywords reporter-feedback removed

I have just noticed another ticket which was reporting issues with the schema I have suggested: #54740
I am sorry giving bad advice!

Last edited 3 years ago by anna.bansaghi (previous) (diff)
Note: See TracTickets for help on using tickets.