0

Drupal version: 8.7.x

I created a module that retrieves meals based on the given ingredients. I display the ingredients with a delete button and the meals underneath them. However I don't know where to start when it comes to deleting the ingredients using the button in the template.

templates/block--recipe-search-block.html.twig:

  <ol class="u-row u-margin-top">
    {% for ingredient in ingredientList %}
      <li class="u-col-md-3 u-col-sm-6 u-col-xs-12">
        {{ ingredient['ingredient'] }}
        <form id="delete-ingredient" action="" method="post">
          <button value="{{ ingredient['pid'] }}" type="submit">
            <span class="icon-close"></span>
          </button>
        </form>
      </li>

    {% endfor %}
  </ol>

This is how I pass them: src/Plugin/Block/RecipeSearch.php:

class RecipeSearch extends BlockBase {

  public function build() {
    /*
     * RETRIEVE ALL GIVEN INGREDIENTS FROM THE DATABASE
     * WHERE THE ID EQUALS THE CURRENTLY LOGGED IN USER.
     */
    $current_user = \Drupal::currentUser();
    $current_user_id = $current_user->id();
    $uid = $current_user_id - 1;

    $connection = Database::getConnection();
    $ingredients = [];

    $result = $connection->select('ingredient_list', 'il');
    $result->fields('il', array('ingredient', 'pid'));
    $result->condition('uid', $uid);
    $data = $result->execute();
    $results = $data->fetchAll(\PDO::FETCH_OBJ);

    foreach ($results as $field) {
      array_push($ingredients, ["ingredient" => $field->ingredient, "pid" => $field->pid]);
    };

    return [
      '#theme' => 'recipe_search_block',
      '#ingredientList' => $ingredients,
    ];
  }
}

recipe_search.module:

function recipe_search_theme() {
  return [
    'recipe_search_block' => [
      'template' => 'block--recipe-search-block',
      'base hook' => 'block',
      'variables' => [
        'ingredientList' => NULL,
      ],
    ],
  ];
}

If someone could point me in the right direction, that would be much appreciated!

  • 3
    This should be handled by a form generated by Form API for starters, not a static HTML form. – Kevin Jun 19 at 14:30
  • Yes, and you will probably find it advisable to build your application using Drupal's entity API rather than using custom db tables. And always start by considering the built-in entity types (node, taxonomy ...) before building your own. Saves much grief and potential security holes. – Alfred Armstrong Jun 19 at 16:13
  • Allright, so make the ingredients a vocabulary for example and then use a view That displays the taxonomy terms associated with the current user ? – Geordi Feijens Jun 20 at 11:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.