Yii2 : Display the phone mask as text - yii2

Tell me how to make the phone output in a readable way?
It is stored in the database as 1234567890, but you need to display the user - (123) 456-78-90.
I do not want to make a garden, obvio,usly there are already ready solutions.
In Controller
public function actionShowPhone()
{
$phone = "1234567890";
return $this->render('show-phone', ['phone' => $phone,]);
}
In View show-phone.php
<?= Html::encode($phone) ?>

Formatting phone numbers in Forms
If you are looking to format the phone number inside the ActiveForm you can use the \yii\widgets\MaskInput in the following way
<?=
$form->field($model, 'landline_phone')->widget(\yii\widgets\MaskedInput::className(), [
'mask' => '(999)-999-99-99'
]);
?>
or without ActiveForm
echo \yii\widgets\MaskedInput::widget([
'name' => 'phone',
'mask' => '(999)-999-99-99',
]);
Note: when saving the phone field you must save it as a number only in the database like 1234567890 so before you save you can use $this->landline_phone= preg_replace('/[^0-9]+/', '', $this->landline_phone); inside the beforeSave().
Formatting Phone Numbers as Text
Extending the \yii\i18n\Formatter
But if you want to print the phone number as text in the above format then a good way is to extend the yii\i18n\Formatter and create a custom component/helper in lets say common\components\ or app\components\ with the following code.
Note : change the namespace for the class accordingly
<?php
namespace common\components;
use yii\i18n\Formatter;
class FormatterHelper extends Formatter {
public function asPhone($value) {
return preg_replace("/^(\d{3})(\d{3})(\d{2})(\d{2})$/", "($1)-$2-$3-$4", $value);
}
}
and then in the common\config\main.php or app\config\web.php add the following under components.
'formatter' => [
'class' => '\common\components\FormatterHelper',
'locale' => 'en-US',
'dateFormat' => 'yyyy-MM-dd',
'datetimeFormat' => 'yyyy-MM-dd HH:mm:ss',
'decimalSeparator' => '.',
'thousandSeparator' => ',',
'currencyCode' => 'USD'
],
then you can use it like below
echo Yii::$app->formatter->asPhone('123456789')
and it will output the following as text
(123)-456-78-90
Using \yii\widgets\MaskedInputAssets
Another simplest and easiest way is to register the available MaskedInputAssets that uses RobinHerbots/Inputmask bundled and use javascript to mask the text
<?php
\yii\widgets\MaskedInputAsset::register($this);
$js = <<<SCRIPT
var selector = document.getElementById("mask");
var im = new Inputmask("(999)-999-99-99");
im.mask(selector);
SCRIPT;
// Register tooltip/popover initialization javascript
$this->registerJs ( $js , \yii\web\View::POS_READY);
?>
<div id="mask">
1234567890
</div>

Related

Yii2 ActiveForm TextField Number Max

I have fields like below
<?= $form->field($model, 'phone')
->textInput(['type' => 'number', 'maxlength' => 13])
->label('Phone')
?>
why the 'maxlength' is not work? and how to make it work?
thank you before
It will not work because you are using type=>number for your input field, you have to change it to type=>text.
<?= $form->field($model, 'phone')
->textInput(['type' => 'text', 'maxlength' => 13])
->label('Phone')
?>
Looking at your input it seems like you are doing it because you do not want the user to enter any other thing than numbers for the Phone field, Yii2 provides you a very nice way to accomplish this i.e yii\widgets\MaskedInput, you can format your input using the mask option to tell it how many digits to allow and in which sequence see the demos HERE
<?= $form->field($model, 'phone')->widget(\yii\widgets\MaskedInput::className(), [
'mask' => '999-999-9999',
]) ?>
apart from the solutions above, you can also have the option of validating this inside your model by using the custom validation option.
Your rule for phone inside your model should look like
[['phone'],'PhoneLimit']
public function PhoneLimit($attribute)
{
if (!preg_match('/^[0-9]{13}$/', $this->$attribute)) {
$this->addError($attribute, 'Please provide digits only no more than 13.');
}
}
try for type number -> 'type'=>'number', 'min' => 1, 'max' => 999

Yii2: How to format input number to currency es-AR?

I have a _form.php file with this field:
<?=
$form->field($model, 'price')
->textInput([
'class' => 'form-control',
'type' => 'number'
])
?>
The price has this format 1234.50. I would like to have the format es-AR, like this: 1234,50.
In the GridView of index.php I use this code and it works great so I would like to do the same in the _form but it is not working.
[
'attribute' => 'price',
'value' => function($myModel) {
$myFormat = new NumberFormatter("es-AR", NumberFormatter::CURRENCY);
return $myFormat->formatCurrency($myModel->price, "ARS");
},
]
There are 2 ways to do that:
Add extra class to the price field and use javascript to convert to format you want (remember to return it back on submit)
Create priceFormat() and use it on AfterFind event and remember to use priceUnFormat() to return to decimal on BeforeSave
Use:
$form->field($model, 'attr', ['inputOptions' => ['value' => Yii::$app->formatter->asDecimal($model->attr)]])

Yii2: Kartik Select2: Initial Value from Model Attribute

I have a Model who has a column (attribute) that stored a comma separated value of IDs.
For Example,
Movie has a column "Genre" that includes more than one genre, e.g.: 40,20,1,3
How can I use Select2 widget to show these values separated when 'multiple' => true
And how can I save them back into comma-separated value as a string. I want a solution that will allow for quick flexibility. I know you can implode and explode the string but seems too much.
Any help appreciated
If I remember correctly pass the default option as part of the $options configuration for the widget:
echo $form->field($model, 'model_attribute_name')->widget(Select2::className(), [
'data' => $data
'options' => [
'class' => 'form-control',
'placeholder' => 'Choose Option...',
'selected' => 40
],
'pluginOptions' => [
'allowClear' => true,
],
])->label('Select2 Form Field');
This is from memory for grain fo salt here. The documentation at http://demos.krajee.com/widget-details/select2 is not very specific about how to do this.
I don't believe you can do that. Select2 sends the data in post as an array, so you would still need to use implode before saving. What i would do instead is in your model class:
class MyModel extends \yii\db\ActiveRecord {
$public myArrayAttribute;
...
public function beforeSave($insert) {
if (parent::beforeSave($insert)) {
$this->myAttribute = implode(',', $this->myArrayAttribute);
return true;
}
return false;
}
public function afterFind() {
parent::afterFind();
$this->myArrayAttribute = explode(',', $this->myAttribute);
}
}
This way myArrayAttribute will hold the values from the comma separated field as an array. Of course you will need to add validation rules for it and use it instead of your other attribute in create and update forms.
if you're displaying a form with already populated fields, maybe you want to update an already existing object, and you want to display the already saved value for the Select2 field, use 'data' => [ 1 => 'Some value' ], where 1 is the value, associated to the value displayed in the form. You can retrieve stuff to put in data from DB beforehand.
Source: https://github.com/kartik-v/yii2-widget-select2/issues/37

Yii2 dropdown selected value

I want to show selected value in Yii2 dropdown,
$_GET Value:
$id = $_GET["cid"];
Drop down code
$form->field($model, 'userid')
->dropDownList(
[User::getUser()],
//[ArrayHelper::map(User::findAll(['active' => '1']), 'id', 'name')],
['prompt'=>'Select a user','id'=>'user_dropdown'],
['options' =>
[
$id => ['selected' => true]
]
]
)->label('');
but this method is not working!
Try this.
$model->userid=$id;
$form->field($model, 'userid')
->dropDownList(...)
->label('');
Basically, you affect the options (your <option> elements) by using the value attribute's actual value as the array key in the dropDownList options array.
So in this case I have an array of states and the value attributes have the state abbreviation, for example value="FL". I'm getting my selected state from the Address table, which stores the abbreviation, so all I have to do is use that as my array key in the options array:
echo $form->field($model, 'state')->dropDownList($listData, ['prompt'=>'Select...', 'options'=>[$address->state=>["Selected"=>true]]]);
The documentation spells it out: http://www.yiiframework.com/doc-2.0/yii-helpers-basehtml.html#dropDownList()-detail
i hope this will help you
$form->field($model, 'userid')
->dropDownList(
[User::getUser()],
//[ArrayHelper::map(User::find()->where('id' => $id)->all(), 'id', 'name')],
['prompt'=>'Select a user','id'=>'user_dropdown'],
['options' =>
[
$id => ['selected' => true]
]
]
)->label('');
$model->userid = $_GET['cid'];
$form->field($model, 'userid')
->dropDownList(
$items, //Flat array('id'=>'val')
['prompt'=>''] //options
)->label('');
<?php
$selectValue = $_GET['tid']
echo $form->field($model, 'tag_id')
->dropdownList(
ArrayHelper::map(Tag::find()->where(['visibility'=>'1'])->orderBy('value ASC')->all(), 'tag_id', 'value'),
['options' => [$selectValue => ['Selected'=>'selected']]],
['prompt' => '-- Select Tag --'])
->label(false);
?>
This code will Auto Select the selected value received as input.
Where $selectValue will be numeric value received from GET method.
Final output : <option value="14" selected="selected">NONE</option>
Ok, if you are using ActiveForm then value of your model field will be used as the selected value. With Html helper dropDownList function accepts another parameter selection doc. Example:
$id = $_GET["cid"];
\yii\helpers\Html::dropDownList('userid', $id, [ArrayHelper::map(User::findAll(['active' => '1']), 'id', 'name'), [......])
This is my S.O.L.I.D approach.
Controller
$model = new User();
$model->userid = $id; #this line does the magick. Make sure the $id has a value, so do the if else here.
return $this->return('view', compact('model'))
But, if you prefer the setter method. Do this...
# Model
class User extends ActiveRecord
{
public function setUserId(int $userId): void
{
$this->userid = $userId;
}
}
# Controller
$model = new User();
$model->setUserId($userId);
View (view is as-is)
$form->field($model, 'userid')
->dropDownList(...)
->label('');
Use this code below:
$category = \backend\models\ProductCategory::find()->WHERE(['deleted'=>'N'])->all();
$listData = ArrayHelper::map($category,'product_category_id','category_name');
echo $form->field($model, 'product_category_id')->dropDownList($listData,['prompt'=>'Select']);
All of the options I've added are unrequired.
What is written in the 'value' index is what dropdown item will be selected as default.
Prompt just displays a first option that doesn't have a value associated with it.
echo $form->field($model, 'model_attribute_name')
->dropDownList($associativeArrayValueToText,
[
'value'=> $valueIWantSelected,
'prompt' => 'What I want as a placeholder for first option',
'class' => 'classname'
]);
You'll find the function that assigns this in the following file:
vendor/yiisoft/yii2/helpers/BaseHtml.php
public static function renderSelectOptions($selection, $items, &$tagOptions = [])
Also from the function you can see that you can add an optgroup to your dropdown, you just need to supply a multidimensional array in where I've put $associativeArrayValueToText. This just means that you can split your options by introducing group headings to the dropdown.

How to change label text of the ActiveField?

I have created new Yii2 basic project and want to dig in.
There is a Username field on login page:
I want to change label 'Username' to a custom one, e.g. 'My superb label'.
I have read the manual:
http://www.yiiframework.com/doc-2.0/yii-widgets-activefield.html
After investigating a little I've got the next result:
I have changed only template and it has changed the layout:
<?= $form->field($model, 'username', [
"template" => "<label> My superb label </label>\n{input}\n{hint}\n{error}"
])?>
How to change the text of the label in a correct way?
What is best practice?
<?= $form->field($model, 'username')->textInput()->label('My superb label') ?>
http://www.yiiframework.com/doc-2.0/yii-bootstrap-activefield.html#label()-detail
there is an another cool way.
<?= $form->field($model, 'username')->textInput(['class'=>'field-class'])->label('Your Label',['class'=>'label-class']) ?>
Okay, just override attributeLabels in LoginForm.php:
/**
* Returns the attribute labels.
*
* See Model class for more details
*
* #return array attribute labels (name => label).
*/
public function attributeLabels()
{
return [
'username' => 'Логин',
'password' => 'Пароль',
];
}
You can also add such function to model:
public function attributeLabels()
{
return [
'username' => 'My Login',
'password' => 'My Pasword',
'rememberMe' => 'Remember Me, please',
];
}
just change the lable from modles like this
'symptomsBefore' => Yii::t('app', 'Has The Patient Suffered from the same or similar symptoms before'),