Flag of Ukraine
SymfonyCasts stands united with the people of Ukraine
This tutorial has a new version, check it out!

Form Field Customization

Keep on Learning!

If you liked what you've learned so far, dive in!
Subscribe to get access to this tutorial plus
video, code and script downloads.

Start your All-Access Pass
Buy just this tutorial for $8.00

With a Subscription, click any sentence in the script to jump to that part of the video!

Login Subscribe

We can pretty much do anything to the list page. But we have totally ignored the two most important views: edit and new. Basically, we've ignored all the forms!

Ok, the edit and new views have some of the same configuration as list and search... like title and help. They also both have a fields key... but it's quite different than fields under edit and new.

Start simple: for Genus, I want to control which fields are shown on the form: I don't want to show every field. But instead of adding an edit or new key, add form, fields below that, and the fields we want: id, name, speciesCount, funFact, isPublished, firstDiscoveredAt, subFamily and genusScientists:

... lines 1 - 80
easy_admin:
... lines 82 - 91
entities:
Genus:
... lines 94 - 114
form:
fields:
- id
- name
- speciesCount
- funFact
- isPublished
- firstDiscoveredAt
- subFamily
- genusScientists
... lines 125 - 133

Before we talk about this, try it! Yes! Behind the scenes, EasyAdminBundle uses Symfony's form system... it just creates a normal form object by using our config. Right now, it's adding these 8 fields with no special config. Then, the form system is guessing which field types to use.

That's great... but why did we put fields under form, instead of edit or new? Where the heck did form come from? First, there is not a form view. But, since edit and new are so similar, EasyAdminBundle allows us to configure a "fake" view called form. Any config under form will automatically be used for new and edit. Then, you can keep customizing. Under new and fields, we can remove the id field with -id:

... lines 1 - 80
easy_admin:
... lines 82 - 91
entities:
Genus:
... lines 94 - 114
form:
... lines 116 - 124
new:
fields:
- '-id'
... lines 128 - 133

And under edit, to include the slug field - which is not under form, just add slug:

... lines 1 - 80
easy_admin:
... lines 82 - 91
entities:
Genus:
... lines 94 - 114
form:
... lines 116 - 124
new:
fields:
- '-id'
edit:
fields:
- slug
... lines 131 - 133

Ok, refresh the edit page. Yep! Now we have a slug field... but it's all the way at the bottom. This is because the fields from form are added first, and then any edit fields are added. We'll fix the order later.

And the new view does not have id.

Customizing Field Types, Options

Go back into the EasyAdminBundle profiler. Under new and then fields, we can see each field and its fieldType. That corresponds to the Symfony form type that's being used for this field. Open up Symfony's form documentation and scroll down to the built-in fields list.

Yes, we know these: TextType, TextareaType, EntityType, etc. When you use these in a normal form class, you reference them by their full class name - like EntityType::class. EasyAdminBundle re-uses these form types... but lets us use a shorter string name... like just entity.

The most important way to customize a field is to change its type. For example, see funFact? It's just a text field... but sometimes, fun facts are so fun... a mere text box cannot contain them. No problem. Just like we did under list, we can expand each field: set property: funFact, then type: textarea:

... lines 1 - 80
easy_admin:
... lines 82 - 91
entities:
Genus:
... lines 94 - 114
form:
fields:
... lines 117 - 121
- { property: 'funFact', type: 'textarea' }
... lines 123 - 138

You can picture what this is doing internally: EasyAdminBundle now calls $builder->add('funFact', TextareaType::class).

It even works! From working with forms, we also know that $builder->add() has a third argument: an options array. And yep, those are added here too. One normal form option is called disabled. Let's use that on the id field. Change it to use the expanded configuration - I'll even get fancy with multiple lines. Then, add type_options set to an array with disabled: true:

... lines 1 - 80
easy_admin:
... lines 82 - 91
entities:
Genus:
... lines 94 - 114
form:
fields:
-
property: id
type_options: {disabled: true}
... lines 120 - 138

Do the same thing below on the slug field. Oh, and EasyAdminBundle also has one special config key called help: Unique auto-generated value:

... lines 1 - 80
easy_admin:
... lines 82 - 91
entities:
Genus:
... lines 94 - 129
edit:
fields:
-
property: 'slug'
help: 'unique auto-generated value'
type_options: { disabled: true }
... lines 136 - 138

Find your browser and go edit a genus. Yea... id is disabled... and so is slug. And, we have a super cool help message below!

The cool thing about EasyAdminBundle is that if you're comfortable with the form system... well... there's not much new to learn. You're simply customizing your form fields in YAML instead of in PHP.

For example, the firstDiscoveredAt field is a DateType. And that means, under type_options, we could set widget to single_text to render that in one text field:

... lines 1 - 80
easy_admin:
... lines 82 - 91
entities:
Genus:
... lines 94 - 114
form:
fields:
... lines 117 - 123
- { property: 'firstDiscoveredAt', type_options: { widget: 'single_text' }}
... lines 125 - 138

If your browser supports it, you'll see a cute calendar widget.

Leave a comment!

10
Login or Register to join the conversation
Hans J. Avatar
Hans J. Avatar Hans J. | posted 3 years ago | edited

Hi,

I'am trying the use the DateTimeFiled in easyAdmin 3.0.2 bit i'am confused. This is my config for this Field in PostCrudController under configureFields method:

`

DateTimeField::new('publishedAt')
->setFormTypeOption(['widget' => 'single_text'])
->setFormat('dd-MM-yyyy HH:mm')
->setCssClass('datepicker')

`

But I get the following error in the frontend:

Argument 1 passed to EasyCorp\Bundle\EasyAdminBundle\Field\DateTimeField::setFormTypeOption() must be of the type string, array given, called in /Users/jonkerh/Sites/my_project/src/Controller/Admin/PostCrudController.php on line 32

Reply

Hey @Hans!

Use setFormTypeOptions with an "s" at the end :). There IS a method called setFormTypeOption(), but it accepts 2 arguments: the option and the value: https://github.com/EasyCorp/EasyAdminBundle/blob/31ff2d884ec6c05c8ddb4186e0eced2b907af8db/src/Field/FieldTrait.php#L95

Cheers!

Reply
Hans J. Avatar

Thanks!!

Reply
Brent Avatar
Brent Avatar Brent | posted 3 years ago | edited

Hi,

I am trying to add set a value on a form field called user_id this field is required. The form is for creating a new user account. When I loaded up this form I see the user_id value which come from the user object of the logged in user. But, no matter what I seem to try I get a sql error on insert telling me that user_id is null in the values list. How can I accomplish this?

easy_admin.yml config for my UserAccount entity:

`
new:

title: 'Add %%entity_label%%'

fields:


  • { property: userid, label: 'User Id', type_options: { disabled: true } }

  • { property: accountnumber, label: 'Account Number' }

    #- '-userid'
    `
    I also have my own UserAccountController which is where I am trying to set the value for this user_id field in the form previously mentioned.

<br />protected function createNewUserAccountEntity()
<br />{
 <br />$userAccount = new UserAccount();

 <br />$userAccount->setUserId($this->getUser()->getId());

 <br />return $userAccount;
<br />}<br />
In my UserAccount entity my setUserId method looks like this:

`
public function setUserId($id): ?int

{

$this->userid = $id;


return $this->userid;

}

`

Thank you in advance for any help.

Reply

Hey Brent

I think you should set the userId in the preFlush action. I believe there is something in the middle of EasyAdmin workflow that is overriding your values

Cheers!

Reply
Dennis E. Avatar
Dennis E. Avatar Dennis E. | posted 5 years ago

Hi guys,

I'm trying to render a fileUpload field. But { property: images, type: file } does not work. How can I do this?

BR,
Dennis

Reply
Dennis E. Avatar

I've got it working.

- { property: 'images', type: 'file', type_options: { multiple: true } }

Now I'm going to figure out how to handle the files.

Reply

Hey Dennis,

Glad you got it working, well done! And thanks for sharing the solution with others. Let us know if you have further problems.

Cheers!

Reply
Default user avatar
Default user avatar Sebastian | posted 5 years ago

Heya everybody!,

First I like to say I love these tutorials. They do help me a lot to find my way through the Symfony-Jungle. <3
Still, I do have a question: I am using type: country for a field. I do want a placeholder as first entry like 'please choose'. Is this possible?

Kind regards

Reply

Hey Sebastian!

We are very happy to hear that you are liking our tutorials :)
About your question, there is a easy way to add a placeholder, just add this to your entity form config


// admin.yml
...
    form:
        fields:
            - { property: 'your_property', type_options: {placeholder: 'the placeholder!' }}

Cheers!

Reply
Cat in space

"Houston: no signs of life"
Start the conversation!

This tutorial is built on an older version of Symfony & EasyAdminBundle. Many of the concepts are the same, but you can expect major differences in newer versions.

What PHP libraries does this tutorial use?

// composer.json
{
    "require": {
        "php": ">=5.5.9",
        "symfony/symfony": "3.3.*", // v3.3.18
        "doctrine/orm": "^2.5", // v2.7.2
        "doctrine/doctrine-bundle": "^1.6", // 1.10.3
        "doctrine/doctrine-cache-bundle": "^1.2", // 1.3.5
        "symfony/swiftmailer-bundle": "^2.3", // v2.6.7
        "symfony/monolog-bundle": "^2.8", // v2.12.1
        "symfony/polyfill-apcu": "^1.0", // v1.17.0
        "sensio/distribution-bundle": "^5.0", // v5.0.25
        "sensio/framework-extra-bundle": "^3.0.2", // v3.0.29
        "incenteev/composer-parameter-handler": "^2.0", // v2.1.4
        "knplabs/knp-markdown-bundle": "^1.4", // 1.7.1
        "doctrine/doctrine-migrations-bundle": "^1.1", // v1.3.2
        "stof/doctrine-extensions-bundle": "^1.2", // v1.3.0
        "composer/package-versions-deprecated": "^1.11", // 1.11.99
        "javiereguiluz/easyadmin-bundle": "^1.16" // v1.17.21
    },
    "require-dev": {
        "sensio/generator-bundle": "^3.0", // v3.1.7
        "symfony/phpunit-bridge": "^3.0", // v3.4.40
        "nelmio/alice": "^2.1", // v2.3.5
        "doctrine/doctrine-fixtures-bundle": "^2.3" // v2.4.1
    }
}
userVoice