如何在表单上自动添加id?

时间:2016-03-10 09:02:26

标签: laravel

手动添加ID看起来像这样

{!! Form::text('email', null, ['id' => 'email', 'class' => 'active']) !!}

如何自动添加ID?

使用宏的任何示例?

1 个答案:

答案 0 :(得分:0)

创建新的FromBuilder类:

class MyFormBuilder extends \Collective\Html\FormBuilder /** Original Form Builder*/{

    // Override the text function
    public function text($name, $value = null, $options = []){

        // If the ID is not explicitly defined in the call
        if(!isset($options['id'])){

            // Set ID equal to the name
            $options['id'] = $name;

        }

        // Call the original text function with the new ID set
        parent::text($name,$value,$options);
    }

}

然后创建一个新的服务提供商

<?php

namespace My\Provider\Space;

use Illuminate\Support\ServiceProvider;

class MyHtmlServiceProvider extends ServiceProvider
{

    /**
     * Indicates if loading of the provider is deferred.
     *
     * @var bool
     */
    protected $defer = true;

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->registerHtmlBuilder();

        $this->registerFormBuilder();

        $this->app->alias('html', 'Collective\Html\HtmlBuilder');
        $this->app->alias('form', 'My\Class\Space\MyFormBuilder');
    }

    /**
     * Register the HTML builder instance.
     *
     * @return void
     */
    protected function registerHtmlBuilder()
    {
        $this->app->singleton('html', function ($app) {
            return new \Collective\Html\HtmlBuilder($app['url'], $app['view']);
        });
    }

    /**
     * Register the form builder instance.
     *
     * @return void
     */
    protected function registerFormBuilder()
    {
        $this->app->singleton('form', function ($app) {
            $form = new \My\Class\Space\MyFormBuilder($app['html'], $app['url'], $app['view'], $app['session.store']->getToken());

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

    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides()
    {
        return ['html', 'form', 'Collective\Html\HtmlBuilder', 'My\Class\Space\FormBuilder'];
    }
}

然后更新您的config / app.php文件并执行:

  1. 从服务提供者数组中删除旧的\ Collective \ Html \ HtmlServiceProvider :: class
  2. 添加您的新服务提供商。
  3. 对此的基本解释:

    一个。您将HTML帮助程序的服务提供程序移动到您注册MyBuilder的服务提供程序

    B中。下次调用\ Form时,服务提供商会将其指向您的构建器。

    查看集合的供应商文件,以确保获得函数定义中的所有变量。

    只是过滤掉任何名称空间错误等,因为我还没有完全测试它们。