deshengk / yii2-phone-input
Yii2 国际电话号码 - 资产包、行为、验证器、小部件
1.0.11
2024-03-19 15:22 UTC
Requires
- giggsey/libphonenumber-for-php: ^8.0@dev
- jackocnr/intl-tel-input: dev-master
- yiisoft/yii2: >=2.0.1
README
本扩展使用了2个库
原始演示可在此处找到 - http://jackocnr.com/intl-tel-input.html。
安装
安装此扩展的首选方式是通过 composer。
运行以下命令
$ php composer.phar require "deshengk/yii2-phone-input" "*"
或添加以下内容到您的 composer.json
文件的 require
部分。
"deshengk/yii2-phone-input": "*"
使用方法
作为带有顶部首选国家的 ActiveField
小部件使用
use deshengk\extensions\phoneInput\PhoneInput; echo $form->field($model, 'phone_number')->widget(PhoneInput::className(), [ 'jsOptions' => [ 'preferredCountries' => ['no', 'pl', 'ua'], ] ]);
作为带有有限国家列表的简单小部件使用
use deshengk\extensions\phoneInput\PhoneInput; echo PhoneInput::widget([ 'name' => 'phone_number', 'jsOptions' => [ 'allowExtensions' => true, 'onlyCountries' => ['no', 'pl', 'ua'], ] ]);
在模型中使用电话验证器(验证正确的国家代码和电话格式)
namespace frontend\models; use deshengk\extensions\phoneInput\PhoneInputValidator; class Company extends Model { public $phone; public function rules() { return [ [['phone'], 'string'], [['phone'], PhoneInputValidator::className()], ]; } }
或者如果您需要验证某些国家的电话
namespace frontend\models; use deshengk\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 deshengk\extensions\phoneInput\PhoneInputBehavior; class Company extends Model { public $phone; public function behaviors() { return [ 'phoneInput' => PhoneInputBehavior::className(), ]; } }
您还可以利用此行为将电话号码的国家代码保存到数据库中。只需将您的属性添加为 countryCodeAttribute
,它将与电话号码一起插入到数据库中。
namespace frontend\models; use deshengk\extensions\phoneInput\PhoneInputBehavior; class Company extends Model { public $phone; public $countryCode; public function behaviors() { return [ [ 'class' => PhoneInputBehavior::className(), 'countryCodeAttribute' => 'countryCode', ], ]; } }
注意:
nationalMode
选项非常重要!如果您想要管理带有国家/运营商代码的电话号码
- 您必须将小部件选项中的
nationalMode: false
设置为nationalMode: false
(例如,PhoneInput::widget(...options, ['jsOptions' => ['nationalMode' => false]])
)。