CakePHP 3.3 Help me format an HTML & lt; select & gt; using a foreign key

advertisements

I am having trouble populating a HTML <select> dropdown using a FOREIGN KEY.

For the sake of clarity, these are the relevant tables:

CREATE TABLE categories(
    id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    categoryName VARCHAR(255) NOT NULL,
    categoryDescription TEXT
);

CREATE TABLE products(
    id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    productName VARCHAR(255) NOT NULL,
    productPrice DECIMAL,
    availableStock INT,
    category_id INT NOT NULL,
    FOREIGN KEY category_id(id)
    REFERENCES categories(id)
    ON UPDATE CASCADE
    ON DELETE RESTRICT
);

Here is my CategoriesController.php class and relevant function:

class CategoriesController extends AppController
{
    public function displayCategories()
    {
        $categories = $this->Categories->find('all');
        $this->set('categories', $categories);
        $products = $this->Categories->Products->find('all');  // I need help with the find function here
        $this->set('products', $products);
    }

And here is my displayCategories.ctp file

<h1>Available Categories</h1>

<form action="#" method="post">

<select name=clubCategory>
    <option value="">Select a category</option>
    <?php foreach ($categories as $category): ?>
    <option><?= $category->categoryName ?></option>
    <?php endforeach; ?>

    <input class="button" type="submit" value="Submit the form"/>

</select>
</form>
<br>
<?php
if((filter_input(INPUT_POST, 'clubCategory')) != null){
    $selected_val = filter_input(INPUT_POST, 'clubCategory');
    echo "You have selected :" .$selected_val;
}
?>

I would like to use the value stored in $selected_val to populate a table of products with the matching id.


You have missed option value.. Try this code. I hope it's will help you.

<h1>Available Categories</h1>
  <form action="#" method="post">
    <select name=clubCategory>
      <option value="">Select a category</option>
        <?php foreach ($categories as $category): ?>
           <option value="<?= $category->id ?>"><?= $category->categoryName ?></option>
        <?php endforeach; ?>
   </select>
   <input class="button" type="submit" value="Submit the form"/>
  </form>
  <br>
  <?php
     if((filter_input(INPUT_POST, 'clubCategory')) != null){
     $selected_val = filter_input(INPUT_POST, 'clubCategory');
     echo "You have selected :" .$selected_val;
   }
   ?>

Thank you!