Update Record with User Input
Custom Button: Update Record with User Input
This tutorial explains how to use the template_updaterecord_userinput.php script. This template allows you to create a custom button that prompts the user for input and then uses that input to modify the current record.
Use Case Example
Imagine you have a "Tasks" table and you want a button to "Add a Note". When clicked, a dialog should appear asking for the note text. After the user enters the text and clicks "OK", the note should be appended to the task's description field.
How It Works: The Flow
The script combines a client-side JavaScript dialog with a server-side PHP handler in a single file. This approach is efficient because it doesn't require a separate API endpoint.
1. Trigger
User clicks the custom button on the record edit page.
2. Dialog
A JavaScript modal appears, asking for input.
3. POST Request
The user's input is sent back to the same PHP script via a POST request.
4. Update
The PHP script validates permissions and updates the database record.
5. Feedback
A success message is shown, and the page reloads to display the changes.
Code Breakdown
The JavaScript code is responsible for displaying the dialog and handling the user's response.
// Step 1: Show the initial dialog with an input field.
showDialog({
title: 'Change Short Name',
text: `
<p>Please enter the text to append to the short name:</p>
<input type="text" id="userInputForTest" class="form-control" placeholder="Your text...">
`,
okText: 'Apply Value',
cancelText: 'Cancel'
}).then(confirmed => {
if (confirmed) {
const userInput = document.getElementById('userInputForTest').value;
if (userInput) {
// If the user entered something, start the update process.
updateRecord(userInput);
} else {
showErrorDialog('Please enter a value.');
}
}
});
- The
showDialog()function (fromdialog.js) is called to create the modal. - The
textproperty contains the HTML for the dialog's body, including the<input>field. This is where you customize the prompt for the user. - If the user clicks "OK", we get the value from the input field and call the
updateRecord()function.
The updateRecord() Function
async function updateRecord(userInput) {
// The URL is the script itself, which now handles the POST request.
const updateUrl = '<?= $_SERVER['PHP_SELF'] ?>?table_id=...';
try {
const formData = new FormData();
formData.append('user_input', userInput);
formData.append('csrf_token', '<?= generate_csrf_token() ?>');
const response = await fetch(updateUrl, {
method: 'POST',
body: formData
});
const result = await response.json();
if (!response.ok || !result.success) {
throw new Error(result.error?.message || result.message);
}
showSuccessDialog();
} catch (error) {
showErrorDialog(error.message);
}
}
- This function sends the
userInputto the server. - It uses
FormDatato package the input and the required CSRF token. - The request is sent as a
POSTto the script's own URL. - It expects a JSON response from the server and shows a final success or error dialog.
The PHP code at the top of the file detects if the request is a POST. If so, it acts as a mini-API endpoint to perform the update.
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
check_csrf_token();
$user_input = trim($_POST['user_input'] ?? '');
// ... permission checks ...
// --- Fetch and update data ---
$record = DBGet($physical_table_name, $record_id);
if (!array_key_exists('kurzname', $record)) {
api_error_response(400, 'FIELD_NOT_FOUND', "The field 'kurzname' does not exist.");
}
// THIS IS THE CORE LOGIC TO CUSTOMIZE:
$updated_value = ($record['kurzname'] ?? '') . ' ' . $user_input;
// --- Perform the update in the database ---
$affected_rows = DBUpdate(
$physical_table_name,
['kurzname'], // The field to update
[$updated_value], // The new value
$record_id,
$record['version'] ?? 1 // Optimistic locking
);
// ... handle success or error and send JSON response ...
exit();
}
- The
if ($_SERVER['REQUEST_METHOD'] === 'POST')block is the entry point for the update logic. - It securely retrieves the
user_inputfrom the POST data. - It performs all necessary permission checks to ensure the current user is allowed to edit the record.
- Important The line
$updated_value = ...is where you define how the record should be changed. You must adapt the field name (e.g., from'kurzname'to'description') and the logic to your specific needs. DBUpdateis used to save the changes. It includes the record'sversionto prevent conflicts if another user has modified the record in the meantime (optimistic locking).- Finally, it sends a JSON response back to the JavaScript part and stops execution with
exit().