0

Suppose, I've created -name -machine_name an entity_type myentity with its schema as:

-name
-machine_name

Next, I want to create another entity subentity that will be grouped under myentity.

I've create both the entities, but somehow during the form making, I'm clueless how to retrieve the myentity data under which I'm creating the subentity and save it.

subentiy schema:

-name
-parent (parent == myentity->machine_name)
  • Which entity is the reference field attached to? – Clive Jul 20 '14 at 14:04
  • @Clive: I've updated the question. The subentity parent field should be attached to myentity machine_name – xan Jul 20 '14 at 14:12
1

I'm not sure if your case is closer to the typical bundle/config entity > content entity use case (because you mention machine name, so that sounds like a config entity to me) or content entity > content entity but the way this works is pretty much the same.

You need to define a route that contains the parent entity ID, then create your entity with the reference to that and then display the add form for it.

Examples for the first use case are for example node type/node or vocabulary/term, the second are comments. While the first is usually not seen as a hierarchy/grouping, it's essentially that.

Route from node.routing.yml:

node.add:
  path: '/node/add/{node_type}'
  defaults:
    _content: '\Drupal\node\Controller\NodeController::add'
    _title_callback: '\Drupal\node\Controller\NodeController::addPageTitle'
  requirements:
    _node_add_access: 'node:{node_type}'
  options:
    _node_operation_route: TRUE

NodeController::add

public function add(NodeTypeInterface $node_type) {
  $account = $this->currentUser();
  $langcode = $this->moduleHandler()->invoke('language', 'get_default_langcode', array('node', $node_type->type));

  $node = $this->entityManager()->getStorage('node')->create(array(
    'uid' => $account->id(),
    'name' => $account->getUsername() ? : '',
    'type' => $node_type->type,
    'langcode' => $langcode ? $langcode : $this->languageManager()->getCurrentLanguage()->id,
  ));

  $form = $this->entityFormBuilder()->getForm($node);

  return $form;
}

The only relevant part is passing through the entity reference value ($node_type) to the new sub-entity. There are issues to make the uid/name and the langcode default value handling work by default.

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.