Как игнорировать пустые поля формы? - PullRequest
0 голосов
/ 22 апреля 2020

Эй, я пытаюсь создать небольшой интернет-магазин, я создаю страницу «Добавить товар», у меня есть форма, где вам нужно ввести имя, цену и атрибут thir, который изменяется в зависимости от типа категорию, которую вы выбрали, например, если я выбрал категорию «Книга», то в форме появляется строка «Вес», теперь форма self выглядит следующим образом:

<!-- HTML form for creating a product -->
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">

    <table class='table table-hover table-responsive table-bordered'>

        <tr>
            <td>Name</td>
            <td><input type='text' name='name' class='form-control' /></td>
        </tr>

        <tr>
            <td>Price</td>
            <td><input type='text' name='price' class='form-control' /></td>
        </tr>

        <script>
$(document).ready(function(){
    $('.form-control').on('change', function() {

      //If red is selected, show red, hide yellow and blue.
      if ( this.value == 1)
      {
        $("#weight").show();
        $("#size").hide();
        $("#height").hide();
      }

       //If yellow is selected, show yellow, hide red and blue.
      if ( this.value == 2)
      {
        $("#weight").hide();
        $("#size").show();
        $("#height").hide();

      }
      if ( this.value == 3)
      {
        $("#weight").hide();
        $("#size").hide();
        $("#height").show();

      }


    });
});

 </script>
    <div >
        <tr id="weight" style="display:none">

            <td >Weight</td>
            <td><input type="text" name='weight' class='form-control'></input></td>
        </tr>
    </div>


        <tr id="size" style="display:none">

            <td>Size</td>
            <td><textarea name='size' class='form-control'></textarea></td>
        </tr>

        <tr id="height" style="display:none">

            <td>Height</td>
            <td><textarea name='height' class='form-control'></textarea></td>
            <td>Length</td>
            <td><textarea name='lenght' class='form-control'></textarea></td>
            <td>Width</td>
            <td><textarea name='width' class='form-control'></textarea></td>
        </tr>

        <tr>
            <td>Category</td>
            <td>

Сценарий существует раньше показывал разные строки в зависимости от выбранной вами категории

Теперь я столкнулся с проблемой, что он создаст продукт и отправит данные в базу данных при заполнении всех полей, как я могу сделать чтобы форма не делала этого?

Вот остаток моего кода

<?php
// include database and object files
include_once 'config/database.php';
include_once 'objects/product.php';
include_once 'objects/category.php';

// get database connection
$database = new Database();
$db = $database->getConnection();

// pass connection to objects
$product = new Product($db);
$category = new Category($db);

// set page headers
$page_title = "Create Product";
include_once "layout_header.php";

echo "<div class='right-button-margin'>";
    echo "<a href='index.php' class='btn btn-default pull-right'>Read Products</a>";
echo "</div>";

?>
<?php 
// if the form was submitted - PHP OOP CRUD Tutorial
if($_POST){

    // set product property values
    $product->name = $_POST['name'];
    $product->price = $_POST['price'];
    $product->category_id = $_POST['category_id'];
    $product->size = $_POST['size'];
    $product->weight = $_POST['weight'];
    $product->lenght = $_POST['lenght'];
    $product->width = $_POST['width'];
    $product->height = $_POST['height'];


    // create the product
    if($product->create()){
        echo "<div class='alert alert-success'>Product was created.</div>";
    }

    // if unable to create the product, tell the user
    else{
        echo "<div class='alert alert-danger'>Unable to create product.</div>";
    }
}
?>

<!-- HTML form for creating a product -->
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">

    <table class='table table-hover table-responsive table-bordered'>

        <tr>
            <td>Name</td>
            <td><input type='text' name='name' class='form-control' /></td>
        </tr>

        <tr>
            <td>Price</td>
            <td><input type='text' name='price' class='form-control' /></td>
        </tr>

        <script>
$(document).ready(function(){
    $('.form-control').on('change', function() {

      //If red is selected, show red, hide yellow and blue.
      if ( this.value == 1)
      {
        $("#weight").show();
        $("#size").hide();
        $("#height").hide();
      }

       //If yellow is selected, show yellow, hide red and blue.
      if ( this.value == 2)
      {
        $("#weight").hide();
        $("#size").show();
        $("#height").hide();

      }
      if ( this.value == 3)
      {
        $("#weight").hide();
        $("#size").hide();
        $("#height").show();

      }


    });
});

 </script>
    <div >
        <tr id="weight" style="display:none">

            <td >Weight</td>
            <td><input type="text" name='weight' class='form-control'></input></td>
        </tr>
    </div>


        <tr id="size" style="display:none">

            <td>Size</td>
            <td><textarea name='size' class='form-control'></textarea></td>
        </tr>

        <tr id="height" style="display:none">

            <td>Height</td>
            <td><textarea name='height' class='form-control'></textarea></td>
            <td>Length</td>
            <td><textarea name='lenght' class='form-control'></textarea></td>
            <td>Width</td>
            <td><textarea name='width' class='form-control'></textarea></td>
        </tr>

        <tr>
            <td>Category</td>
            <td>
            <?php
// read the product categories from the database
$stmt = $category->read();

// put them in a select drop-down
echo "<select class='form-control' name='category_id'>";
    echo "<option>Select category...</option>";

    while ($row_category = $stmt->fetch(PDO::FETCH_ASSOC)){
        extract($row_category);
        echo "<option value='{$id}'>{$name}</option>";
    }

echo "</select>";
?>
            </td>
        </tr>

        <tr>
            <td></td>
            <td>
                <button type="submit" class="btn btn-primary">Create</button>
            </td>
        </tr>

    </table>
</form>

<?php

// footer
include_once "layout_footer.php";
?>

Нужно ли мне изменить способ отображения разных атрибутов в зависимости от выбранной категории? Заранее спасибо!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...