在Laravel Form selectRange中追加/预附加文本

时间:2015-09-26 18:16:20

标签: laravel

在Laravel中生成selectRange时,是否可以在选择选项标签中附加或预先附加文本?例如,就像%符号一样,所有标签都会显示为{number}%

{!! Form::selectRange('number', 1, 99) !!}

1 个答案:

答案 0 :(得分:0)

Laravel Collective核心中没有这样的东西。我创建了自己的实用程序类,它扩展了Laravel Collective表单构建器。

在您的刀片中,您只需写下:

{!! MyCustomForm::selectRange('number', 1, 99, ' %') !!}

这是我的自定义类,它扩展自Laravel Collectives Form构建器:

<?php

namespace App\Models\Utilities;

use Collective\Html\FormFacade;

class MyCustomForm extends FormFacade
{
    /**
     * Create a select range field with appending text.
     * This function overrides Laravel Collective Form::selectRange()
     * function.
     *
     * @param   string  $name
     * @param   string  $begin
     * @param   string  $end
     * @param   string  $appended_text
     * @param   string  $selected
     * @param   array   $options
     * @return  string
     */
    public static function selectRange($name, $begin, $end, $appended_text = null, $selected = null, $options = array()){
        $html = parent::selectRange($name, $begin, $end, $selected, $options);

        $dom = new \DOMDocument();
        $dom->loadHTML($html);
        $xpath = new \DOMXPath($dom);
        $options = $xpath->query("*/select[@name='" . $name . "']/option");

        foreach ($options as $option) {
            $option->nodeValue = $option->nodeValue . $appended_text;
        }

        $html = self::innerHTML($dom->documentElement->firstChild);
        return $html;
    }

    /**
     * This function removes HTML DOCTYPE, html tag and body tag from the
     * generated DOM HTML.
     *
     * @param  DOMNode  $node
     * @return string
     */
    public static function innerHTML($node){
        $doc = new \DOMDocument();
        foreach ($node->childNodes as $child)
            $doc->appendChild($doc->importNode($child, true));

        return $doc->saveHTML();
    }
}

让我知道是否还有一些模糊的东西。