0

Here is my situation: I am using the ECK module with Drupal 8 to create entities and bundles, and the new REST core module to create API features.

I have installed the REST_UI module, and I enabled the route for the entity I am interested in.

Here's my issue: I created an entity type and a bundle with ECK, and I can then create a new entity when I am calling the /entity/entity_type_name endpoint with a POST request, giving the following parameter as json:

{
   "type":[{"target_id":"bundle_name"}],
   "field_test_text":[{"value":"test"}]
}

However, this is only working when I have only one entity type in my list of entities; Let's say for example I decide to create a new entity type, then run the same request, I got the following error message:

Drupal\Core\Entity\Exception\AmbiguousEntityClassException: Multiple entity types found for Drupal\eck\Entity\EckEntity

I understand that apparently, now that I have multiple entity types, the Entity API is not able to understand what should be the type of the entity it has to create (which I find pretty weird, considering that I am providing it in the URL under this form /entity/entity_type_name and that there are different routes available for the different types of entities that I have).

I guess I need to pass an extra parameter in my json for Drupal to understand what kind of entity it should create, but what would be this parameter ? I've been trying to look online and in the documentation, but I cannot figure out how to do this.

schankam
  • 10,778
  • 2
  • 15
  • 26
  • Do you have an API url to list available entities ? Maybe you can identify what's wrong like that – Fky Aug 09 '17 at 11:51
  • I check the available entities using the ECK admin interface, it gives me their machine name. – schankam Aug 10 '17 at 02:20
  • can you dump call and return when you are in admin interface ? it's to see how it process ? – Fky Aug 11 '17 at 11:53

1 Answers1

1

I had the same problem, and here is how I resolved it:

  1. Enable the HAL module.
  2. Enable hal_json under Accepted request formats in /admin/config/services/rest for that particular resource.

Then, in your POST request, use headers:

  • Content-Type: application/hal+json
  • X-CSRF-Token: [AUTH SESSION TOKEN]

And the body of the request being:

{
  "_links": {
   "type": {
     "href": "http://localhost:8080/rest/type/[ENTITY_TYPE]/[ENTITY_BUNDLE]"
   }
  },
  "title":[
    {"value": "This is a new entity title"}
  ],
  "field_example":[
    {"value": "This is an example of a custom text field value."}
  ]
}

Drupal is reading the entity type and bundle from the _links.type.href string.

For example, if your entity type was automobile and your bundle was car, your URL would be "http://localhost:8080/rest/type/automobile/car"

Steven
  • 551
  • 3
  • 7