Форум программистов
 

Восстановите пароль или Зарегистрируйтесь на форуме, о проблемах и с заказом рекламы пишите сюда - alarforum@yandex.ru, проверяйте папку спам!

Вернуться   Форум программистов > Скриптовые языки программирования > PHP
Регистрация

Восстановить пароль
Повторная активизация e-mail

Купить рекламу на форуме - 42 тыс руб за месяц

Ответ
 
Опции темы Поиск в этой теме
Старый 27.10.2018, 14:54   #1
swallow_97
Новичок
Джуниор
 
Регистрация: 27.10.2018
Сообщений: 1
По умолчанию При создании обратной формы возникла ошибка: Call to a member function isAttributeRequired() on null

Здравствуйте, после создания формы обратной связи, выскочила ошибка:

Код:
Call to a member function isAttributeRequired() on null
1. in C:\Users\acer\OSPanel\domains\medicalyii2\vendor\yiisoft\yii2\widgets\ActiveField.php at line                  
    /**
     * Adds aria attributes to the input options.
     * @param $options array input options
     * @since 2.0.11
     */
    protected function addAriaAttributes(&$options)
    {
        if ($this->addAriaAttributes) {
            if (!isset($options['aria-required']) && $this->model->isAttributeRequired($this->attribute)) {
                $options['aria-required'] = 'true';
            }
            if (!isset($options['aria-invalid'])) {
                if ($this->model->hasErrors($this->attribute)) {
                    $options['aria-invalid'] = 'true';
                }
            }
        }
    }
                
2. yii\base\ErrorHandler::handleFatalError()
Вот моя форма:

Код:
<?php
                        $form = ActiveForm::begin([
                            'id' => 'appointment_form',
                            'fieldConfig' => [
                                'options' => [
                                    'tag' => 'span',
                                    'class' => 'input input--kohana'
                                ],
                                'template' => '{input}{label}',
                                'inputOptions' => ['class' => 'input__field input__field--kohana'],
                                'labelOptions' => [
                                    'class' => 'input__label input__label--kohana',
                                ]
                            ]
                        ]);
                        ?>
                        <?= $form->field($model, 'name')->textInput(['inputOptions' => ['id' => 'input-29']])->label("<i class=\"icon-phone5 icon icon--kohana\"></i><span class=\"input__label-content input__label-content--kohana\">" . $model->getAttributeLabel('Your Name') . "</span>") ?>
                        <?= $form->field($model, 'email')->textInput(['inputOptions' => ['id' => 'input-30']])->label("<i class=\"icon-dollar icon icon--kohana\"></i><span class=\"input__label-content input__label-content--kohana\">" . $model->getAttributeLabel('Email Address') . "</span>") ?>
                        <span class="last"><?= $form->field($model, 'phone')->textInput(['inputOptions' => ['id' => 'input-31']])->label("<i class=\"icon-phone5 icon icon--kohana\"></i><span class=\"input__label-content input__label-content--kohana\">" . $model->getAttributeLabel('Phone Number') . "</span>") ?></span>
                        <?= $form->field($model, 'date')->textInput(['inputOptions' => ['id' => 'datepicker']])->label(false) ?>
                        <!-- ОСТАЛЬНЫЕ ПОЛЯ ФОРМЫ  -->
                        <?= $form->field($model, 'body')->textInput(['inputOptions' => ['id' => 'texterea']])->label("<i class=\"icon-new-message icon icon--kohana\"></i><span class=\"input__label-content input__label-content--kohana\">" . $model->getAttributeLabel('Message') . "</span>") ?>
                        <?= Html::submitButton('Submit'); ?>
                        <?php
                        ActiveForm::end();
                        ?>
Контроллер:

Код:
public function actionIndex()
    {
        /* Создаем экземпляр класса */
        $model = new AppointmentForm();
        /* получаем данные из формы и запускаем функцию отправки contact, если все хорошо, выводим сообщение об удачной отправке сообщения на почту */
        if ($model->load(Yii::$app->request->post()) && $model->appointment(Yii::$app->params['adminEmail'])) {
            Yii::$app->session->setFlash('contactFormSubmitted');
            return $this->refresh();
            /* иначе выводим форму обратной связи */
        }  else {
        return $this->render('index');
        }
    }
Модель AppointmentForm.php

Код:
class AppointmentForm extends Model
{
    public $name;
    public $email;
    public $phone;
    public $date;
    public $body;


    /**
     * @return array the validation rules.
     */
    public function rules()
    {
        return [
            // name, email, subject and body are required
            [['name', 'email', 'phone', 'date', 'body'], 'required'],
            // email has to be a valid email address
            ['email', 'email'],
        ];
    }

    /**
     * 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 appointment($email)
    {
        $content = "<p>Email: " . $this->email . "</p>";
        $content .= "<p>Name: " . $this->name . "</p>";
        $content .= "<p>Phone: " . $this->phone . "</p>";
        $content .= "<p>Date: " . $this->date . "</p>";
        $content .= "<p>Body: " . $this->body . "</p>";
        if ($this->validate()) {
            Yii::$app->mailer->compose("@app/mail/layouts/html", ["content" => $content])
                //->setTo($email)
                ->setTo('swallowsveta97@yandex.ru')
                ->setFrom([\Yii::$app->params['supportEmail'] => $this->name])
                ->setPhone($this->phone)
                ->setDate($this->date)
                ->setTextBody($this->body)
                ->send();

            return true;
        }
        return false;
    }
}
swallow_97 вне форума Ответить с цитированием
Старый 27.10.2018, 17:24   #2
ADSoft
Старожил
 
Регистрация: 25.02.2007
Сообщений: 4,150
По умолчанию

Ну перевести сложно?
Ну нету метода isAttributeRequired в модели
ADSoft вне форума Ответить с цитированием
Старый 27.10.2018, 23:27   #3
Andkorol
Старожил
 
Регистрация: 31.05.2010
Сообщений: 3,301
По умолчанию

Цитата:
Сообщение от ADSoft Посмотреть сообщение
Ну нету метода isAttributeRequired в модели
Точно есть, в базовой модели
https://www.yiiframework.com/doc/api/2.0/yii-base-model#isAttributeRequired()-detail

Если только ТС не забыл указать, какую именно Model расширяет его модель формы:
PHP код:
use yii\base\Model
Тут скорее проблема в самом атрибуте.
Сложно сказать, не видя полного стека ошибки – а только финальную его часть.
Andkorol вне форума Ответить с цитированием
Ответ


Купить рекламу на форуме - 42 тыс руб за месяц

Опции темы Поиск в этой теме
Поиск в этой теме:

Расширенный поиск


Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
error: cannot call member function without object NDrago Общие вопросы C/C++ 2 28.04.2018 13:49
Laravel: Call to a member function attach() on null Max00766 PHP 1 31.08.2017 12:21
Как обработать: Fatal error: Call to a member function asArray() on a non-object in ? СамСебеСамса PHP 12 21.03.2014 20:56
Ошибка с3867 function call missing argument list enjo Общие вопросы C/C++ 11 13.11.2012 17:49
ошибка Call to a member function fetch_assoc() on a non-object Bendebej PHP 2 02.04.2010 14:04