integready/yii2-intl-tel-input

Yii2 国际电话号码 - 资产包、行为、验证器、小部件

安装: 812

依赖: 0

建议: 0

安全: 0

星标: 0

关注者: 2

分支: 0

开放问题: 0

类型:yii2-extension

2.0.0.4 2019-10-23 12:47 UTC

This package is auto-updated.

Last update: 2024-09-24 00:00:23 UTC


README

本扩展使用了 2 个库

安装

安装此扩展的首选方式是通过 composer

运行以下命令之一:

$ php composer.phar require "integready/yii2-intl-tel-input" "~2.0.0"

或者将以下内容添加到您的 composer.json 文件的 require 部分:

"integready/yii2-intl-tel-input": "~2.0.0"

使用方法

作为具有顶部首选国家的 ActiveField 小部件使用

use integready\extensions\phoneInput\PhoneInput;

echo $form->field($model, 'phone_number')->widget(PhoneInput::class, [
    'jsOptions' => [
        'preferredCountries' => ['no', 'pl', 'ua'],
    ]
]);

作为具有有限国家列表的简单小部件使用

use integready\extensions\phoneInput\PhoneInput;

echo PhoneInput::widget([
    'name' => 'phone_number',
    'jsOptions' => [
        'allowExtensions' => true,
        'onlyCountries' => ['no', 'pl', 'ua'],
    ]
]);

在模型中使用电话验证器(验证正确的国家代码和电话格式)

namespace frontend\models;

use integready\extensions\phoneInput\PhoneInputValidator;

class Company extends Model
{
    public $phone;

    public function rules()
    {
        return [
            [['phone'], 'string'],
            [['phone'], PhoneInputValidator::class],
        ];
    }
}

或者如果您需要验证某些国家的电话号码

namespace frontend\models;

use integready\extensions\phoneInput\PhoneInputValidator;

class Company extends Model
{
    public $phone;

    public function rules()
    {
        return [
            [['phone'], 'string'],
            // [['phone'], PhoneInputValidator::className(), 'region' => 'UA'],
            [['phone'], PhoneInputValidator::className(), 'region' => ['PL', 'UA']],
        ];
    }
}

在模型中使用电话行为(自动将电话字符串格式化为所需的格式)

namespace frontend\models;

use integready\extensions\phoneInput\PhoneInputBehavior;

class Company extends Model
{
    public $phone;

    public function behaviors()
    {
        return [
            'phoneInput' => PhoneInputBehavior::class,
        ];
    }
}

您还可以利用此行为将电话号码的国家代码保存到数据库中。只需将您的属性添加为 countryCodeAttribute,它将与电话号码一起插入到数据库中。

namespace frontend\models;

use integready\extensions\phoneInput\PhoneInputBehavior;

class Company extends Model
{
    public $phone;
    public $countryCode;

    public function behaviors()
    {
        return [
            [
                'class'                => PhoneInputBehavior::class,
                'countryCodeAttribute' => 'countryCode',
            ],
        ];
    }
}

注意:nationalMode 选项非常重要!如果您想管理带有国家/运营商代码的电话号码

  • 您必须在小部件选项中设置 nationalMode: false(例如,PhoneInput::widget(...options, ['jsOptions' => ['nationalMode' => false]]))。