Rendering form in node view or field formatter drupal 8

 

In some cases you need to show form in formatter for example add  a product to cart where in you need to show up form in node view. the Simple Way to do it is to return form in your formatter.

add to cart formatter

namespace Drupal\modulename\Plugin\Field\FieldFormatter;

use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Field\FieldItemListInterface;

/**
 * Plugin implementation of the 'field_myform' formatter.
 *
 * @FieldFormatter(
 *   id = "myform",
 *   module = "mymodule",
 *   label = @Translation("My field Form"),
 *   field_types = {
 *     "text","string"
 *   }
 * )
 */
class MyFieldFormatter extends FormatterBase {

 /**
   * {@inheritdoc}
   */
  public function viewElements(FieldItemListInterface $items, $langcode) {      
    $form = \Drupal::formBuilder()->getForm('\Drupal\modulename\Form\FormClassname');
    $elements = $form;
    return $elements;
  }

}