yjballestero/yii2-phone-input

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

dev-master 2024-06-12 16:07 UTC

This package is auto-updated.

Last update: 2024-09-12 16:45:55 UTC


README

Latest Stable Version Total Downloads Latest Unstable Version License Build Status

需求

此扩展使用

  • PHP 8.1+.
  • Yii2 2.0.45+

原始演示可以在以下链接找到 - http://jackocnr.com/intl-tel-input.html.

安装

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

运行以下命令之一

$ php composer.phar require "yjballestero/yii2-phone-input" "*"

或添加

"yjballestero/yii2-phone-input": "*"

到您的 composer.json 文件的 require 部分。

使用方法

Phone input

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

use yjballestero\phoneInput\PhoneInput;

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

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

use yjballestero\phoneInput\PhoneInput;

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

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

namespace frontend\models;

use yjballestero\phoneInput\PhoneInputValidator;

class Company extends Model
{
    public $phone;

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

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

namespace frontend\models;

use yjballestero\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 yjballestero\phoneInput\PhoneInputBehavior;

class Company extends Model
{
    public $phone;

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

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

namespace frontend\models;

use yjballestero\phoneInput\PhoneInputBehavior;

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

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

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

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