Call to a member function format() on null

Общие вопросы по использованию второй версии фреймворка. Если не знаете как что-то сделать и это про Yii 2, вам сюда.
Закрыто
Drugpunker
Сообщения: 187
Зарегистрирован: 2014.08.13, 19:44

Call to a member function format() on null

Сообщение Drugpunker »

Добрый вечер.
Читаю "Разработка приложений в YII2".

При запуске теста QueryCustomerByPhoneNumberCept выводится ошибка:
Step I fill field "PhoneRecord[number]","599.760.3821"
Fail Field by name, label, CSS or XPath element with 'PhoneRecord[number]' was not found.


Понаблюдав за выполнением в браузере, лицезрею ошибку при при отправке формы:
Call to a member function format() on null

Это поле Birth date. Крутил/ смотрел метод store в CustomerController, конкретно
$customer_record->birth_date = $customer->birth_date->format('Y-m-d');

так ничего и не нашёл.

Что делаю не так? Может кто-нить сталкивался?
zelenin
Сообщения: 10596
Зарегистрирован: 2013.04.20, 11:30

Re: Call to a member function format() on null

Сообщение zelenin »

Call to a member function format() on null

вызывается функция format() объекта, который на самом деле null.
Drugpunker
Сообщения: 187
Зарегистрирован: 2014.08.13, 19:44

Re: Call to a member function format() on null

Сообщение Drugpunker »

Верно. Но данные то ведь в объект передаются.
Поле дата заполняется. Конструктор класса customer присваивает (во всяком случае должен) значение переменной $birth_date. Её уже должен обработать метод format().
Но объект пустой.
Ничего не пойму.
Аватара пользователя
ElisDN
Сообщения: 5845
Зарегистрирован: 2012.10.07, 10:24
Контактная информация:

Re: Call to a member function format() on null

Сообщение ElisDN »

Чем у Вас поле $customer->birth_date заполняется?
Drugpunker
Сообщения: 187
Зарегистрирован: 2014.08.13, 19:44

Re: Call to a member function format() on null

Сообщение Drugpunker »

Сейчас не дома. Посмотрел код по поиску. По-моему я упустил метод makeCustomer, создающий экземпляр класса. Позже гляну. Пока с Codeception разбирался (изучал), потерялся слегка. Инфа в книге не очень, на мой взгляд, структуирована. Приходится многое разбирать. Да ещё и шаблон advanced взял под обучение.
Drugpunker
Сообщения: 187
Зарегистрирован: 2014.08.13, 19:44

Re: Call to a member function format() on null

Сообщение Drugpunker »

Поле в форме заполняется датой в формате 1970-01-01.
Drugpunker
Сообщения: 187
Зарегистрирован: 2014.08.13, 19:44

Re: Call to a member function format() on null

Сообщение Drugpunker »

Вобщем всё перепроверил 10 000 раз. Не могу понять почему объект пустой.
Onotole
Сообщения: 1808
Зарегистрирован: 2012.12.24, 12:49

Re: Call to a member function format() on null

Сообщение Onotole »

var_dump($customer->birth_date);
Drugpunker
Сообщения: 187
Зарегистрирован: 2014.08.13, 19:44

Re: Call to a member function format() on null

Сообщение Drugpunker »

Попоробовал вывести переменную $customer_record->birth_date из метода:

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

private function store(Customer $customer)
    {
        $customer_record = new CustomerRecord();
        $customer_record->name = $customer->name;
        $customer_record->birth_date = $customer->birth_date->format('Y-m-d');
        
        /*Вот так вывел*/
       echo $customer_record->birth_date; exit();
       
        $customer_record->notes = $customer->notes;

        $customer_record->save();
Получаю ошибку:
DateTime::__construct(): Failed to parse time string (1566-25-25) at position 6 (5): Unexpected character
Drugpunker
Сообщения: 187
Зарегистрирован: 2014.08.13, 19:44

Re: Call to a member function format() on null

Сообщение Drugpunker »

Ввожу вроде всё правильно...

1970-11-25
Drugpunker
Сообщения: 187
Зарегистрирован: 2014.08.13, 19:44

Re: Call to a member function format() on null

Сообщение Drugpunker »

Onotole писал(а):var_dump($customer->birth_date);
Выдаёт NULL

А почему пустой?
Drugpunker
Сообщения: 187
Зарегистрирован: 2014.08.13, 19:44

Re: Call to a member function format() on null

Сообщение Drugpunker »

Нет. И главное же в методе makeCustomer данные есть.

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

private function makeCustomer(CustomerRecord $customer_record, PhoneRecord $phone_record)
    {
        $name = $customer_record->name;
        $birth_date = new \DateTime($customer_record->birth_date);

        var_dump($name);
        var_dump($birth_date);

        $customer = new Customer($name, $birth_date);
        $customer->notes = $customer_record->notes;
        $customer->phones[] = new Phone($phone_record->number);

        return $customer;
    }
Но передав в метод store - пусто

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

private function store(Customer $customer)
    {
        $customer_record = new CustomerRecord();
        $customer_record->name = $customer->name;

        var_dump($customer_record->name);
        var_dump($customer_record->birth_date); exit();
//        var_dump($customer->birth_date); exit();
//        $customer_record->birth_date = $customer->birth_date->format('Y-m-d');
        $customer_record->notes = $customer->notes;

        $customer_record->save();

        foreach ($customer->phones as $phone)
        {
            $phone_record = new PhoneRecord();
            $phone_record->number = $phone->number;
            $phone_record->customer_id = $customer_record->id;
            $phone_record->save();
        }
    }
 
????????????????

Что не так делаю?
Onotole
Сообщения: 1808
Зарегистрирован: 2012.12.24, 12:49

Re: Call to a member function format() on null

Сообщение Onotole »

Не вижу, чтобы где-то задавались значение для birth_date
Drugpunker
Сообщения: 187
Зарегистрирован: 2014.08.13, 19:44

Re: Call to a member function format() on null

Сообщение Drugpunker »

Метод store принимает в качестве аргумента результат метода makeCustomer для сохранения в бд.
В свою очередь данные попадают в метод makeCustomer из пост переменной. Но теряются после передачи в store.
Аватара пользователя
ElisDN
Сообщения: 5845
Зарегистрирован: 2012.10.07, 10:24
Контактная информация:

Re: Call to a member function format() on null

Сообщение ElisDN »

Тогда смотрите в конструкторе new Customer($name, $birth_date);
Drugpunker
Сообщения: 187
Зарегистрирован: 2014.08.13, 19:44

Re: Call to a member function format() on null

Сообщение Drugpunker »

Вот именно, что там всего один сеттер, устанавливающий поля имени и даты рождения.
Phpstorm не ругается. Всё тянется как нужно. Вчера даже примеры к книге скопипастил, поправил нэймспэйсы. Всё равно не работает. Вечером попробую в очередной раз взглядом чё нить высверлить..
Drugpunker
Сообщения: 187
Зарегистрирован: 2014.08.13, 19:44

Re: Call to a member function format() on null

Сообщение Drugpunker »

И так, после очередного удара головой об стенку нашёл таки:

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

//    public function _construct($name, $birth_date)
//    {
//        $this->name = $name;
//        $this->birth_date = $birth_date;
//    }

    public function __construct($name, $birth_date)
    {
        $this->name = $name;
        $this->birth_date = $birth_date;
    }
То, что закомментил - неправильно.

Вот же гадина. Несколько дней сверлил глазами эту функцию. :roll:

Стыдно.
zelenin
Сообщения: 10596
Зарегистрирован: 2013.04.20, 11:30

Re: Call to a member function format() on null

Сообщение zelenin »

один var_dump в функции присваивания сразу бы показал что вы в функцию даже не попадаете
Drugpunker
Сообщения: 187
Зарегистрирован: 2014.08.13, 19:44

Re: Call to a member function format() on null

Сообщение Drugpunker »

Буду объективнее. Спасибо всем. Помогли.
Drugpunker
Сообщения: 187
Зарегистрирован: 2014.08.13, 19:44

Re: Call to a member function format() on null

Сообщение Drugpunker »

:idea:
Закрыто