0

I've spent the last 6 hours trying to figure this out, I'm likely being dumb.

I'm trying to create a POST endpoint that has parameters that are required based on the value of another parameter.

register_rest_route(
        'thing/v1',
        '/thingy/(?P<foo>\d+)',
        array(
            'methods'  => 'POST',
            'callback' => array( $this, 'create_something' ),
            'args'     => array(
                'foo' => array(
                    'required' => true,
                    'type'     => 'integer',
                ),
                'bar' => array(
                    'required' => true, // make this false if foo = 3
                    'type'     => 'integer',
                ),
            ),
        )
    );

I've tried a few things including:

  • Setting a callback as the required value. (It didn't get into the function so I guess it doesn't like callbacks).
  • Using validate_callback with required as false by default, the problem was that if the parameter wasn't submitted to the request it didn't get into the function.
  • Using validate_callback with required as true by default, the problem was that the parameter still existed when it wasn't needed (which in my case would cause issue further down the line).

I was looking through the core for a filter or hook that would let me change the required value dynamically, (a little hacky sure), but I couldn't find anything.

Just thought I'd ask here, incase I'm missing something obvious.

Thanks

0

This is how I solved similar issue using validate callback - this is the part of code where bar argument is defined:

'bar' => array(
     'default' => FALSE,
     'validate_callback' => function($param, $request, $key) {
         if ($request['foo'] == 3)
             return ($param !== FALSE);
         return FALSE;
     }
),

The default parameter causes call of validate callback even if request parameter bar is not supplied. Then in validate callback only if condition is met, check whether parameter has other than default value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.