Обработка формы с помощью ООП

472
30 ноября 2017, 03:15

Я создал класс формы

 class Form {
        private $type ;
        private $value;
        private $placeholder;
        private $action = '';
        private $method;
        private $name;
        private $className;
        public function checkValue($arr) {
            if (array_key_exists('value', $arr)) {
                $this->value = $arr['value'];
            }
        }
        public function checkName($arr) {
            if (array_key_exists('name', $arr)) {
                $this->name = 'name="'.$arr['name'].'"';
            }
        }
        public function checkClass($arr) {
            if (array_key_exists('class', $arr)) {
                $this->className = 'class="' . $arr['class'] . "\" ";
            }
        }
        public function input($arr) {
            $this->type = $arr['type'];
            $this->checkName($arr);
            $this->checkValue($arr);
            $this->checkClass($arr);
            return '<input ' . $this->className . $this->name . ' type="' .$this->type . '" value="' .$this->value . '">';
        }
        public function password($arr) {
            $this->type = 'password';
            $this->checkName($arr);
            $this->checkValue($arr);
            $this->checkClass($arr);
            return '<input '. $this->className . $this->name .' type="' .$this->type . '" value="' .$this->value . '">';
        }
        public function submit($arr) {
            $this->type = 'submit';
            $this->checkName($arr);
            $this->checkValue($arr);
            $this->checkClass($arr);
            return '<input ' . $this->className . $this->name .' type="' .$this->type . '" value="' .$this->value . '">';
        }
        public function textarea($arr) {
            $this->placeholder = $arr['placeholder'];
            $this->name = $arr['name'];
            $this->checkValue($arr);
            $this->checkClass($arr);
            return '<textarea ' . $this->className . $this->name . ' placeholder="' . $this->placeholder. '">' . $this->value . '</textarea>';
        }
        public function open($arr) {
            $this->action = $arr['action'];
            $this->method = $arr['method'];
            $this->checkClass($arr);
            return '<form '.$this->className.' action="'.$this->action.'" method="'.$this->method.'">';
        }
        public function close() {
            return '</form>';
        }
    }

Потом создал класс, который всё наследует от класса Form и почему, если после отправки, не сохраняется значение в input name?

class SmartForm extends Form {
        public function checkValue($arr) {
            if(!empty($_POST['name'])) {
                 $this->value = $_POST['name'];
            }
            parent::checkValue($arr);
        }
    }
    $form2 = new SmartForm;
    echo $form2->open(['action'=>'./2.php', 'method'=>'POST']) . "\n";
    echo "\t ". $form2->input(['type'=>'text', 'placeholder'=>'Ваше имя', 'name'=>'name', 'class'=>'name']) . "\n";
    echo "\t ". $form2->password(['placeholder'=>'Ваш пароль', 'name'=>'pass', 'class'=>'user-password']) . "\n";
    echo "\t ". $form2->submit(['value'=>'Отправить']) . "\n";
    echo $form2->close();
Answer 1

PHP скрипт выводит форму и завершается. При этом все классы и переменные уничножаются. Чтобы после отправки формы у вас запускается новая копия скрипта и она нечего не знает о прошлом скрипте.

У вас в классе наследнике есть метод checkValue который как раз получает из значений формы массив $_POST значение поля name это надо сделать в скрипте 2.php

$form2 = new SmartForm();
$form2->checkValue([]);

После этого у вас в свойстве класса value будет значение введенное пользователем в соответствующий инпут.

Вообще класс построен не совсем верно так как описывает одно поле, а у вас как минимум 2 выводится.

READ ALSO
Как в GridView yii2 изменить view?

Как в GridView yii2 изменить view?

То есть сейчас выводится стандартная таблица yii, хочу поменять шаблон вывода на подобии itemView

529
переназначить id

переназначить id

Всем добрый день!

342
Нелогичное поведение call_user_func_array

Нелогичное поведение call_user_func_array

Почему вот этот код:

291
SOAP добавить 2-ой input!

SOAP добавить 2-ой input!

Делаю сервис, который возвращает ответ в StringПроблема в том что, если я сделаю функцию с 1 инпутом и ввожу 1 инпут, то все работает, а когда хочу...

280