Initialize the form state and the entity before the first form build.
protected function init(array &$form_state, EntityInterface $entity, $field_name) {
// @todo Remove when http://drupal.org/node/1346214 is complete.
$entity = $entity
->getBCEntity();
// @todo Rather than special-casing $node->revision, invoke prepareEdit()
// once http://drupal.org/node/1863258 lands.
if ($entity
->entityType() == 'node') {
$entity
->setNewRevision(in_array('revision', variable_get('node_options_' . $entity
->bundle(), array())));
$entity->log = NULL;
}
$form_state['entity'] = $entity;
$form_state['field_name'] = $field_name;
// @todo Allow the usage of different form modes by exposing a hook and the
// UI for them.
$form_display = entity_get_render_form_display($entity, 'default');
// Let modules alter the form display.
$form_display_context = array(
'entity_type' => $entity
->entityType(),
'bundle' => $entity
->bundle(),
'form_mode' => 'default',
);
\Drupal::moduleHandler()
->alter('entity_form_display', $form_display, $form_display_context);
$form_state['form_display'] = $form_display;
}