By means of a custom module I compile an order form. This module queries all nodes of a specific content type, reads out name, price etc. and provides an order form in a block.
Result: https://mettler-beef.ch/bestellung

Problem: If I change a product (node), the cache (probably) prevents the rebuilding of the form.

Desired solution: Upon saving a product, the cache for the custom form and, if necessary, for the custom block is to be invalidated.
How can I achieve this?

Comments

vm’s picture

The question is best served in the 'module development and code questions' forum. Please edit the post and move it. Thank you.

May also want to include your code.

piridium’s picture

Thank you, VM. I moved the thread to the 'module development and code questions' section. Also, I attach the relevant part of the code here:

./src/Form/OrderForm.php

/**
 * @file
 * Contains \Drupal\pi_order_form\Form\OrderForm.
 */
namespace Drupal\pi_order_form\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Component\Utility\UrlHelper;
/** Order form. */
class OrderForm extends FormBase {
  public function getFormId() {
    return 'pi_order_form';
  }
  public function buildForm(array $form, FormStateInterface $form_state) {
    // Get product information
    $nids = \Drupal::entityQuery('node')->condition('type','produkt')->sort('field_sort_order','ASC')->sort('title','ASC')->execute();
    $nodes =  \Drupal\node\Entity\Node::loadMultiple($nids);
    // build the table
    $form['table'] = array(
      '#type' => 'table',
      '#tree' => TRUE,
    );
    // write rows
    foreach ($nodes as $key=>$node){
      // skip unpublished nodes
      if (!$node->isPublished()){
        continue;
      }
      // add product-title
      $form['table'][$key]['product'] = array(
        '#type' => 'textfield',
        '#default_value' => $node->getTitle(),
        '#attributes' => array(
          'readonly' => 'readonly',
        ),
      );
      // ... additional form elements per product ...
    }
    // ... additional general form elements ...
    $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Submit'),
    );
    return $form;
  }
}

./src/Plugin/Block/OrderBlock.php

/**
 * @file
 * Contains \Drupal\pi_order_form\Block\OrderBlock.
 */
namespace Drupal\pi_order_form\Plugin\Block;
use Drupal\Core\Form\FormInterface;
use Drupal\Core\Block\BlockBase;
/**
 * Provides a 'order' block.
 *
 * @Block(
 *   id = "order_block",
 *   admin_label = @Translation("Order block"),
 *   category = @Translation("pi_order_form")
 * )
 */
class OrderBlock extends BlockBase {
  public function build() {
    $form = \Drupal::formBuilder()->getForm('Drupal\pi_order_form\Form\OrderForm');
    return $form;
   }
}

Can I define some kind of cache-context (I don't even know if it's the right term here) and have a hook_node_save()-function which invalidates this cache-context after editing a product-node?