How to change label text of the ActiveField? - yii2

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'),

Related

Yii2 : Display the phone mask as text

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>

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 transfer logic from view to model

I would like to arrange my code a little bit better. I have this in view, generated by giiant:
$form->field($model, 'land_id')->dropDownList(ArrayHelper::map(app\models\Land::find()->orderBy('name')->all(), 'id', 'name'), [
'prompt' => Yii::t('app', 'Select'),
'disabled' => (isset($relAttributes) && isset($relAttributes['land_id'])),]);
Somebody has told me here on stackoverflow that it's not really nice. So I would like to transfer this part:
ArrayHelper::map(app\models\Land::find()->orderBy('name')->all(), 'id', 'name'
into model. The same applies to grid filter dropdowns:
'filter' => ArrayHelper::map(\app\models\base\Land::find()->asArray()->all(), 'id', 'name'),
Does it make sense? I think so, I hope so. I've tried to implement it in model Land 2 ways:
public function getAllAsArray() {
return ArrayHelper::map(app\models\Land::find()->orderBy('name')->all(), 'id', 'name');
}
or
public function getAllAsArray() {
return ArrayHelper::map($this->find()->orderBy('name')->all(), 'id', 'name');
}
and I wanted to call it from View/Grid (Zip - Land):
'filter' => $model->land->allAsArray,
but I'm getting the following error:
Undefined variable: model
then tried this way:
'filter' => function ($model) {$model->getLand()->one()->getAllAsArray();},
'filter' => function ($model) {$model->getLand()->getAllAsArray();},
then I get no error messages, but it's also not working.
and in Form (Zip - Land) the same way:
$form->field($model, 'land_id')->dropDownList($model->land->allAsArray(), [
'prompt' => Yii::t('app', 'Select'),
'disabled' => (isset($relAttributes) && isset($relAttributes['land_id'])),]);
but I'm getting the following error:
Call to a member function getAllAsArray() on null
Can you please point me to the right direction? I think I don't understand something basically and this disturbes me. Thank you very much in advance!
Land model
public static function getAllAsArray() {
return ArrayHelper::map(Land::find()->orderBy('name')->all(), 'id', 'name');
}
index
use app\models\Land;
'filter' => Land::getAllAsArray(),
form
use app\models\Land;
$form->field($model, 'land_id')->dropDownList(Land::getAllAsArray(), [
'prompt' => Yii::t('app', 'Select'),
'disabled' => (isset($relAttributes) && isset($relAttributes['land_id']))]);

Getting field value in controller

I want to get value of field in controller.
could you please help me?
here is my form code:
<?php
$form = ActiveForm::begin([
'id' => 'request-form',
'action' => 'site/request_page',
'method' => 'post',
'fieldConfig' => ['autoPlaceholder' => false]
]);
?>
<?= $form->field($model, 'workroom_id')->label(FALSE) ?>
and this is my controller code:
public function actionRequest_page() {
echo Yii::$app->request->post('workroom_id');
die();
}
But I got nothing in result.
write workroom_id in safe rule like this-
public function rules()
{
return [
[['workroom_id'],'safe']
];
}
Use bellow code -
echo Yii::$app->request->post('MODEL_NAME')['workroom_id'];
You should expand your action form-attribute. By using Url::to() for instance. As in echo \yii\helpers\Url::to(['site/request_page']);
And access your post data differently. Try var_dump(Yii::$app->request->post()); to see what your form data looks like. The other answer shows how to access it correctly.
The docs have an excellent starting place for working with forms.

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.