<?php
use phpformbuilder\Form;
use phpformbuilder\Validator\Validator;
use phpformbuilder\database\Mysql;
/* =============================================
start session and include form class
============================================= */
session_start();
include_once rtrim($_SERVER['DOCUMENT_ROOT'], DIRECTORY_SEPARATOR) . '/phpformbuilder/Form.php';
/* =============================================
validation if posted
============================================= */
if ($_SERVER["REQUEST_METHOD"] == "POST" && Form::testToken('movies-form') === true) {
// create validator & auto-validate required fields
$validator = Form::validate('movies-form');
// additional validation
$validator->email()->validate('user-email');
// check for errors
if ($validator->hasErrors()) {
$_SESSION['errors']['movies-form'] = $validator->getAllErrors();
} else {
/* (disabled in demo - no database enabled)
require_once rtrim($_SERVER['DOCUMENT_ROOT'], DIRECTORY_SEPARATOR) . '/phpformbuilder/database/db-connect.php';
require_once rtrim($_SERVER['DOCUMENT_ROOT'], DIRECTORY_SEPARATOR) . '/phpformbuilder/database/Mysql.php';
$db = new Mysql();
$filter['user-email'] = Mysql::sqlValue($_POST['user-email'], Mysql::SQLVALUE_TEXT);
$update['movie'] = Mysql::SQLValue($_POST['movie']);
if (!$db->UpdateRows('movies', $update, $filter)) {
$msg = '<p class="alert alert-danger">' . $db->error() . '<br>' . $db->getLastSql() . '</p>' . "\n";
} else {
*/
$msg = '<p class="alert alert-success">Database updated successfully !</p>' . " \n";
// $msg = '<p class="alert alert-success">Database updated successfully !<br>Last query : <strong>' . $db->getLastSql() . '</strong></p>'. " \n";
/*
}
*/
}
}
/* The demo is not connected to any database and use the array below to build the options.
Uncomment this part of code if you want to retrieve the options values from your database
$categories_ids = array();
$categories = array();
$qry = 'SELECT id, category FROM categories';
$db = new Mysql();
$db->query($qry);
$db_count = $db->rowCount();
if(!empty($db_count)) {
while (! $db->endOfSeek()) {
$row = $db->row();
$categories_ids[] = $row->categories_ids;
$categories[] = $row->categories;
}
}
*/
// values for demo
$db_count = 10;
$categories_ids = array('1', '2', '3', '4', '5', '6', '7', '8', '9', '10');
$categories = array(
'Action',
'Adventure',
'Animation',
'Comedy',
'Documentary',
'Drama',
'Horror',
'Mystery',
'Thriller',
'War'
);
$form = new Form('movies-form', 'vertical', 'novalidate');
$form->setMode('development');
$form->startFieldset('<h2 class="mb-5">Choose a movie category</h2>');
for ($i = 0; $i < $db_count; $i++) {
$form->addOption('category', $categories_ids[$i], $categories[$i]);
}
$form->addSelect('category', 'Categories', 'class=select2, required');
// create a div with an id to retrieve the dependent select box with Ajax
$form->addHtml('<div id="movies"> </div>');
$form->addInput('email', 'user-email', '', 'Your email : ', 'required');
$form->addHtml('<p> </p>');
$form->addBtn('submit', 'submit-btn', 1, 'Submit <i class="fa fa-check ml-2" aria-hidden="true"></i>', 'class=btn btn-success ladda-button, data-style=zoom-in');
$form->endFieldset();
// jQuery validation
$form->addPlugin('formvalidation', '#movies-form');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Bootstrap 4 Form - Dependent Select dropdown form</title>
<meta name="description" content="Bootstrap 4 Form Generator - Example of dynamic dropdown depending on a main select box">
<link rel="canonical" href="https://www.phpformbuilder.pro/templates/bootstrap-4-forms/dependent-select-dropdown.php" />
<!-- Bootstrap 4 CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<!-- Font awesome icons -->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.2/css/all.css" integrity="sha384-oS3vJWv+0UjzBfQzYUhtDYW+Pj2yciDJxpsK1OYPAYjqT085Qq/1cq5FLXAZQ7Ay" crossorigin="anonymous">
<?php $form->printIncludes('css'); ?>
</head>
<body>
<h1 class="text-center">Php Form Builder - Dependent Select dropdown form<br><small>Dynamic dropdown depending on a main select box</small></h1>
<div class="container h-100">
<div class="row justify-content-center">
<div class="col-md-11 col-lg-10">
<?php
if (isset($msg)) {
echo $msg;
}
$form->render();
?>
</div>
</div>
</div>
<!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<!-- Bootstrap 4 JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<?php
$form->printIncludes('js');
$form->printJsCode();
?>
<script>
$(document).ready(function() {
$('select[name="category"]').on('change', function() {
let target = $('#movies');
$.ajax({
url: 'dependent-select-dropdown-form/ajax-dependent-select-dropdown.php',
type: 'POST',
data: {
'movie_id': $('select[name="category"]').val()
}
}).done(function(data) {
target.html(data);
var run = window.run;
if (typeof(run) != 'undefined') {
setTimeout(run, 0);
}
}).fail(function(data, statut, error) {
console.log(error);
});
})
$('select[name="category"]').trigger('change');
});
</script>
</body>
</html>