How to Add a Custom ‘Add New’ Option in Dropdown with Auto Form Display

In this article, we are exploring how we can add Custom ‘Add New’ Option in Dropdown with auto form display as well as validation.

Check out the official docs of filament:

Form Fields

So, for this , we will have to create a dropdown field with the list of all the options. Furthermore, we will merge the new key value for “Add New” option in the dropdown. Here is the code for that:

Forms\Components\Select::make("category_id")
                                ->options(function(){
                                    $options = Category::pluck("name",'id')->toArray();
                                    return array_merge(['create_new' => "Add new Category"],$options);
                                })
                                ->dehydrated(function($state){
                                    return $state == "create_new";
                                })
                                ->reactive()
                                ->searchable()
                                ->required(),

So, in the above code, you can find we are listing all the categories and included one custom array of [‘create_new’ => “Add New Category”]. After that we will merge those arrays and return them.

Besides that, I am chaining dehydrated() method and validating if the current state is create_new. dehydrated() method protects the data from being sent when we are submitting the form.

Advertisements

Custom Text Input Field

Furthermore, we will add a new TextInput() field to enter the category name and validate it on the basis of our selected category_id.

Forms\Components\TextInput::make('new_category_name')
                                ->label(__("New Category Name"))
                                ->visible(function(callable $get){
                                    return $get('category_id') == "create_new";
                                })
                                ->requiredIf('category_id','create_new'),

So, in the above code, you can check that we are chaining two methods.

  1. visible(): When the category_id is selected to “create_new”, the field input will be visible.
  2. requiredIf(): Similarly, we are using requiredIf() to check if category_id is equal to “create_new” then the field is required.

So, in this way, we can create a dynamic form fields. But remember, we must need to control the saving process from our side. So, for that you can check out this article that gives you an idea on how to customize the saving process.

Advertisements

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top