borales / yii2-phone-input
Yii2 国际电话号码 - 资产包,行为,验证器,小部件
0.3.0
2019-10-06 17:45 UTC
Requires
- bower-asset/intl-tel-input: ^16
- giggsey/libphonenumber-for-php: ^8
- yiisoft/yii2: >=2.0.1
README
此扩展使用了 2 个库
原始演示可在此处找到 - http://jackocnr.com/intl-tel-input.html.
安装
安装此扩展的最佳方式是通过 composer.
运行以下命令之一
$ php composer.phar require "borales/yii2-phone-input" "*"
或在您的 composer.json
文件的 require
部分添加以下内容
"borales/yii2-phone-input": "*"
to the require
section of your composer.json
file.
使用方法
作为带有首选国家的 ActiveField
小部件使用
use borales\extensions\phoneInput\PhoneInput; echo $form->field($model, 'phone_number')->widget(PhoneInput::className(), [ 'jsOptions' => [ 'preferredCountries' => ['no', 'pl', 'ua'], ] ]);
作为具有有限国家列表的简单小部件使用
use borales\extensions\phoneInput\PhoneInput; echo PhoneInput::widget([ 'name' => 'phone_number', 'jsOptions' => [ 'allowExtensions' => true, 'onlyCountries' => ['no', 'pl', 'ua'], ] ]);
在模型中使用电话验证器(验证正确的国家代码和电话格式)
namespace frontend\models; use borales\extensions\phoneInput\PhoneInputValidator; class Company extends Model { public $phone; public function rules() { return [ [['phone'], 'string'], [['phone'], PhoneInputValidator::className()], ]; } }
或者如果您需要验证某些国家的电话号码
namespace frontend\models; use borales\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 borales\extensions\phoneInput\PhoneInputBehavior; class Company extends Model { public $phone; public function behaviors() { return [ 'phoneInput' => PhoneInputBehavior::className(), ]; } }
您还可以利用此行为将电话号码的国家代码保存到数据库中。只需将您的属性添加为 countryCodeAttribute
,它将与电话号码一起插入到数据库中。
namespace frontend\models; use borales\extensions\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]])
)。