Skip to content

Commit 7a38c7e

Browse files
committed
always focus on error field
1 parent aeea538 commit 7a38c7e

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

src/app/View/Components/Dataform.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ class Dataform extends Component
1717
* @param string $operation The operation to use (create, update, etc.)
1818
* @param string|null $action Custom form action URL
1919
* @param string $method Form method (post, put, etc.)
20+
* @param bool $focusOnFirstField Whether to focus on the first field when form loads
2021
*/
2122
public function __construct(
2223
public string $controller,

src/resources/views/crud/form_content.blade.php

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -234,6 +234,9 @@ function preventUnload(event) {
234234
235235
// Only display errors if this is the form that was submitted
236236
if (submittedFormId && submittedFormId === currentFormId) {
237+
var firstErrorField = null;
238+
var firstErrorTab = null;
239+
237240
$.each(errors, function(bag, errorMessages){
238241
$.each(errorMessages, function (inputName, messages) {
239242
var normalizedProperty = inputName.split('.').map(function(item, index){
@@ -246,6 +249,17 @@ function preventUnload(event) {
246249
$('#' + currentFormId + ' [name="' + normalizedProperty + '"]'),
247250
container = field.closest('.form-group');
248251
252+
// Store the first error field for focusing
253+
if (firstErrorField === null && field.length > 0) {
254+
firstErrorField = field.first();
255+
@if ($crud->tabsEnabled())
256+
var tab_container = $(container).closest('[role="tabpanel"]');
257+
if (tab_container.length) {
258+
firstErrorTab = tab_container.attr('id');
259+
}
260+
@endif
261+
}
262+
249263
// iterate the inputs to add invalid classes to fields and red text to the field container.
250264
container.find('input, textarea, select').each(function() {
251265
let containerField = $(this);
@@ -278,6 +292,28 @@ function preventUnload(event) {
278292
});
279293
});
280294
});
295+
296+
// Focus on the first error field
297+
if (firstErrorField !== null) {
298+
@if ($crud->tabsEnabled())
299+
// Switch to the tab containing the first error if needed
300+
if (firstErrorTab) {
301+
$('.nav a[href="#' + firstErrorTab + '"]').tab('show');
302+
}
303+
@endif
304+
305+
// Focus on the first error field
306+
setTimeout(function() {
307+
const fieldOffset = firstErrorField.offset().top;
308+
const scrollTolerance = $(window).height() / 2;
309+
310+
triggerFocusOnFirstInputField(firstErrorField);
311+
312+
if (fieldOffset > scrollTolerance) {
313+
$('html, body').animate({scrollTop: (fieldOffset - 30)});
314+
}
315+
}, 100);
316+
}
281317
}
282318
@endif
283319

0 commit comments

Comments
 (0)