I'll help fix the department addition issue. The main problem appears to be with the form submission handling and database operations. Here's the corrected version:
Key fixes made:
I'll fix the word counting functionality in the JavaScript code. Here's the corrected version:
Key improvements made to the word counting functionality:
The word count will now accurately reflect the number of words as you type, including when you paste text or make other changes to the description field.
Here's the modified version with a "+" button in the table that shows/hides the add department form:
Key changes made:
The form submission and database operations remain the same, just now triggered from the modal forms instead of the static form.
I'll fix the issue with the "Add Department" button not working. Here's the corrected version:
Key fixes made:
The button should now properly open the add department modal when clicked. The form submission will work as before, just now triggered from the modal.
Make sure your HTML for the modal form has the correct ID:
<form id="add-dept-form" action="<?php echo esc_url($_SERVER['REQUEST_URI']); ?>" method="post">
```_
<form id="add-dept-form" action="<?php echo esc_url($_SERVER['REQUEST_URI']); ?>" method="post">
```_
Here's a clean, modern implementation of a department management system with all the requested functionality:
<?php
session_start();
date_default_timezone_set('Asia/Manila');
global $wpdb;
// Database setup
$dept_table = $wpdb->prefix . 'departments';
$user_table = $wpdb->prefix . 'users';
// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_POST['add_dept'])) {
handle_add_department();
} elseif (isset($_POST['edit_dept'])) {
handle_edit_department();
}
}
// Handle GET actions
if (isset($_GET['action'])) {
if ($_GET['action'] === 'delete' && isset($_GET['id'])) {
handle_delete_department();
}
}
// Get all departments
$departments = $wpdb->get_results("
SELECT d.*, COUNT(u.id) as user_count
FROM $dept_table d
LEFT JOIN $user_table u ON d.id = u.department_id
GROUP BY d.id
", ARRAY_A);
function handle_add_department() {
global $wpdb, $dept_table;
$name = sanitize_text_field($_POST['name']);
$description = sanitize_textarea_field($_POST['description']);
if (empty($name)) {
set_message('Department name is required', 'error');
return;
}
$result = $wpdb->insert($dept_table, [
'name' => $name,
'description' => $description,
'created_at' => current_time('mysql')
]);
if ($result) {
set_message('Department added successfully', 'success');
} else {
set_message('Error adding department: ' . $wpdb->last_error, 'error');
}
}
function handle_edit_department() {
global $wpdb, $dept_table;
$id = absint($_POST['dept_id']);
$name = sanitize_text_field($_POST['name']);
$description = sanitize_textarea_field($_POST['description']);
$result = $wpdb->update($dept_table,
['name' => $name, 'description' => $description],
['id' => $id]
);
if ($result !== false) {
set_message('Department updated successfully', 'success');
} else {
set_message('Error updating department', 'error');
}
}
function handle_delete_department() {
global $wpdb, $dept_table, $user_table;
$id = absint($_GET['id']);
// Check if department has users
$user_count = $wpdb->get_var($wpdb->prepare(
"SELECT COUNT(*) FROM $user_table WHERE department_id = %d", $id
));
if ($user_count > 0) {
set_message('Cannot delete department with assigned users', 'error');
return;
}
$result = $wpdb->delete($dept_table, ['id' => $id]);
if ($result) {
set_message('Department deleted successfully', 'success');
} else {
set_message('Error deleting department', 'error');
}
}
function set_message($text, $type) {
$_SESSION['dept_message'] = $text;
$_SESSION['dept_message_type'] = $type;
}
function get_message() {
if (empty($_SESSION['dept_message'])) return null;
$message = [
'text' => $_SESSION['dept_message'],
'type' => $_SESSION['dept_message_type']
];
unset($_SESSION['dept_message']);
unset($_SESSION['dept_message_type']);
return $message;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Department Management</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
:root {
--primary: #4663ac;
--secondary: #D1B48C;
--success: #38a169;
--danger: #e53e3e;
--light: #f8f9fa;
--dark: #212529;
}
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background-color: #f4f7f9;
margin: 0;
padding: 0;
}
.container {
display: flex;
min-height: 100vh;
}
.sidebar {
width: 250px;
background-color: #c1d8f0;
padding: 20px 0;
}
.main-content {
flex: 1;
padding: 20px;
}
.card {
background: white;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
padding: 20px;
margin-bottom: 20px;
}
table {
width: 100%;
border-collapse: collapse;
}
th, td {
padding: 12px 15px;
text-align: left;
border-bottom: 1px solid #ddd;
}
th {
background-color: var(--light);
font-weight: 600;
}
tr:hover {
background-color: rgba(0,0,0,0.02);
}
.btn {
display: inline-flex;
align-items: center;
padding: 8px 16px;
border-radius: 4px;
text-decoration: none;
font-size: 14px;
cursor: pointer;
transition: all 0.2s;
}
.btn i {
margin-right: 8px;
}
.btn-primary {
background-color: var(--primary);
color: white;
border: none;
}
.btn-success {
background-color: var(--success);
color: white;
border: none;
}
.btn-danger {
background-color: var(--danger);
color: white;
border: none;
}
.btn-secondary {
background-color: #6c757d;
color: white;
border: none;
}
.modal {
display: none;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0,0,0,0.5);
z-index: 1000;
justify-content: center;
align-items: center;
}
.modal-content {
background: white;
border-radius: 8px;
width: 100%;
max-width: 500px;
padding: 20px;
box-shadow: 0 4px 20px rgba(0,0,0,0.15);
}
.form-group {
margin-bottom: 15px;
}
.form-group label {
display: block;
margin-bottom: 5px;
font-weight: 500;
}
.form-control {
width: 100%;
padding: 10px;
border: 1px solid #ddd;
border-radius: 4px;
font-size: 14px;
}
textarea.form-control {
min-height: 100px;
resize: vertical;
}
.alert {
padding: 12px 15px;
border-radius: 4px;
margin-bottom: 20px;
}
.alert-success {
background-color: #f0fff4;
color: #2f855a;
border-left: 4px solid var(--success);
}
.alert-danger {
background-color: #fff5f5;
color: #c53030;
border-left: 4px solid var(--danger);
}
</style>
</head>
<body>
<div class="container">
<!-- Sidebar -->
<aside class="sidebar">
<div style="padding: 20px; text-align: center;">
<h3 style="margin: 0; color: var(--dark);">RJL DeskTrack</h3>
</div>
<nav>
<ul style="list-style: none; padding: 0; margin: 0;">
<li><a href="#" style="display: block; padding: 12px 20px; color: var(--dark); text-decoration: none;"><i class="fas fa-tachometer-alt"></i> Dashboard</a></li>
<li><a href="#" style="display: block; padding: 12px 20px; color: var(--dark); text-decoration: none;"><i class="fas fa-users"></i> Users</a></li>
<li><a href="#" style="display: block; padding: 12px 20px; background-color: rgba(0,0,0,0.1); color: var(--dark); text-decoration: none;"><i class="fas fa-building"></i> Departments</a></li>
<li><a href="#" style="display: block; padding: 12px 20px; color: var(--dark); text-decoration: none;"><i class="fas fa-ticket-alt"></i> Tickets</a></li>
</ul>
</nav>
</aside>
<!-- Main Content -->
<main class="main-content">
<header style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
<h1 style="margin: 0;">Department Management</h1>
<div>
<button class="btn btn-success" onclick="openModal('addDeptModal')">
<i class="fas fa-plus"></i> Add Department
</button>
</div>
</header>
<!-- Message Alert -->
<?php $message = get_message(); ?>
<?php if ($message): ?>
<div class="alert alert-<?= $message['type'] ?>">
<?= $message['text'] ?>
</div>
<?php endif; ?>
<!-- Departments Table -->
<div class="card">
<table>
<thead>
<tr>
<th>ID</th>
<th>Department Name</th>
<th>Description</th>
<th>Personnel</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php foreach ($departments as $dept): ?>
<tr>
<td><?= $dept['id'] ?></td>
<td><?= esc_html($dept['name']) ?></td>
<td><?= esc_html($dept['description']) ?></td>
<td><?= $dept['user_count'] ?></td>
<td>
<button class="btn btn-primary" onclick="openEditModal(<?= $dept['id'] ?>, '<?= esc_js($dept['name']) ?>', '<?= esc_js($dept['description']) ?>')">
<i class="fas fa-edit"></i> Edit
</button>
<a href="?action=delete&id=<?= $dept['id'] ?>" class="btn btn-danger" onclick="return confirm('Are you sure you want to delete this department?')">
<i class="fas fa-trash"></i> Delete
</a>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
</main>
</div>
<!-- Add Department Modal -->
<div id="addDeptModal" class="modal">
<div class="modal-content">
<h2 style="margin-top: 0;">Add New Department</h2>
<form method="post">
<div class="form-group">
<label for="deptName">Department Name</label>
<input type="text" id="deptName" name="name" class="form-control" required>
</div>
<div class="form-group">
<label for="deptDesc">Description</label>
<textarea id="deptDesc" name="description" class="form-control"></textarea>
</div>
<div style="display: flex; gap: 10px;">
<button type="submit" name="add_dept" class="btn btn-success">
<i class="fas fa-save"></i> Save
</button>
<button type="button" class="btn btn-secondary" onclick="closeModal('addDeptModal')">
<i class="fas fa-times"></i> Cancel
</button>
</div>
</form>
</div>
</div>
<!-- Edit Department Modal -->
<div id="editDeptModal" class="modal">
<div class="modal-content">
<h2 style="margin-top: 0;">Edit Department</h2>
<form method="post">
<input type="hidden" name="dept_id" id="editDeptId">
<div class="form-group">
<label for="editDeptName">Department Name</label>
<input type="text" id="editDeptName" name="name" class="form-control" required>
</div>
<div class="form-group">
<label for="editDeptDesc">Description</label>
<textarea id="editDeptDesc" name="description" class="form-control"></textarea>
</div>
<div style="display: flex; gap: 10px;">
<button type="submit" name="edit_dept" class="btn btn-success">
<i class="fas fa-save"></i> Update
</button>
<button type="button" class="btn btn-secondary" onclick="closeModal('editDeptModal')">
<i class="fas fa-times"></i> Cancel
</button>
</div>
</form>
</div>
</div>
<script>
// Modal functions
function openModal(modalId) {
document.getElementById(modalId).style.display = 'flex';
}
function closeModal(modalId) {
document.getElementById(modalId).style.display = 'none';
}
function openEditModal(id, name, description) {
document.getElementById('editDeptId').value = id;
document.getElementById('editDeptName').value = name;
document.getElementById('editDeptDesc').value = description;
openModal('editDeptModal');
}
// Close modal when clicking outside
window.onclick = function(event) {
if (event.target.classList.contains('modal')) {
event.target.style.display = 'none';
}
}
</script>
</body>
</html>
<?php
session_start();
date_default_timezone_set('Asia/Manila');
global $wpdb;
// Database setup
$dept_table = $wpdb->prefix . 'departments';
$user_table = $wpdb->prefix . 'users';
// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_POST['add_dept'])) {
handle_add_department();
} elseif (isset($_POST['edit_dept'])) {
handle_edit_department();
}
}
// Handle GET actions
if (isset($_GET['action'])) {
if ($_GET['action'] === 'delete' && isset($_GET['id'])) {
handle_delete_department();
}
}
// Get all departments
$departments = $wpdb->get_results("
SELECT d.*, COUNT(u.id) as user_count
FROM $dept_table d
LEFT JOIN $user_table u ON d.id = u.department_id
GROUP BY d.id
", ARRAY_A);
function handle_add_department() {
global $wpdb, $dept_table;
$name = sanitize_text_field($_POST['name']);
$description = sanitize_textarea_field($_POST['description']);
if (empty($name)) {
set_message('Department name is required', 'error');
return;
}
$result = $wpdb->insert($dept_table, [
'name' => $name,
'description' => $description,
'created_at' => current_time('mysql')
]);
if ($result) {
set_message('Department added successfully', 'success');
} else {
set_message('Error adding department: ' . $wpdb->last_error, 'error');
}
}
function handle_edit_department() {
global $wpdb, $dept_table;
$id = absint($_POST['dept_id']);
$name = sanitize_text_field($_POST['name']);
$description = sanitize_textarea_field($_POST['description']);
$result = $wpdb->update($dept_table,
['name' => $name, 'description' => $description],
['id' => $id]
);
if ($result !== false) {
set_message('Department updated successfully', 'success');
} else {
set_message('Error updating department', 'error');
}
}
function handle_delete_department() {
global $wpdb, $dept_table, $user_table;
$id = absint($_GET['id']);
// Check if department has users
$user_count = $wpdb->get_var($wpdb->prepare(
"SELECT COUNT(*) FROM $user_table WHERE department_id = %d", $id
));
if ($user_count > 0) {
set_message('Cannot delete department with assigned users', 'error');
return;
}
$result = $wpdb->delete($dept_table, ['id' => $id]);
if ($result) {
set_message('Department deleted successfully', 'success');
} else {
set_message('Error deleting department', 'error');
}
}
function set_message($text, $type) {
$_SESSION['dept_message'] = $text;
$_SESSION['dept_message_type'] = $type;
}
function get_message() {
if (empty($_SESSION['dept_message'])) return null;
$message = [
'text' => $_SESSION['dept_message'],
'type' => $_SESSION['dept_message_type']
];
unset($_SESSION['dept_message']);
unset($_SESSION['dept_message_type']);
return $message;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Department Management</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
:root {
--primary: #4663ac;
--secondary: #D1B48C;
--success: #38a169;
--danger: #e53e3e;
--light: #f8f9fa;
--dark: #212529;
}
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background-color: #f4f7f9;
margin: 0;
padding: 0;
}
.container {
display: flex;
min-height: 100vh;
}
.sidebar {
width: 250px;
background-color: #c1d8f0;
padding: 20px 0;
}
.main-content {
flex: 1;
padding: 20px;
}
.card {
background: white;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
padding: 20px;
margin-bottom: 20px;
}
table {
width: 100%;
border-collapse: collapse;
}
th, td {
padding: 12px 15px;
text-align: left;
border-bottom: 1px solid #ddd;
}
th {
background-color: var(--light);
font-weight: 600;
}
tr:hover {
background-color: rgba(0,0,0,0.02);
}
.btn {
display: inline-flex;
align-items: center;
padding: 8px 16px;
border-radius: 4px;
text-decoration: none;
font-size: 14px;
cursor: pointer;
transition: all 0.2s;
}
.btn i {
margin-right: 8px;
}
.btn-primary {
background-color: var(--primary);
color: white;
border: none;
}
.btn-success {
background-color: var(--success);
color: white;
border: none;
}
.btn-danger {
background-color: var(--danger);
color: white;
border: none;
}
.btn-secondary {
background-color: #6c757d;
color: white;
border: none;
}
.modal {
display: none;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0,0,0,0.5);
z-index: 1000;
justify-content: center;
align-items: center;
}
.modal-content {
background: white;
border-radius: 8px;
width: 100%;
max-width: 500px;
padding: 20px;
box-shadow: 0 4px 20px rgba(0,0,0,0.15);
}
.form-group {
margin-bottom: 15px;
}
.form-group label {
display: block;
margin-bottom: 5px;
font-weight: 500;
}
.form-control {
width: 100%;
padding: 10px;
border: 1px solid #ddd;
border-radius: 4px;
font-size: 14px;
}
textarea.form-control {
min-height: 100px;
resize: vertical;
}
.alert {
padding: 12px 15px;
border-radius: 4px;
margin-bottom: 20px;
}
.alert-success {
background-color: #f0fff4;
color: #2f855a;
border-left: 4px solid var(--success);
}
.alert-danger {
background-color: #fff5f5;
color: #c53030;
border-left: 4px solid var(--danger);
}
</style>
</head>
<body>
<div class="container">
<!-- Sidebar -->
<aside class="sidebar">
<div style="padding: 20px; text-align: center;">
<h3 style="margin: 0; color: var(--dark);">RJL DeskTrack</h3>
</div>
<nav>
<ul style="list-style: none; padding: 0; margin: 0;">
<li><a href="#" style="display: block; padding: 12px 20px; color: var(--dark); text-decoration: none;"><i class="fas fa-tachometer-alt"></i> Dashboard</a></li>
<li><a href="#" style="display: block; padding: 12px 20px; color: var(--dark); text-decoration: none;"><i class="fas fa-users"></i> Users</a></li>
<li><a href="#" style="display: block; padding: 12px 20px; background-color: rgba(0,0,0,0.1); color: var(--dark); text-decoration: none;"><i class="fas fa-building"></i> Departments</a></li>
<li><a href="#" style="display: block; padding: 12px 20px; color: var(--dark); text-decoration: none;"><i class="fas fa-ticket-alt"></i> Tickets</a></li>
</ul>
</nav>
</aside>
<!-- Main Content -->
<main class="main-content">
<header style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
<h1 style="margin: 0;">Department Management</h1>
<div>
<button class="btn btn-success" onclick="openModal('addDeptModal')">
<i class="fas fa-plus"></i> Add Department
</button>
</div>
</header>
<!-- Message Alert -->
<?php $message = get_message(); ?>
<?php if ($message): ?>
<div class="alert alert-<?= $message['type'] ?>">
<?= $message['text'] ?>
</div>
<?php endif; ?>
<!-- Departments Table -->
<div class="card">
<table>
<thead>
<tr>
<th>ID</th>
<th>Department Name</th>
<th>Description</th>
<th>Personnel</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php foreach ($departments as $dept): ?>
<tr>
<td><?= $dept['id'] ?></td>
<td><?= esc_html($dept['name']) ?></td>
<td><?= esc_html($dept['description']) ?></td>
<td><?= $dept['user_count'] ?></td>
<td>
<button class="btn btn-primary" onclick="openEditModal(<?= $dept['id'] ?>, '<?= esc_js($dept['name']) ?>', '<?= esc_js($dept['description']) ?>')">
<i class="fas fa-edit"></i> Edit
</button>
<a href="?action=delete&id=<?= $dept['id'] ?>" class="btn btn-danger" onclick="return confirm('Are you sure you want to delete this department?')">
<i class="fas fa-trash"></i> Delete
</a>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
</main>
</div>
<!-- Add Department Modal -->
<div id="addDeptModal" class="modal">
<div class="modal-content">
<h2 style="margin-top: 0;">Add New Department</h2>
<form method="post">
<div class="form-group">
<label for="deptName">Department Name</label>
<input type="text" id="deptName" name="name" class="form-control" required>
</div>
<div class="form-group">
<label for="deptDesc">Description</label>
<textarea id="deptDesc" name="description" class="form-control"></textarea>
</div>
<div style="display: flex; gap: 10px;">
<button type="submit" name="add_dept" class="btn btn-success">
<i class="fas fa-save"></i> Save
</button>
<button type="button" class="btn btn-secondary" onclick="closeModal('addDeptModal')">
<i class="fas fa-times"></i> Cancel
</button>
</div>
</form>
</div>
</div>
<!-- Edit Department Modal -->
<div id="editDeptModal" class="modal">
<div class="modal-content">
<h2 style="margin-top: 0;">Edit Department</h2>
<form method="post">
<input type="hidden" name="dept_id" id="editDeptId">
<div class="form-group">
<label for="editDeptName">Department Name</label>
<input type="text" id="editDeptName" name="name" class="form-control" required>
</div>
<div class="form-group">
<label for="editDeptDesc">Description</label>
<textarea id="editDeptDesc" name="description" class="form-control"></textarea>
</div>
<div style="display: flex; gap: 10px;">
<button type="submit" name="edit_dept" class="btn btn-success">
<i class="fas fa-save"></i> Update
</button>
<button type="button" class="btn btn-secondary" onclick="closeModal('editDeptModal')">
<i class="fas fa-times"></i> Cancel
</button>
</div>
</form>
</div>
</div>
<script>
// Modal functions
function openModal(modalId) {
document.getElementById(modalId).style.display = 'flex';
}
function closeModal(modalId) {
document.getElementById(modalId).style.display = 'none';
}
function openEditModal(id, name, description) {
document.getElementById('editDeptId').value = id;
document.getElementById('editDeptName').value = name;
document.getElementById('editDeptDesc').value = description;
openModal('editDeptModal');
}
// Close modal when clicking outside
window.onclick = function(event) {
if (event.target.classList.contains('modal')) {
event.target.style.display = 'none';
}
}
</script>
</body>
</html>
Key Features:
Modern Clean Design:
Improved Functionality:
Code Organization:
User Experience:
The implementation maintains all the required functionality while providing a much cleaner and more professional user interface. The code is also better organized and more maintainable._
I understand the issue now. The problem is with the form submission and redirection. Let me fix this with a complete working solution:
<?php
session_start();
date_default_timezone_set('Asia/Manila');
global $wpdb;
// Database setup
$dept_table = $wpdb->prefix . 'departments';
$user_table = $wpdb->prefix . 'users';
// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_POST['add_dept'])) {
$name = sanitize_text_field($_POST['name']);
$description = sanitize_textarea_field($_POST['description']);
if (empty($name)) {
$_SESSION['dept_message'] = 'Department name is required';
$_SESSION['dept_message_type'] = 'error';
} else {
$result = $wpdb->insert($dept_table, [
'name' => $name,
'description' => $description,
'created_at' => current_time('mysql')
]);
if ($result) {
$_SESSION['dept_message'] = 'Department added successfully';
$_SESSION['dept_message_type'] = 'success';
wp_redirect(remove_query_arg(['action', 'id']));
exit;
} else {
$_SESSION['dept_message'] = 'Error adding department';
$_SESSION['dept_message_type'] = 'error';
}
}
}
elseif (isset($_POST['edit_dept'])) {
$id = absint($_POST['dept_id']);
$name = sanitize_text_field($_POST['name']);
$description = sanitize_textarea_field($_POST['description']);
$result = $wpdb->update($dept_table,
['name' => $name, 'description' => $description],
['id' => $id]
);
if ($result !== false) {
$_SESSION['dept_message'] = 'Department updated successfully';
$_SESSION['dept_message_type'] = 'success';
wp_redirect(remove_query_arg(['action', 'id']));
exit;
} else {
$_SESSION['dept_message'] = 'Error updating department';
$_SESSION['dept_message_type'] = 'error';
}
}
}
// Handle delete action
if (isset($_GET['action']) && $_GET['action'] === 'delete' && isset($_GET['id'])) {
$id = absint($_GET['id']);
// Check if department has users
$user_count = $wpdb->get_var($wpdb->prepare(
"SELECT COUNT(*) FROM $user_table WHERE department_id = %d", $id
));
if ($user_count > 0) {
$_SESSION['dept_message'] = 'Cannot delete department with assigned users';
$_SESSION['dept_message_type'] = 'error';
} else {
$result = $wpdb->delete($dept_table, ['id' => $id]);
if ($result) {
$_SESSION['dept_message'] = 'Department deleted successfully';
$_SESSION['dept_message_type'] = 'success';
} else {
$_SESSION['dept_message'] = 'Error deleting department';
$_SESSION['dept_message_type'] = 'error';
}
}
wp_redirect(remove_query_arg(['action', 'id']));
exit;
}
// Get all departments
$departments = $wpdb->get_results("
SELECT d.*, COUNT(u.id) as user_count
FROM $dept_table d
LEFT JOIN $user_table u ON d.id = u.department_id
GROUP BY d.id
", ARRAY_A);
// Get message if exists
$message = isset($_SESSION['dept_message']) ? $_SESSION['dept_message'] : null;
$message_type = isset($_SESSION['dept_message_type']) ? $_SESSION['dept_message_type'] : null;
// Clear message after displaying
unset($_SESSION['dept_message']);
unset($_SESSION['dept_message_type']);
?>
<!-- HTML and JavaScript remain exactly the same as in my previous response -->
<!-- Only change is ensuring the form action points to the current page -->
<form method="post" action="<?php echo esc_url($_SERVER['REQUEST_URI']); ?>">
<?php
session_start();
date_default_timezone_set('Asia/Manila');
global $wpdb;
// Database setup
$dept_table = $wpdb->prefix . 'departments';
$user_table = $wpdb->prefix . 'users';
// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_POST['add_dept'])) {
$name = sanitize_text_field($_POST['name']);
$description = sanitize_textarea_field($_POST['description']);
if (empty($name)) {
$_SESSION['dept_message'] = 'Department name is required';
$_SESSION['dept_message_type'] = 'error';
} else {
$result = $wpdb->insert($dept_table, [
'name' => $name,
'description' => $description,
'created_at' => current_time('mysql')
]);
if ($result) {
$_SESSION['dept_message'] = 'Department added successfully';
$_SESSION['dept_message_type'] = 'success';
wp_redirect(remove_query_arg(['action', 'id']));
exit;
} else {
$_SESSION['dept_message'] = 'Error adding department';
$_SESSION['dept_message_type'] = 'error';
}
}
}
elseif (isset($_POST['edit_dept'])) {
$id = absint($_POST['dept_id']);
$name = sanitize_text_field($_POST['name']);
$description = sanitize_textarea_field($_POST['description']);
$result = $wpdb->update($dept_table,
['name' => $name, 'description' => $description],
['id' => $id]
);
if ($result !== false) {
$_SESSION['dept_message'] = 'Department updated successfully';
$_SESSION['dept_message_type'] = 'success';
wp_redirect(remove_query_arg(['action', 'id']));
exit;
} else {
$_SESSION['dept_message'] = 'Error updating department';
$_SESSION['dept_message_type'] = 'error';
}
}
}
// Handle delete action
if (isset($_GET['action']) && $_GET['action'] === 'delete' && isset($_GET['id'])) {
$id = absint($_GET['id']);
// Check if department has users
$user_count = $wpdb->get_var($wpdb->prepare(
"SELECT COUNT(*) FROM $user_table WHERE department_id = %d", $id
));
if ($user_count > 0) {
$_SESSION['dept_message'] = 'Cannot delete department with assigned users';
$_SESSION['dept_message_type'] = 'error';
} else {
$result = $wpdb->delete($dept_table, ['id' => $id]);
if ($result) {
$_SESSION['dept_message'] = 'Department deleted successfully';
$_SESSION['dept_message_type'] = 'success';
} else {
$_SESSION['dept_message'] = 'Error deleting department';
$_SESSION['dept_message_type'] = 'error';
}
}
wp_redirect(remove_query_arg(['action', 'id']));
exit;
}
// Get all departments
$departments = $wpdb->get_results("
SELECT d.*, COUNT(u.id) as user_count
FROM $dept_table d
LEFT JOIN $user_table u ON d.id = u.department_id
GROUP BY d.id
", ARRAY_A);
// Get message if exists
$message = isset($_SESSION['dept_message']) ? $_SESSION['dept_message'] : null;
$message_type = isset($_SESSION['dept_message_type']) ? $_SESSION['dept_message_type'] : null;
// Clear message after displaying
unset($_SESSION['dept_message']);
unset($_SESSION['dept_message_type']);
?>
<!-- HTML and JavaScript remain exactly the same as in my previous response -->
<!-- Only change is ensuring the form action points to the current page -->
<form method="post" action="<?php echo esc_url($_SERVER['REQUEST_URI']); ?>">
Key fixes made:
The issue you're experiencing with the redirect to ?page_id=66&action=edit_dept&id=1 suggests there might be some JavaScript interfering with the form submission. The fixed version above:
Make sure:
action="<?php echo esc_url($_SERVER['REQUEST_URI']); ?>"This should now allow you to:
Here's the complete solution that maintains your original style and layout while implementing the improved department addition logic:
<?php
session_start();
date_default_timezone_set('Asia/Manila');
global $wpdb;
// Database table names
$dept_table_name = $wpdb->prefix . 'departments';
$user_table_name = $wpdb->prefix . 'users';
$message = '';
$message_type = '';
// Handle success messages from redirect
if (isset($_GET['message'])) {
if ($_GET['message'] === 'updated') {
$message = 'Department updated successfully!';
$message_type = 'success';
} elseif ($_GET['message'] === 'added') {
$message = 'Department added successfully!';
$message_type = 'success';
}
}
// --- Handle delete department action ---
if (isset($_GET['action']) && $_GET['action'] === 'delete_dept' && isset($_GET['id']) && isset($_GET['_wpnonce']) && wp_verify_nonce($_GET['_wpnonce'], 'delete_dept_' . absint($_GET['id']))) {
$dept_id_to_delete = absint($_GET['id']);
if ($dept_id_to_delete) {
// Check if department has users
$users_count = $wpdb->get_var($wpdb->prepare(
"SELECT COUNT(*) FROM $user_table_name WHERE department_id = %d",
$dept_id_to_delete
));
if ($users_count > 0) {
$message = 'Cannot delete department with assigned users.';
$message_type = 'error';
} else {
$deleted = $wpdb->delete(
$dept_table_name,
['id' => $dept_id_to_delete],
['%d']
);
if ($deleted) {
$message = 'Department deleted successfully!';
$message_type = 'success';
} else {
$message = 'Error deleting department.';
$message_type = 'error';
}
}
}
}
// --- Handle edit department action (prepare form) ---
$editing_dept = null;
if (isset($_GET['action']) && $_GET['action'] === 'edit_dept' && isset($_GET['id'])) {
$dept_id_to_edit = absint($_GET['id']);
if ($dept_id_to_edit) {
$editing_dept = $wpdb->get_row(
$wpdb->prepare("SELECT * FROM $dept_table_name WHERE id = %d", $dept_id_to_edit),
ARRAY_A
);
if (!$editing_dept) {
$message = 'Department not found for editing.';
$message_type = 'error';
}
}
}
// === NEW DEPARTMENT ADDITION LOGIC ===
if (isset($_POST['add_dept'])) {
$name = trim($_POST['name']);
$description = trim($_POST['description']);
// Validate inputs
if (empty($name)) {
$message = 'Department name is required.';
$message_type = 'error';
} elseif (strlen($name) > 100) {
$message = 'Department name cannot exceed 100 characters.';
$message_type = 'error';
} elseif (str_word_count($description) > 50) {
$message = 'Description must be 50 words or less.';
$message_type = 'error';
} else {
// Check if department already exists
$existing = $wpdb->get_var($wpdb->prepare(
"SELECT COUNT(*) FROM $dept_table_name WHERE name = %s",
$name
));
if ($existing > 0) {
$message = 'Department already exists.';
$message_type = 'error';
} else {
$inserted = $wpdb->insert(
$dept_table_name,
[
'name' => $name,
'description' => $description,
'created_at' => current_time('mysql')
],
['%s', '%s', '%s']
);
if ($inserted) {
wp_redirect(add_query_arg(['message' => 'added'], remove_query_arg(['action', 'id'])));
exit;
} else {
$message = 'Error adding department: ' . $wpdb->last_error;
$message_type = 'error';
}
}
}
}
// --- Handle update department form submission ---
if (isset($_POST['edit_dept'])) {
$name = trim($_POST['name']);
$description = trim($_POST['description']);
// Validate inputs
if (empty($name)) {
$message = 'Department name is required.';
$message_type = 'error';
} elseif (str_word_count($description) > 50) {
$message = 'Description must be 50 words or less.';
$message_type = 'error';
} else {
$dept_id = absint($_POST['dept_id']);
$updated = $wpdb->update(
$dept_table_name,
['name' => $name, 'description' => $description],
['id' => $dept_id],
['%s', '%s'],
['%d']
);
if ($updated !== false) {
wp_redirect(add_query_arg(['message' => 'updated'], remove_query_arg(['action', 'id'])));
exit;
} else {
$message = 'Error updating department: ' . $wpdb->last_error;
$message_type = 'error';
}
}
}
// Fetch all departments with user counts
$departments = $wpdb->get_results("
SELECT d.*, COUNT(u.id) as user_count
FROM $dept_table_name d
LEFT JOIN $user_table_name u ON d.id = u.department_id
GROUP BY d.id
", ARRAY_A);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Department Management</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
<style>
/* Keep all the original User Management styling */
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background-color: #f4f7f9;
color: #333;
}
.dashboard-container {
display: flex;
}
.sidebar {
width: 240px;
background-color: #c1d8f0;
color: #000;
height: 100vh;
position: fixed;
left: 0; top: 0;
overflow-y: auto;
box-shadow: 2px 0 5px rgba(0, 0, 0, 0.1);
z-index: 1000;
}
.sidebar-header {
padding: 20px;
text-align: center;
}
.sidebar-header .inventory-name {
font-size: 17px;
font-weight: bold;
color: #000;
}
.sidebar-menu {
padding: 0;
}
.sidebar-menu ul {
list-style: none;
margin: 0;
padding: 0;
}
.sidebar-menu li a {
display: flex;
align-items: center;
padding: 12px 20px;
text-decoration: none;
color: #000;
transition: 0.3s;
font-size: 16px;
}
.sidebar-menu li a i {
margin-right: 12px;
width: 极客时间
text-align: center;
}
.sidebar-menu li a:hover {
background-color: #ffffff;
color: #000;
}
.main-content {
margin-left: 240px;
padding: 25px;
flex-grow: 1;
}
.header {
position: fixed;
top: 0;
left: 240px;
right: 0;
display: flex;
justify-content: space-between;
align-items: center;
background-color: #4663ac;
padding: 10px 30px;
height: 60px;
z-index: 999;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}
.header-left .date-time {
font-size: 15px;
color: #fff;
font-weight: 500;
}
.header-right {
display: flex;
align-items: center;
font-size: 16px;
color: #ffffff;
}
.user-dropdown {
position: relative;
display: inline-block;
cursor: pointer;
}
.user-dropdown-content {
display: none;
position: absolute;
right极客时间
background-color: #D1B48C;
min-width: 100px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
border-radius: 4px;
}
.user-dropdown-header {
padding: 8px 12px;
background-color: #D1B48C;
border-bottom: 1px solid #e9ecef;
display: flex;
align-items: center;
gap: 8px;
}
.user-dropdown-header i {
font-size: 20px;
color: #000000;
}
.user-dropdown-content.user-info {
display: flex;
align-items: right;
gap: 1px;
color: #000000;
}
.user-dropdown-content a {
display: flex;
padding: 8px 15px;
align-items: center;
color: #000000;
text-decoration: none;
font-size: 16px;
transition: all 0.2s;
}
.user-dropdown-content a i {
font-size: 16px;
margin-right: 8px;
}
.user-dropdown-content a:hover {
text-decoration: underline;
color: #000000;
}
.user-dropdown:hover .user-dropdown-content {
display: block;
}
.header-right i {
color: #ffffff;
font-size:40px;
}
.header-right span {
font-size: 15px;
color: #ffffff;
}
h1 {
margin-top: 0;
padding-top: 0;
}
.user-management {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
gap: 20px;
}
.form-container, .table-container {
background-color: #fff;
border-radius: 8px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
padding: 15px;
margin: 10px;
width: 48%;
}
h3 {
margin: 0 0 15px 0;
color: #2f4050;
font-size: 1.5em;
}
input[type="text"], textarea, select {
width: calc(100% - 22px);
padding: 10px;
margin-bottom: 15px;
border: 1px solid #ddd;
border-radius: 4px;
}
textarea {
min-height: 100px;
resize: vertical;
}
button {
padding: 10px 15px;
border: none;
background-color: #D1B48C;
color: white;
border-radius: 4px;
cursor: pointer;
margin-top: 10px;
}
.table-container {
flex: 1;
}
table {
width: 100%;
border-collapse: collapse;
margin-top: 20px;
}
th, td {
padding: 10px;
border: 1极客时间
text-align: left;
}
th {
background-color: #f9f9f9;
}
tr:hover {
background-color: #f5f5f5;
}
.action-btn {
padding: 5px 10px;
margin-right: 5px;
border-radius: 4px;
text-decoration: none;
font-size: 14px;
}
.edit-btn {
background-color: #3498db;
color: white;
}
.delete-btn {
background-color: #e74c3c;
color: white;
}
.notice-container {
width: 100%;
margin-bottom: 20px;
}
.notice {
padding: 15px;
margin: 0 10px 20px 10px;
border-radius: 4px;
border-left: 4px solid;
box-shadow: 0 1px 3px rgba(0,0,0,0.1);
display: flex;
align-items: center;
}
.notice p {
margin: 0;
padding: 0;
font-size: 16px;
}
.notice-success {
background-color: #f0fff4;
border-color: #38a169;
color: #2f855a;
}
.notice-error {
background-color: #fff5f5;
border-color: #e53e3e;
color: #c53030;
}
.notice i {
margin-right: 10px;
font-size: 18px;
}
.word-count {
font-size: 12px;
color: #6c757d;
text-align: right;
margin-top: -10px;
margin-bottom: 10px;
}
</style>
</head>
<body>
<div class="dashboard-container">
<aside class="sidebar">
<div class="sidebar-header">
<div class="inventory-name">RJL DeskTrack</div>
</div>
<div class="sidebar-menu">
<ul>
<li><a href="http://localhost/helpdesk/?page_id=57"><i class="fas fa-tachometer-alt"></i> Dashboard</a></li>
<li><a href="http://localhost/helpdesk/?page_id=62"><i class="fas fa-users-cog"></极客时间 Users</a></li>
<li><a href="http://localhost/helpdesk/?page_id=66" class="active"><i class="fas fa-building"></i> Departments</a></li>
<li><a href="tickets.php"><i class="fas fa-ticket-alt"></i> Tickets</a></li>
<li><a href="messages.php"><i class="fas fa-envelope"></i> Messages</a></li>
<li><a href="reports.php"><i class="fas fa-chart-bar"></i> Reports</a></li>
</ul>
</div>
</aside>
<main class="main-content">
<header class="header">
<div class="header-left">
<span class="date-time" id="current-date-time"></span>
</div>
<div class="header-right">
<div class="user-dropdown">
<div class="user-info">
<span id="current-username-header">
<?= htmlspecialchars($_SESSION['username']) ?>
<i class="fas fa-user-circle"></i>
</span>
</div>
<div class="user-dropdown-content">
<div class="user-dropdown-header">
<i class="fas fa-user-circle" style="color:#000000;"></i>
<span style="color:#000000;"><?= htmlspecialchars($_SESSION['username']) ?></span>
</div>
<a href="#" onclick="return confirm('Are you sure you want to log out?');">
<i class="fas fa-sign-out-alt" style="font-size: 16px; color:#000000;"></i>Logout
</a>
</div>
</div>
</div>
</header>
<h1>Department Management</h1>
<div class="user-management">
<div class="notice-container">
<?php if ($message): ?>
<div class="notice notice-<?php echo esc_attr($message_type); ?>">
<p><?php echo esc_html($message); ?></p>
</div>
<?php endif; ?>
</div>
<div class="form-container" style="max-width: 400px;">
<h2><?php echo $editing_dept ? 'Edit Department' : 'Add New Department'; ?></h2>
<form action="<?php echo esc_url($_SERVER['REQUEST_URI']); ?>" method="post">
<input type="hidden" name="dept_id" value="<?php echo esc_attr($editing_dept['id'] ?? ''); ?>">
<div class="form-group">
<label for="name">Department Name</label>
<input type="text" id="name" name="name"
value="<?php echo esc_attr($editing_dept['name'] ?? ''); ?>"
required
maxlength="100">
</div>
<div class="form-group">
<label for="description">Description (max 50 words)</label>
<textarea id="description" name="description"><?php echo esc_textarea($editing_dept['description'] ?? ''); ?></textarea>
<div class="word-count" id="wordCount">Words: 0/50</div>
</div>
<button type="submit" name="<?php echo $editing_dept ? 'edit_dept' : 'add_dept'; ?>">
<?php echo $editing_dept ? 'Update Department' : 'Add Department'; ?>
</button>
<?php if ($editing_dept): ?>
<a href="<?php echo remove_query_arg(['action', 'id']); ?>" class="action-btn" style="background-color: #6c757d;">Cancel</a>
<?php endif; ?>
</form>
</div>
<div class="table-container">
<h2>All Departments</h2>
<table>
<thead>
<tr>
<th>ID</th>
<th>Department Name</th>
<th>Description</th>
<th>No. of Personnel</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php foreach ($departments as $dept): ?>
<tr>
<td><?php echo $dept['id']; ?></td>
<td><?php echo esc_html($dept['name']); ?></td>
<td><?php echo esc_html($dept['description']); ?></td>
<td><?php echo $dept['user_count']; ?></td>
<td>
<a href="<?php echo add_query_arg(['action' => 'edit_dept', 'id' => $dept['id']]); ?>" class="action-btn edit-btn">Edit</a>
<a href="<?php echo add_query_arg(['action' => 'delete_dept', 'id' => $dept['id'], '_wpnonce' => wp_create_nonce('delete_dept_' . $dept['id'])]); ?>" class极客时间 action-btn delete-btn" onclick="return confirm('Are you sure you want to delete this department?');">Delete</a>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
</div>
</main>
</div>
<script>
// Update date and time
function updateDateTime() {
const now = new Date();
const options = {
weekday: 'short',
year: 'numeric',
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
second: '2-digit'
};
document.getElementById("current-date-time").textContent = now.toLocaleDateString('en-US', options);
}
setInterval(updateDateTime, 1000);
updateDateTime();
// Word count for description
document.addEventListener('DOMContentLoaded', function() {
const descriptionField = document.getElementById('description');
const wordCountDisplay = document.getElementById('wordCount');
function updateWordCount() {
const text = descriptionField.value.trim();
const wordCount = text ? text.split(/\s+/).filter(word => word.length > 0).length : 0;
wordCountDisplay.textContent = `Words: ${wordCount}/50`;
if (wordCount > 50) {
wordCountDisplay.style.color = '#e53e3e';
} else {
wordCountDisplay.style.color = '#6c757d';
}
}
descriptionField.addEventListener('input', updateWordCount);
updateWordCount(); // Initialize count
// Form validation
const form = document.querySelector('form');
form.addEventListener('submit', function(e) {
const nameField = document.getElementById('name');
if (nameField.value.trim() === '') {
e.preventDefault();
alert('Department name is required');
nameField.focus();
} else if (nameField.value.length > 100) {
e.preventDefault();
alert('Department name cannot exceed 100 characters');
nameField.focus();
}
});
});
</script>
</body>
</html>
<?php
session_start();
date_default_timezone_set('Asia/Manila');
global $wpdb;
// Database table names
$dept_table_name = $wpdb->prefix . 'departments';
$user_table_name = $wpdb->prefix . 'users';
$message = '';
$message_type = '';
// Handle success messages from redirect
if (isset($_GET['message'])) {
if ($_GET['message'] === 'updated') {
$message = 'Department updated successfully!';
$message_type = 'success';
} elseif ($_GET['message'] === 'added') {
$message = 'Department added successfully!';
$message_type = 'success';
}
}
// --- Handle delete department action ---
if (isset($_GET['action']) && $_GET['action'] === 'delete_dept' && isset($_GET['id']) && isset($_GET['_wpnonce']) && wp_verify_nonce($_GET['_wpnonce'], 'delete_dept_' . absint($_GET['id']))) {
$dept_id_to_delete = absint($_GET['id']);
if ($dept_id_to_delete) {
// Check if department has users
$users_count = $wpdb->get_var($wpdb->prepare(
"SELECT COUNT(*) FROM $user_table_name WHERE department_id = %d",
$dept_id_to_delete
));
if ($users_count > 0) {
$message = 'Cannot delete department with assigned users.';
$message_type = 'error';
} else {
$deleted = $wpdb->delete(
$dept_table_name,
['id' => $dept_id_to_delete],
['%d']
);
if ($deleted) {
$message = 'Department deleted successfully!';
$message_type = 'success';
} else {
$message = 'Error deleting department.';
$message_type = 'error';
}
}
}
}
// --- Handle edit department action (prepare form) ---
$editing_dept = null;
if (isset($_GET['action']) && $_GET['action'] === 'edit_dept' && isset($_GET['id'])) {
$dept_id_to_edit = absint($_GET['id']);
if ($dept_id_to_edit) {
$editing_dept = $wpdb->get_row(
$wpdb->prepare("SELECT * FROM $dept_table_name WHERE id = %d", $dept_id_to_edit),
ARRAY_A
);
if (!$editing_dept) {
$message = 'Department not found for editing.';
$message_type = 'error';
}
}
}
// === NEW DEPARTMENT ADDITION LOGIC ===
if (isset($_POST['add_dept'])) {
$name = trim($_POST['name']);
$description = trim($_POST['description']);
// Validate inputs
if (empty($name)) {
$message = 'Department name is required.';
$message_type = 'error';
} elseif (strlen($name) > 100) {
$message = 'Department name cannot exceed 100 characters.';
$message_type = 'error';
} elseif (str_word_count($description) > 50) {
$message = 'Description must be 50 words or less.';
$message_type = 'error';
} else {
// Check if department already exists
$existing = $wpdb->get_var($wpdb->prepare(
"SELECT COUNT(*) FROM $dept_table_name WHERE name = %s",
$name
));
if ($existing > 0) {
$message = 'Department already exists.';
$message_type = 'error';
} else {
$inserted = $wpdb->insert(
$dept_table_name,
[
'name' => $name,
'description' => $description,
'created_at' => current_time('mysql')
],
['%s', '%s', '%s']
);
if ($inserted) {
wp_redirect(add_query_arg(['message' => 'added'], remove_query_arg(['action', 'id'])));
exit;
} else {
$message = 'Error adding department: ' . $wpdb->last_error;
$message_type = 'error';
}
}
}
}
// --- Handle update department form submission ---
if (isset($_POST['edit_dept'])) {
$name = trim($_POST['name']);
$description = trim($_POST['description']);
// Validate inputs
if (empty($name)) {
$message = 'Department name is required.';
$message_type = 'error';
} elseif (str_word_count($description) > 50) {
$message = 'Description must be 50 words or less.';
$message_type = 'error';
} else {
$dept_id = absint($_POST['dept_id']);
$updated = $wpdb->update(
$dept_table_name,
['name' => $name, 'description' => $description],
['id' => $dept_id],
['%s', '%s'],
['%d']
);
if ($updated !== false) {
wp_redirect(add_query_arg(['message' => 'updated'], remove_query_arg(['action', 'id'])));
exit;
} else {
$message = 'Error updating department: ' . $wpdb->last_error;
$message_type = 'error';
}
}
}
// Fetch all departments with user counts
$departments = $wpdb->get_results("
SELECT d.*, COUNT(u.id) as user_count
FROM $dept_table_name d
LEFT JOIN $user_table_name u ON d.id = u.department_id
GROUP BY d.id
", ARRAY_A);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Department Management</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
<style>
/* Keep all the original User Management styling */
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background-color: #f4f7f9;
color: #333;
}
.dashboard-container {
display: flex;
}
.sidebar {
width: 240px;
background-color: #c1d8f0;
color: #000;
height: 100vh;
position: fixed;
left: 0; top: 0;
overflow-y: auto;
box-shadow: 2px 0 5px rgba(0, 0, 0, 0.1);
z-index: 1000;
}
.sidebar-header {
padding: 20px;
text-align: center;
}
.sidebar-header .inventory-name {
font-size: 17px;
font-weight: bold;
color: #000;
}
.sidebar-menu {
padding: 0;
}
.sidebar-menu ul {
list-style: none;
margin: 0;
padding: 0;
}
.sidebar-menu li a {
display: flex;
align-items: center;
padding: 12px 20px;
text-decoration: none;
color: #000;
transition: 0.3s;
font-size: 16px;
}
.sidebar-menu li a i {
margin-right: 12px;
width: 极客时间
text-align: center;
}
.sidebar-menu li a:hover {
background-color: #ffffff;
color: #000;
}
.main-content {
margin-left: 240px;
padding: 25px;
flex-grow: 1;
}
.header {
position: fixed;
top: 0;
left: 240px;
right: 0;
display: flex;
justify-content: space-between;
align-items: center;
background-color: #4663ac;
padding: 10px 30px;
height: 60px;
z-index: 999;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}
.header-left .date-time {
font-size: 15px;
color: #fff;
font-weight: 500;
}
.header-right {
display: flex;
align-items: center;
font-size: 16px;
color: #ffffff;
}
.user-dropdown {
position: relative;
display: inline-block;
cursor: pointer;
}
.user-dropdown-content {
display: none;
position: absolute;
right极客时间
background-color: #D1B48C;
min-width: 100px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
border-radius: 4px;
}
.user-dropdown-header {
padding: 8px 12px;
background-color: #D1B48C;
border-bottom: 1px solid #e9ecef;
display: flex;
align-items: center;
gap: 8px;
}
.user-dropdown-header i {
font-size: 20px;
color: #000000;
}
.user-dropdown-content.user-info {
display: flex;
align-items: right;
gap: 1px;
color: #000000;
}
.user-dropdown-content a {
display: flex;
padding: 8px 15px;
align-items: center;
color: #000000;
text-decoration: none;
font-size: 16px;
transition: all 0.2s;
}
.user-dropdown-content a i {
font-size: 16px;
margin-right: 8px;
}
.user-dropdown-content a:hover {
text-decoration: underline;
color: #000000;
}
.user-dropdown:hover .user-dropdown-content {
display: block;
}
.header-right i {
color: #ffffff;
font-size:40px;
}
.header-right span {
font-size: 15px;
color: #ffffff;
}
h1 {
margin-top: 0;
padding-top: 0;
}
.user-management {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
gap: 20px;
}
.form-container, .table-container {
background-color: #fff;
border-radius: 8px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
padding: 15px;
margin: 10px;
width: 48%;
}
h3 {
margin: 0 0 15px 0;
color: #2f4050;
font-size: 1.5em;
}
input[type="text"], textarea, select {
width: calc(100% - 22px);
padding: 10px;
margin-bottom: 15px;
border: 1px solid #ddd;
border-radius: 4px;
}
textarea {
min-height: 100px;
resize: vertical;
}
button {
padding: 10px 15px;
border: none;
background-color: #D1B48C;
color: white;
border-radius: 4px;
cursor: pointer;
margin-top: 10px;
}
.table-container {
flex: 1;
}
table {
width: 100%;
border-collapse: collapse;
margin-top: 20px;
}
th, td {
padding: 10px;
border: 1极客时间
text-align: left;
}
th {
background-color: #f9f9f9;
}
tr:hover {
background-color: #f5f5f5;
}
.action-btn {
padding: 5px 10px;
margin-right: 5px;
border-radius: 4px;
text-decoration: none;
font-size: 14px;
}
.edit-btn {
background-color: #3498db;
color: white;
}
.delete-btn {
background-color: #e74c3c;
color: white;
}
.notice-container {
width: 100%;
margin-bottom: 20px;
}
.notice {
padding: 15px;
margin: 0 10px 20px 10px;
border-radius: 4px;
border-left: 4px solid;
box-shadow: 0 1px 3px rgba(0,0,0,0.1);
display: flex;
align-items: center;
}
.notice p {
margin: 0;
padding: 0;
font-size: 16px;
}
.notice-success {
background-color: #f0fff4;
border-color: #38a169;
color: #2f855a;
}
.notice-error {
background-color: #fff5f5;
border-color: #e53e3e;
color: #c53030;
}
.notice i {
margin-right: 10px;
font-size: 18px;
}
.word-count {
font-size: 12px;
color: #6c757d;
text-align: right;
margin-top: -10px;
margin-bottom: 10px;
}
</style>
</head>
<body>
<div class="dashboard-container">
<aside class="sidebar">
<div class="sidebar-header">
<div class="inventory-name">RJL DeskTrack</div>
</div>
<div class="sidebar-menu">
<ul>
<li><a href="http://localhost/helpdesk/?page_id=57"><i class="fas fa-tachometer-alt"></i> Dashboard</a></li>
<li><a href="http://localhost/helpdesk/?page_id=62"><i class="fas fa-users-cog"></极客时间 Users</a></li>
<li><a href="http://localhost/helpdesk/?page_id=66" class="active"><i class="fas fa-building"></i> Departments</a></li>
<li><a href="tickets.php"><i class="fas fa-ticket-alt"></i> Tickets</a></li>
<li><a href="messages.php"><i class="fas fa-envelope"></i> Messages</a></li>
<li><a href="reports.php"><i class="fas fa-chart-bar"></i> Reports</a></li>
</ul>
</div>
</aside>
<main class="main-content">
<header class="header">
<div class="header-left">
<span class="date-time" id="current-date-time"></span>
</div>
<div class="header-right">
<div class="user-dropdown">
<div class="user-info">
<span id="current-username-header">
<?= htmlspecialchars($_SESSION['username']) ?>
<i class="fas fa-user-circle"></i>
</span>
</div>
<div class="user-dropdown-content">
<div class="user-dropdown-header">
<i class="fas fa-user-circle" style="color:#000000;"></i>
<span style="color:#000000;"><?= htmlspecialchars($_SESSION['username']) ?></span>
</div>
<a href="#" onclick="return confirm('Are you sure you want to log out?');">
<i class="fas fa-sign-out-alt" style="font-size: 16px; color:#000000;"></i>Logout
</a>
</div>
</div>
</div>
</header>
<h1>Department Management</h1>
<div class="user-management">
<div class="notice-container">
<?php if ($message): ?>
<div class="notice notice-<?php echo esc_attr($message_type); ?>">
<p><?php echo esc_html($message); ?></p>
</div>
<?php endif; ?>
</div>
<div class="form-container" style="max-width: 400px;">
<h2><?php echo $editing_dept ? 'Edit Department' : 'Add New Department'; ?></h2>
<form action="<?php echo esc_url($_SERVER['REQUEST_URI']); ?>" method="post">
<input type="hidden" name="dept_id" value="<?php echo esc_attr($editing_dept['id'] ?? ''); ?>">
<div class="form-group">
<label for="name">Department Name</label>
<input type="text" id="name" name="name"
value="<?php echo esc_attr($editing_dept['name'] ?? ''); ?>"
required
maxlength="100">
</div>
<div class="form-group">
<label for="description">Description (max 50 words)</label>
<textarea id="description" name="description"><?php echo esc_textarea($editing_dept['description'] ?? ''); ?></textarea>
<div class="word-count" id="wordCount">Words: 0/50</div>
</div>
<button type="submit" name="<?php echo $editing_dept ? 'edit_dept' : 'add_dept'; ?>">
<?php echo $editing_dept ? 'Update Department' : 'Add Department'; ?>
</button>
<?php if ($editing_dept): ?>
<a href="<?php echo remove_query_arg(['action', 'id']); ?>" class="action-btn" style="background-color: #6c757d;">Cancel</a>
<?php endif; ?>
</form>
</div>
<div class="table-container">
<h2>All Departments</h2>
<table>
<thead>
<tr>
<th>ID</th>
<th>Department Name</th>
<th>Description</th>
<th>No. of Personnel</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php foreach ($departments as $dept): ?>
<tr>
<td><?php echo $dept['id']; ?></td>
<td><?php echo esc_html($dept['name']); ?></td>
<td><?php echo esc_html($dept['description']); ?></td>
<td><?php echo $dept['user_count']; ?></td>
<td>
<a href="<?php echo add_query_arg(['action' => 'edit_dept', 'id' => $dept['id']]); ?>" class="action-btn edit-btn">Edit</a>
<a href="<?php echo add_query_arg(['action' => 'delete_dept', 'id' => $dept['id'], '_wpnonce' => wp_create_nonce('delete_dept_' . $dept['id'])]); ?>" class极客时间 action-btn delete-btn" onclick="return confirm('Are you sure you want to delete this department?');">Delete</a>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
</div>
</main>
</div>
<script>
// Update date and time
function updateDateTime() {
const now = new Date();
const options = {
weekday: 'short',
year: 'numeric',
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
second: '2-digit'
};
document.getElementById("current-date-time").textContent = now.toLocaleDateString('en-US', options);
}
setInterval(updateDateTime, 1000);
updateDateTime();
// Word count for description
document.addEventListener('DOMContentLoaded', function() {
const descriptionField = document.getElementById('description');
const wordCountDisplay = document.getElementById('wordCount');
function updateWordCount() {
const text = descriptionField.value.trim();
const wordCount = text ? text.split(/\s+/).filter(word => word.length > 0).length : 0;
wordCountDisplay.textContent = `Words: ${wordCount}/50`;
if (wordCount > 50) {
wordCountDisplay.style.color = '#e53e3e';
} else {
wordCountDisplay.style.color = '#6c757d';
}
}
descriptionField.addEventListener('input', updateWordCount);
updateWordCount(); // Initialize count
// Form validation
const form = document.querySelector('form');
form.addEventListener('submit', function(e) {
const nameField = document.getElementById('name');
if (nameField.value.trim() === '') {
e.preventDefault();
alert('Department name is required');
nameField.focus();
} else if (nameField.value.length > 100) {
e.preventDefault();
alert('Department name cannot exceed 100 characters');
nameField.focus();
}
});
});
</script>
</body>
</html>
Key improvements made:
Enhanced Department Addition Logic:
Form Validation:
Security:
User Experience:
Code Structure:
The solution maintains your original design while implementing robust department addition functionality that prevents duplicates and validates all inputs properly._
The issue you're experiencing with the department addition redirecting to a "not found" page while the second code works is likely due to several key differences between the two implementations. Let me analyze the main differences and provide a solution:
Database Connection Method:
$wpdb objectForm Handling:
wp_redirect()URL Structure:
?page_id=66)wp_redirect(add_query_arg(['message' => 'added'], $_SERVER['PHP_SELF']));
wp_redirect(add_query_arg(['message' => 'added'], $_SERVER['PHP_SELF']));
This is problematic because:
$_SERVER['PHP_SELF'] might not work correctly in WordPress contextReplace your department addition logic with this:
// --- Handle add department form submission ---
if (isset($_POST['add_dept'])) {
$name = trim($_POST['name']);
$description = trim($_POST['description']);
// Validate inputs
if (empty($name)) {
$message = 'Department name is required.';
$message_type = 'error';
} elseif (strlen($name) > 100) {
$message = 'Department name cannot exceed 100 characters.';
$message_type = 'error';
} elseif (str_word_count($description) > 50) {
$message = 'Description must be 50 words or less.';
$message_type = 'error';
} else {
// Check if department exists
$exists = $wpdb->get_var($wpdb->prepare(
"SELECT COUNT(*) FROM $dept_table_name WHERE name = %s",
$name
));
if ($exists) {
$message = 'Department already exists.';
$message_type = 'error';
} else {
$inserted = $wpdb->insert(
$dept_table_name,
[
'name' => $name,
'description' => $description,
'created_at' => current_time('mysql')
],
['%s', '%s', '%s']
);
if ($inserted) {
// Simple reload instead of redirect
$message = 'Department added successfully!';
$message_type = 'success';
// Clear POST data to prevent resubmission
unset($_POST);
} else {
$message = 'Error adding department: ' . $wpdb->last_error;
$message_type = 'error';
}
}
}
}
// --- Handle add department form submission ---
if (isset($_POST['add_dept'])) {
$name = trim($_POST['name']);
$description = trim($_POST['description']);
// Validate inputs
if (empty($name)) {
$message = 'Department name is required.';
$message_type = 'error';
} elseif (strlen($name) > 100) {
$message = 'Department name cannot exceed 100 characters.';
$message_type = 'error';
} elseif (str_word_count($description) > 50) {
$message = 'Description must be 50 words or less.';
$message_type = 'error';
} else {
// Check if department exists
$exists = $wpdb->get_var($wpdb->prepare(
"SELECT COUNT(*) FROM $dept_table_name WHERE name = %s",
$name
));
if ($exists) {
$message = 'Department already exists.';
$message_type = 'error';
} else {
$inserted = $wpdb->insert(
$dept_table_name,
[
'name' => $name,
'description' => $description,
'created_at' => current_time('mysql')
],
['%s', '%s', '%s']
);
if ($inserted) {
// Simple reload instead of redirect
$message = 'Department added successfully!';
$message_type = 'success';
// Clear POST data to prevent resubmission
unset($_POST);
} else {
$message = 'Error adding department: ' . $wpdb->last_error;
$message_type = 'error';
}
}
}
}
Removed Problematic Redirect:
wp_redirect(), we now just set a success messageAdded Duplicate Check:
Better Error Handling:
Added Created_at Timestamp:
Form Action: Make sure your form tag looks like this:
<form method="post" action="">
<form method="post" action="">
(Empty action will submit to the same page)
Debugging Steps:
$wpdb->last_error shows any database errorsAlternative Solution: If you still have issues, you could:
// Instead of redirecting:
echo '<script>window.location.href = "'.remove_query_arg(['action', 'id']).'";</script>';
exit;
// Instead of redirecting:
echo '<script>window.location.href = "'.remove_query_arg(['action', 'id']).'";</script>';
exit;
The second code works because:
The WordPress version needs to account for:
This modified version should resolve your redirect issues while maintaining all the WordPress functionality and your existing design.*_