MaskedInput.php 6.59 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13
<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace yii\widgets;

use yii\base\InvalidConfigException;
use yii\helpers\Html;
use yii\helpers\Json;
use yii\web\JsExpression;
14
use yii\web\View;
15 16 17 18

/**
 * MaskedInput generates a masked text input.
 *
19 20
 * MaskedInput is similar to [[Html::textInput()]] except that an input mask will be used to force users to enter
 * properly formatted data, such as phone numbers, social security numbers.
21
 *
22 23
 * To use MaskedInput, you must set the [[mask]] property. The following example
 * shows how to use MaskedInput to collect phone numbers:
24
 *
25
 * ```php
Alexander Makarov committed
26
 * echo MaskedInput::widget([
27 28
 *     'name' => 'phone',
 *     'mask' => '999-999-9999',
Alexander Makarov committed
29
 * ]);
30
 * ```
31
 *
32
 * The masked text field is implemented based on the
33
 * [jQuery input masked plugin](https://github.com/RobinHerbots/jquery.inputmask).
34
 *
35
 * @author Kartik Visweswaran <kartikv2@gmail.com>
36 37 38 39
 * @since 2.0
 */
class MaskedInput extends InputWidget
{
40 41 42
    /**
     * The name of the jQuery plugin to use for this widget.
     */
43 44
    const PLUGIN_NAME = 'inputmask';

45
    /**
46 47
     * @var string|array|JsExpression the input mask (e.g. '99/99/9999' for date input). The following characters
     * can be used in the mask and are predefined:
48 49 50 51
     *
     * - `a`: represents an alpha character (A-Z, a-z)
     * - `9`: represents a numeric character (0-9)
     * - `*`: represents an alphanumeric character (A-Z, a-z, 0-9)
52
     * - `[` and `]`: anything entered between the square brackets is considered optional user input. This is
53
     *   based on the `optionalmarker` setting in [[clientOptions]].
54
     *
55
     * Additional definitions can be set through the [[definitions]] property.
56 57 58
     */
    public $mask;
    /**
59 60 61 62 63
     * @var array custom mask definitions to use. Should be configured as `maskSymbol => settings`, where
     *
     * - `maskSymbol` is a string, containing a character to identify your mask definition and
     * - `settings` is an array, consisiting of the following entries:
     *   - `validator`: string, a JS regular expression or a JS function.
64 65 66
     *   - `cardinality`: int, specifies how many characters are represented and validated for the definition.
     *   - `prevalidator`: array, validate the characters before the definition cardinality is reached.
     *   - `definitionSymbol`: string, allows shifting values from other definitions, with this `definitionSymbol`.
67
     */
68
    public $definitions;
69
    /**
70 71 72 73
     * @var array custom aliases to use. Should be configured as `maskAlias => settings`, where
     *
     * - `maskAlias` is a string containing a text to identify your mask alias definition (e.g. 'phone') and
     * - `settings` is an array containing settings for the mask symbol, exactly similar to parameters as passed in [[clientOptions]].
74
     */
75
    public $aliases;
76
    /**
77 78
     * @var array the JQuery plugin options for the input mask plugin.
     * @see https://github.com/RobinHerbots/jquery.inputmask
79
     */
80
    public $clientOptions = [];
81 82 83 84 85
    /**
     * @var array the HTML attributes for the input tag.
     * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
     */
    public $options = ['class' => 'form-control'];
86

87 88 89 90 91
    /**
     * @var string the hashed variable to store the pluginOptions
     */
    protected $_hashVar;

92

93 94
    /**
     * Initializes the widget.
95
     *
96 97 98 99 100
     * @throws InvalidConfigException if the "mask" property is not set.
     */
    public function init()
    {
        parent::init();
101 102
        if (empty($this->mask) && empty($this->clientOptions['alias'])) {
            throw new InvalidConfigException("Either the 'mask' property or the 'clientOptions[\"alias\"]' property must be set.");
103 104
        }
    }
105

106
    /**
107
     * @inheritdoc
108 109 110 111 112 113 114 115 116 117
     */
    public function run()
    {
        if ($this->hasModel()) {
            echo Html::activeTextInput($this->model, $this->attribute, $this->options);
        } else {
            echo Html::textInput($this->name, $this->value, $this->options);
        }
        $this->registerClientScript();
    }
118

119
    /**
120 121 122
     * Generates a hashed variable to store the plugin `clientOptions`. Helps in reusing the variable for similar
     * options passed for other widgets on the same page. The following special data attributes will also be
     * setup for the input widget, that can be accessed through javascript:
123
     *
124 125 126 127
     * - 'data-plugin-options' will store the hashed variable storing the plugin options.
     * - 'data-plugin-name' the name of the plugin
     *
     * @param View $view the view instance
128
     * @author [Thiago Talma](https://github.com/thiagotalma)
129
     */
130
    protected function hashPluginOptions($view)
131
    {
132 133 134 135 136
        $encOptions = empty($this->clientOptions) ? '{}' : Json::encode($this->clientOptions);
        $this->_hashVar = self::PLUGIN_NAME . '_' . hash('crc32', $encOptions);
        $this->options['data-plugin-name'] = self::PLUGIN_NAME;
        $this->options['data-plugin-options'] = $this->_hashVar;
        $view->registerJs("var {$this->_hashVar} = {$encOptions};\n", View::POS_HEAD);
137
    }
138

139
    /**
140
     * Initializes client options
141
     */
142
    protected function initClientOptions()
143
    {
144 145 146 147 148 149
        $options = $this->clientOptions;
        foreach ($options as $key => $value) {
            if (in_array($key, ['oncomplete', 'onincomplete', 'oncleared', 'onKeyUp', 'onKeyDown', 'onBeforeMask',
                    'onBeforePaste', 'onUnMask', 'isComplete', 'determineActiveMasksetIndex']) && !$value instanceof JsExpression
            ) {
                $options[$key] = new JsExpression($value);
150 151
            }
        }
152 153
        $this->clientOptions = $options;
    }
154

155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
    /**
     * Registers the needed client script and options.
     */
    public function registerClientScript()
    {
        $js = '';
        $view = $this->getView();
        $this->initClientOptions();
        if (!empty($this->mask)) {
            $this->clientOptions['mask'] = $this->mask;
        }
        $this->hashPluginOptions($view);
        if (is_array($this->definitions) && !empty($this->definitions)) {
            $js .= '$.extend($.' . self::PLUGIN_NAME . '.defaults.definitions, ' . Json::encode($this->definitions) . ");\n";
        }
        if (is_array($this->aliases) && !empty($this->aliases)) {
            $js .= '$.extend($.' . self::PLUGIN_NAME . '.defaults.aliases, ' . Json::encode($this->aliases) . ");\n";
        }
        $id = $this->options['id'];
        $js .= '$("#' . $id . '").' . self::PLUGIN_NAME . "(" . $this->_hashVar . ");\n";
        MaskedInputAsset::register($view);
        $view->registerJs($js);
177
    }
178
}