Last chapter ended with a challenge: our file and image fields are required, so when you edit a book, EasyAdmin complains they’re empty, even though the files exist. This is a classic EasyAdmin gotcha. Let’s fix it properly, then clean up the admin’s styling with a custom CSS file.

Why It Happens

On the edit page, an upload field doesn’t know that a file is already stored for this entity. If it’s marked as required, the form expects a new file every time.

What we want:

  • Required when creating a book
  • Optional when editing one, without losing the existing file

Using $pageName

configureFields() receives the current page as $pageName. Dump it on the create page and you’ll see new; on the edit page, edit. That’s all we need. Instead of setRequired(true), we make it depend on the page:

FileField::new('bookFileName', 'Livre')
    // ... upload options ...
    ->setRequired($pageName === Crud::PAGE_NEW),

ImageField::new('coverImageName', 'Couverture')
    // ... upload options ...
    ->setRequired($pageName === Crud::PAGE_NEW),

Test it: both fields are required on the create page, and optional on the edit page. Change the title, save, and the book keeps its PDF and its cover.

Cleaning Up the Error Style

Now try uploading a file that’s too big. The error message appears, which is good, but the whole fieldset gets a red border that doesn’t look great.

Inspect the page to find the class: form-fieldset has-fieldset-error. Then create public/custom.css:

.form-fieldset.has-fieldset-error {
    border: none;
    box-shadow: none;
}

Loading CSS in EasyAdmin: configureAssets()

EasyAdmin doesn’t use our base.html.twig, so we add the file through the dashboard. In DashboardController, override configureAssets():

public function configureAssets(): Assets
{
    return Assets::new()->addCssFile('custom.css');
}

The path is relative to public/. Test again with a large file: the error message is still there, without the red border.

Need JavaScript too? Use addJsFile() the same way: Assets::new()->addJsFile('admin.js').

Recap

  • $pageName === Crud::PAGE_NEW makes upload fields required only on creation
  • Global admin styles go in a CSS file in public/
  • configureAssets() with addCssFile() or addJsFile() loads them in EasyAdmin

Exercise · A bit of JavaScript

Create a public/admin.js file that prints “Admin loaded” in the browser console, and load it across the whole admin.

Show the solution
// public/admin.js
console.log('Admin loaded');
public function configureAssets(): Assets
{
    return Assets::new()
        ->addCssFile('custom.css')
        ->addJsFile('admin.js');
}

Open the browser console (F12) on any admin page: the message shows up.


This is Chapter 12 of the Mini Library course. Follow along to build a complete Symfony 8 + EasyAdmin digital library application from scratch.