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
Related
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>
I'm using following rules in model:
public function rules() {
return [
[['beurteilung_fachlich', 'beurteilung_persoenlich', 'sonstiges', 'anschreiben'], 'string'],
[['anschreiben'], 'string', 'max' => 255]
];
}
Although there is nowhere any restriction for attribute beurteilung_persoenlich, I will get error of form validation:
Beurteilung(fachlich) must not be longer as 255 chars!
How can this be?
What do I wrong?
Is there another place for declaring validation rules besides in model?
Database has datatype TEXT without any boundary.
Here is code of form:
<div class="col-md-6">
<?= $form->field($model, 'beurteilung_fachlich')>widget(\dosamigos\ckeditor\CKEditor::className(), ['preset' => 'full', 'clientOptions' => ['height' => 200]]) ?>
</div>
I noticed, that following rule will influence all other string attributes, too
[['anschreiben'], 'string', 'max' => 255]];
I have no idea, why, but after having removed this rule, everything did well.
In order to valid form clientside, I coded like this(in form):
$form->field($model, 'anschreiben', ['addon' => ['prepend' => ['content' => 'Anschreiben']]])->widget(TwbsMaxlength::className())->textInput(['maxlength' => 255])->label(false);
In most of my cases, the javascript / client side validation still work because of caching. Even after the model is modified. Try to Cmd / Ctrl + Shift + R (bypassing the cache), or delete the content of your backend/web/assets or frontend/web/assets.
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 active form
<?= $form->field($model, 'pid')->dropDownList([1=>1,2=>2])->hint('上级分类') ?>
I want to disable the option item 2=>2.
Is there a way to do it?
You can add attributes for all items in the dropdownlist with the 'options' key. Let's say you want to disable the second item.
<?= $form->field($model, 'pid')->dropDownList([1 => 1, 2 => 2], ['options' => [2 => ['disabled' => true]]])->hint('上级分类') ?>
In the docs:
http://www.yiiframework.com/doc-2.0/yii-helpers-basehtml.html#activeDropDownList()-detail
This would work definitely:
<?= $form->field($model, 'pid')->dropDownList([1=>1,2=>2], ['options'=>['2'=>['disabled'=>true]]]) ?>
ActiveField dropDownlist() explicitly calls BaseHtml activeDropDownList():
From the docs to ActiveField dropDownList():
The tag options in terms of name-value pairs.
For the list of available options please refer to the $options
parameter of yii\helpers\Html::activeDropDownList().
And from the docs to BaseHtml activeDropDownList():
options: array, the attributes for the select option tags. The array
keys must be valid option values, and the array values are the extra
attributes for the corresponding option tags. For example,
[
'value1' => ['disabled' => true],
'value2' => ['label' => 'value 2'],
];
So pass these options:
[
2 => ['disabled' => true],
],
as second parameter to dropDownList().
Try this:
$disableDataArr['1'] = ['disabled' => true];
dropDownList( $dataArr, ['options'=> $disableDataArr ])
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'),