0

I am using drupal 8 rest and I want to be able to do a few computations and return custom json messages as per the defined condition when posting a user. I am using the already existing /entity/user/ resource provided by core out of the box. I tried to create a custom module and tried to use the Drupal\rest\ResourceResponse class in the module file like below:

function magri_rest_user_presave($account) {

    if (isset($account->field_region->value)) {

        $taxonomy_query = \Drupal::entityQuery('taxonomy_term');
        $taxonomy_query ->condition('vid', "region")
            ->condition('name', $account->field_region->value);
        $tids = $taxonomy_query->execute();

        $tid = array_values($tids)[0];


        if($tid){
            //set taxonomy ref field on user entity
            $account->field_region_tax->target_id = $tid;

        }else{
            die;
            $response = ['message' => 'Region not found'];
            return new ResourceResponse($response);
        }
    }
}

This does not stop the rest call to return the custom message. Is there a way I can archive this withouts creating my own custom rest plugin?

1 Answer 1

2

You can't return a response from a presave hook. You can however throw an exception, which in a json route will return a json error message:

throw new NotFoundHttpException('Region not found!');

If you want to change the default error response, implement an exception subscriber to catch this exception and return your own response.

For reference the default exception handler: ExceptionJsonSubscriber::on4xx

13
  • Thank you, but this just throws the exception its not returning a json error message Sep 4, 2019 at 21:11
  • If you have a json route, what I don't know, then Drupal can out-of-the-box return a json error message, as explained in the second part of my answer. In other cases you might need to implement your own exception subscriber.
    – 4uk4
    Sep 5, 2019 at 6:25
  • okay maybe if you point me in the right direction. What is a json route? I am using the rest module, together with REST UI and RESTful Web Services. Sep 5, 2019 at 9:06
  • Add ?_format=json to the requested url.
    – 4uk4
    Sep 5, 2019 at 9:29
  • yet it has. It is actually the only allowed format on all my configured resources. hal_json and xml are disabled. Sep 5, 2019 at 9:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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