Attribute name must contain word characters only

I have been having this error since yesterday and i can’t find any solution. the error was in the Technician No attribute Label. I already changed the database field to ‘number’ but still no effect. I already changed the word No to Number in the attribute labels but still the same error. Do I need to code a validation exception about this matter? Can someone help me? thanks in advance.

I have this code for the model.

Techinicians.model

public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'technician_no' => 'Technician No',
            'smcode' => 'Code',
            'name' => 'Name',
        ];
    }

and the controller:

public function actionTechnicians()
    {
        $model = new Technicians();
        return $this->render('technicians', [
            'model' => $model,
            ]);
     }

this is the ActiveForm in the View.

<?php $form = ActiveForm::begin([
          'id' => 'new-technician-form',
          'options' => ['class' => 'form-horizontal'],
           ]); ?>
      <?= $form->field($model, 'Technician No')->textInput() ?>
      <?= $form->field($model, 'Code')->textInput() ?>
      <?= $form->field($model, 'Name')->textInput() ?>
<div class="form-group">
      <?= Html::submitButton('Submit', ['class' => 'btn btn-primary', 'name' => 'technicians-button']) ?>
 </div>
<div>
      <?= Html::resetButton('Reset', ['class' => 'btn btn-default']); ?>
 </div>

<?php ActiveForm::end(); ?>

Comments

@gpoehl

activeTextInput and DetailView::widget don’t accept field names with non word characters like ä ö or ü.
In mysql these are valid characters for column names.

@samdark

Is it throwing exception?

@gpoehl

yes.
activeTextInput throws:
Attribute name must contain word characters only in vendoryiisoftyii2helpersBaseHtml.php

and DetailView::widget throws
The attribute must be specified in the format of «attribute», «attribute:format» or «attribute:format:label»

@samdark

It’s not the best practice to use umlauts in code but I’ll check what we can do about it closer to release of 2.0.

@gpoehl

I know but I can’t see a reason not to accept those characters.

@cebe

we already accept them in gridview so we can allow them in these places too…

@samdark

@twiNNi want to create a pull request?

@qiangxue

Moved out of 2.0. Not a crucial one.

@gpoehl

Then you have to create queries or re-design your database to work around this problem. I really would expect that yii can deal with international characters and don’t limit users with a design back to the 60ths.

Why not just drop the constraint and let the database decide what charactes are allowed?

@samdark

@twiNNi we aren’t saying we won’t fix it but since it’s not critical it’s either someone sending a pull request or we’re doing it later in 2.0.1.

@gpoehl

I was just wondering that you don’t fix a bug as soon as possible.

@samdark

Our time is limited, unfortunately.

@kmindi

The regular expression in BaseHtml::getInputName '/(^|.*])([w.]+)([.*|$)/' could be rewritten to ´’/(^|.])(([p{L}p{M}p{N}]+[p{Pd}p{Pc}p{Po}])+)([.*|$)/u’´ (http://www.phpliveregex.com/p/66N). Can somebody confirm that this regular expression is correct for what we expect/need?

p{L} for letters, p{M} for marks (combining characters), p{N} numbers and p{P?} for punctuation (see http://www.regular-expressions.info/unicode.html)

This should then be defined as a constant, as this regular expression is used in more places in that file.

PCRE has to be compiled with—enable-unicode-properties to use this I think.

@cebe

@twiNNi you can send a pull request to speed things up.

@gpoehl

@cebe, unfortunately not. Till now I’ve never used git except for issue reporting.
Hopefully @kmindi can help as he has found a solution.

I just want to repeat my question:
Why not just drop the constraint and let the database decide what charactes are allowed?
Maybe this question looks stupid to you but the reason for the character check is not obvious.

@cebe

In general it is easier to reserve some characters to extend things further making characters with special meaning, when you allow all in first place you can not change the meaning of some later. in this case we can do the change but we have to prioritize issues.

About PR: It is always good to try new things, so give it a try.

@kmindi

@kmindi

can you look over the regular expression and the tests, we maybe need to add tests and adjust the regex further.
Currently DetailView was not changed by me, there a different regex is used and it expects a different format, I’m investigating.

@drdanio

just in «/vendor/yiisoft/yii2/helpers/BaseHtml.php» file find and replace lines:
if (preg_match(‘/(^|.])([w.]+)([.|$)/’, $attribute, $matches)) {
if (!preg_match(‘/(^|.])([w.]+)([.|$)/’, $attribute, $matches)) {
if (!preg_match(‘/(^|.])([w.]+)([.|$)/’, $attribute, $matches)) {
to:
if (preg_match(‘/(^|.])([w.]+)([.|$)/u’, $attribute, $matches)) {
if (!preg_match(‘/(^|.])([w.]+)([.|$)/u’, $attribute, $matches)) {
if (!preg_match(‘/(^|.])([w.]+)([.|$)/u’, $attribute, $matches)) {

@dynasource

if somebody is creating a PR for this, please include the spaces scenario as noted in #12262

@cebe

seems this has been fixed by #13243

@cebe

Hm… no solved for Html though. Need to check whether HTML allows these characters first.

@SamMousa

@SamMousa

I’ve chosen to use public static $attributeRegex instead of a constant to allow for easier customization.

Did some research regarding unicode characters.
When using the /u modifier, both PCRE_UTF8 and PCRE_UCP are used.
https://github.com/php/php-src/blob/bf59acdea75cf13d179f10ce89d296a30f38676d/ext/pcre/php_pcre.c#L364

This means that if Unicode properties are available then PHP with use them to decide if a character is a word character.

Before blindly addding the /u modifier some cases need to be considered.

  1. The subject is ASCII —> no worries, all ASCII is valid UTF-8.
  2. The subject is an encoding that is incompatible with UTF-8 —> the pattern matching will silently fail, in our case that means an error will always be thrown (could be considered good behavior).

@SamMousa

Some tests with ü.
Encoded in UTF-8:

preg_match('/w+', 'ü') === 0;
preg_match('/w+/u', 'ü') === 1;

Encoded in ISO-8859-1:

preg_match('/w+/', utf8_decode('ü')) === 0;
preg_match('/w{1}/u', utf8_decode('ü')) === false;

Practically this suggests that we could just enable the unicode modifier in the regular expression, if we can assume that unicode support is always available. I’m not sure what happens if it is not available, it might fail silently (ie revert to current behavior) or fail hard…

@SamMousa

@cebe, from the spec: https://html.spec.whatwg.org/multipage/syntax.html#attributes-2

Attributes for an element are expressed inside the element’s start tag.

Attributes have a name and a value. Attribute names must consist of one or more characters other than the ASCII whitespace, U+0000 NULL, U+0022 QUOTATION MARK («), U+0027 APOSTROPHE (‘), U+003E GREATER-THAN SIGN (>), U+002F SOLIDUS (/), and U+003D EQUALS SIGN (=) characters, the control characters, and any characters that are not defined by Unicode. In the HTML syntax, attribute names, even those for foreign elements, may be written with any mix of lower- and uppercase letters that are an ASCII case-insensitive match for the attribute’s name.

So the regex that I use is a lot more relaxed than the current one in Yii, yet still a lot stricter than what is allowed according to the spec.

Yii Framework Forum

Loading

Yii PHP Framework

  • Guide
  • API
  • Wiki
  • Forum
  • Community
    • Live Chat
    • Extensions
    • Resources
    • Members
    • Hall of Fame
    • Badges
  • More
    • Learn
    • Books
    • Resources
    • Develop
    • Download Yii
    • Report an Issue
    • Report a Security Issue
    • Contribute to Yii
    • About
    • What is Yii?
    • Release Cycle
    • News
    • License
    • Team
    • Official logo

Не могу понять почему почему такая ошибка вылетает когда хочу сохранить модель с картинкой.

Изображение

Model:

Код: Выделить всё

...

[['uploadfirst', 'uploadsecond'], 'string', 'max'=>100, 'on'=>'save'],
            [['uploadfirst', 'uploadsecond'], 'file', 'extensions' => ['png', 'jpg', 'gif'], 'mimeTypes' => ['image/png', 'image/jpg', 'image/jpeg'], 'on'=>'save'],

...

View:

Код: Выделить всё

...
   </div>
                    <div class="box-body">
                        <div class="row">
                            <div class="col-xs-12 col-md-6">
                                <?= $form->field($model, 'uploadfirst')->fileInput() ?>
                            </div>

                            <div class="col-xs-12 col-md-6">
                                <?= $form->field($model, 'uploadsecond')->fileInput() ?>
                            </div>
                        </div>
...

Может кто подскажет что тут не так ?

Приветствую! Помогите разобраться.. при создании контактной формы с помощью ActiveForm в yii2 решила поменять английский язык на русский и тут выскакивает следующая ошибка:

Invalid Parameter – yiibaseInvalidParamException
Attribute name must contain word characters only.

1. in C:UsersacerOpenServerdomainsinvestvendoryiisoftyii2helpersBaseHtml.php at line 2128

    2119 * @param Model $model the model object
    2120 * @param string $attribute the attribute name or expression
    2121 * @return string the generated input name
    2122 * @throws InvalidParamException if the attribute name contains non-word characters.
    2123 */
    2124 public static function getInputName($model, $attribute)
    2125 {
    2126    $formName = $model->formName();
    2127    if (!preg_match('/(^|.*])([w.]+)([.*|$)/', $attribute, $matches)) {
    2128        throw new InvalidParamException('Attribute name must contain word characters only.');
    2129    }
    2130    $prefix = $matches[1];
    2131    $attribute = $matches[2];
    2132    $suffix = $matches[3];
    2133    if ($formName === '' && $prefix === '') {
    2134        return $attribute . $suffix;
    2135    } elseif ($formName !== '') {
    2136        return $formName . $prefix . "[$attribute]" . $suffix;
    2137    } else {

2. in C:UsersacerOpenServerdomainsinvestvendoryiisoftyii2helpersBaseHtml.php at line 1263 – yiihelpersBaseHtml::getInputName(appmodelsContactForm, 'ваше имя')
3. in C:UsersacerOpenServerdomainsinvestvendoryiisoftyii2helpersBaseHtml.php at line 1313 – yiihelpersBaseHtml::activeInput('text', appmodelsContactForm, 'ваше имя', ['class' => 'form-control', 'autofocus' => true])
4. in C:UsersacerOpenServerdomainsinvestvendoryiisoftyii2widgetsActiveField.php at line 395 – yiihelpersBaseHtml::activeTextInput(appmodelsContactForm, 'ваше имя', ['class' => 'form-control', 'autofocus' => true])
5. in C:UsersacerOpenServerdomainsinvestviewssitecontact.php at line 29 – yiiwidgetsActiveField::textInput(['class' => 'form-control', 'autofocus' => true])

23            <div class="row-content buffer even clear-after">
24                <div class="section-title"><h3>Контакты</h3></div>
25                <p>Техническая поддержка проекта Money-day</p>
26                <div class="column nine">
27                    <?php $form = ActiveForm::begin(['id' => 'contact-form']); ?>
28 
29                    <?= $form->field($model, 'ваше имя')->textInput(['autofocus' => true]) ?>
30 
31                    <?= $form->field($model, 'ваш Email') ?>
32 
33                    <?= $form->field($model, 'тема') ?>
34 
35                    <?= $form->field($model, 'ваше сообщение')->textarea(['rows' => 6]) ?>

6. in C:UsersacerOpenServerdomainsinvestvendoryiisoftyii2baseView.php at line 328 – require('C:UsersacerOpenServerdomains...')
7. in C:UsersacerOpenServerdomainsinvestvendoryiisoftyii2baseView.php at line 250 – yiibaseView::renderPhpFile('C:UsersacerOpenServerdomains...', ['model' => appmodelsContactForm])
8. in C:UsersacerOpenServerdomainsinvestvendoryiisoftyii2baseView.php at line 152 – yiibaseView::renderFile('C:UsersacerOpenServerdomains...', ['model' => appmodelsContactForm], appcontrollersSiteController)
9. in C:UsersacerOpenServerdomainsinvestvendoryiisoftyii2baseController.php at line 381 – yiibaseView::render('contact', ['model' => appmodelsContactForm], appcontrollersSiteController)
10. in C:UsersacerOpenServerdomainsinvestcontrollersSiteController.php at line 180 – yiibaseController::render('contact', ['model' => appmodelsContactForm])
174175176177178179180181182183184185186

174        if ($model->load(Yii::$app->request->post()) && $model->contact(Yii::$app->params['adminEmail'])) {
175            Yii::$app->session->setFlash('contactFormSubmitted');
176 
177            return $this->refresh();
178        }
179        return $this->render('contact', [
180            'model' => $model,
181        ]);
182    }
183 
184    /**
185     * Displays about page.
186     *

11. appcontrollersSiteController::actionContact()

вот код из contact.php:

<?php $form = ActiveForm::begin(['id' => 'contact-form']); ?>

                <?= $form->field($model, 'Ваше имя')->textInput(['autofocus' => true]) ?>

                <?= $form->field($model, 'Ваш Email') ?>

                <?= $form->field($model, 'Тема') ?>

                <?= $form->field($model, 'Ваше сообщение')->textarea(['rows' => 6]) ?>

                <?= $form->field($model, 'verifyCode')->widget(Captcha::className(), [
                    'template' => '<div class="row"><div class="col-lg-3">{image}</div><div class="col-lg-6">{input}</div></div>',
                ]) ?>

                <div class="form-group">
                    <?= Html::submitButton('Отправить', ['class' => 'btn btn-primary', 'name' => 'contact-button']) ?>
                </div>

<?php ActiveForm::end(); ?>

Вот код из web.php:

$config = [
    'id' => 'basic',
    'basePath' => dirname(__DIR__),
    'bootstrap' => ['log'],
    'language' => 'ru-RU',
    'sourceLanguage' => 'en-US',
    'timeZone' => 'Europe/Moscow',

Вот код из ContactForm.php:

class ContactForm extends Model
{
    public $name;
    public $email;
    public $subject;
    public $body;
    public $verifyCode;


/**
 * @return array the validation rules.
 */
public function rules()
{
    return [
        // name, email, subject and body are required
        [['Ваше имя', 'Ваш Email', 'Тема', 'Ваше сообщение'], 'required'],
        // email has to be a valid email address
        ['email', 'email'],
        // verifyCode needs to be entered correctly
        ['verifyCode', 'captcha'],
    ];
}

/**
 * @return array customized attribute labels
 */
public function attributeLabels()
{
    return [
        'verifyCode' => 'Введите следующий код безопасности',
    ];
}

/**
 * Sends an email to the specified email address using the information collected by this model.
 * @param string $email the target email address
 * @return bool whether the model passes validation
 */
public function contact($email)
{
    if ($this->validate()) {
        Yii::$app->mailer->compose()
            ->setTo($email)
            ->setFrom([$this->email => $this->name])
            ->setSubject($this->subject)
            ->setTextBody($this->body)
            ->send();

        return true;
    }
    return false;
}

}

Понравилась статья? Поделить с друзьями:
  • Attestat excel как добавить
  • Attention sign in word
  • Attention another word for
  • Attendance sheet in excel
  • Attend to my excel