4

I want to create my own version of the add/edit form for an entity defined in contrib module (drupal_commerce). I assumed i'd be able to adapt the example here http://www.foreach.be/blog/how-manipulate-forms-drupal-8 to alter route for entity forms. However i am getting the following when i try to load edit

Fatal error: Call to a member function getEntityTypeId() on a non-object in C:\xampp\htdocs\tocyn\core\lib\Drupal\Core\Entity\EntityForm.php on line 82

My route subscriber looks like:

    if ($route = $collection->get('entity.commerce_product.edit_form') ) {
        $defs = $route->getDefaults();
        $route->setDefault('_form', '\Drupal\mymod\Form\EventForm');
    }

And my new form:

class EventForm extends Drupal\commerce_product\Form\ProductForm
{
   public function buildForm(array $form, FormStateInterface $form_state)
   {

      // doing nothing much here
      return $form;
   }
}

Do i need to do something with _entity_form also?? Grateful for any feedback Mathew

2 Answers 2

4

Alternatively, you can use hook_entity_type_alter() to override the default form handler classes. It would be something like:

/**
 * Implements hook_entity_type_alter().
 */
function mymod_entity_type_alter(array &$entity_types){
  $entity_types['commerce_product']->setHandlerClass('form', array(
    'edit' => 'Drupal\mymod\Form\EventForm'
  ));
}
0

You need to change

$route->setDefault('_form', '\Drupal\mymod\Form\EventForm');

To

$route->setDefault('_entity_form', '\Drupal\mymod\Form\EventForm');

Otherwise the upcasting and other magical things are broken. See \Drupal\Core\Entity\Routing\DefaultHtmlRouteProvider::getEditFormRoute where it gets defined initially.

2
  • I spotted that earlier on and tried it but it gave me a Drupal\Component\Plugin\Exception\PluginNotFoundException: The "\Drupal\mymod\Form\EventForm" entity type does not exist. in Drupal\Core\Entity\EntityTypeManager->getDefinition() (line 130 of core\lib\Drupal\Core\Entity\EntityTypeManager.php). I assumed that it was still looking for an '<entity>.<operation>' format as in the getEditFromRoute, instead of the form path as in your suggestion?
    – Mathew
    Feb 12, 2016 at 20:13
  • ok so just tried the above with entity.comment.edit_form re routed to my form extending CommentForm this time. Just incase something in Product Entity setup is causing it to fail - but I am getting a access denied on trying to access edit form - confused?!
    – Mathew
    Feb 13, 2016 at 20:27

Your Answer

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

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