简体   繁体   中英

Setting a global option for all forms in a Laravel application

I want all forms in my laravel application to have 'autocomplete' => 'off' by default, unless I specify 'autocomplete' => 'on'..

Since my application has many forms and laravel is such an awesome framework, I am wondering if I can set a global option of the form class to be always autocomplete off unless I specify the opposite.

Anyone know about this?

Yes, this is possible. The basic idea is that you need to extend two classes: the built in Illuminate\\Html\\FormBuilder and Illuminate\\Html\\HtmlServiceProvider classes, and replace the HtmlServiceProvider in app/config/app.php with the one you create.

First, create a MyForm class that is going to override the functionality you want from the FormBuilder :

use Illuminate\Html\FormBuilder;

class MyForm extends FormBuilder
{
    /**
     * Open up a new HTML form.
     *
     * @param  array   $options
     * @return string
     */
    public function open(array $options = array())
    {
        // If you haven't specified an autocomplete option, default it to 'off'
        if(!isset($options['autocomplete'])) {
            $options['autocomplete'] = 'off';
        }

        return parent::open($options);
    }
}

Next, you will need to create a service provider that extends from Illuminate\\Html\\HtmlServiceProvider and override the registerFormBuilder method:

use Illuminate\Html\HtmlServiceProvider;
use MyForm;

class FormServiceProvider extends HtmlServiceProvider
{
    public function registerFormBuilder()
    {
        $app = $this->app;
        // Taken From: Illuminate\Html\HtmlServiceProvider
        $app->bindShared('form', function($app) {
            // Replace FormBuilder with MyForm
            $form = new MyForm($app['html'], $app['url'], $app['session.store']->getToken());

            return $form->setSessionStore($app['session.store']);
        });
    }
}

Finally, you will need to replace 'Illuminate\\Html\\HtmlServiceProvider', in app/config/app.php with your new Service Provider. I have tested this on a local test Laravel 4.2 install and works without having to modify anything in the calls to Form::open

I was feeling lazy, so I just added the line $attributes['autocomplete'] = 'off'; to the file FormBuilder.php . I added it on line # 108 in the open function.

This is a good example of a hacky solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM