addElement('hidden', 'id'); $this->addElement('text', 'text', ['label' => 'Question', 'required' => true]); $this->addAnswers(); $this->addOptionsColumn(); return parent::_initElements(); } protected function addAnswers() { $name = 'answers'; $options = [ 'id' => 'questions-' . $this->getName() . '-' . $name, 'name' => $name, 'defaults' => Qs_Array::get($this->_defaults, 'answers', []), 'orientation' => Table::ORIENTATION_HORIZONTAL, 'itemClass' => AnswerRow::CLASS, 'itemName' => 'Answer', 'itemsName' => 'Answers', ]; $this->addSubForm(new Table($options), $name); return $this; } public function isValid($data) { $isValid = parent::isValid($data); return $this->isValidCustomRules($data) && $isValid; } public function isValidPartial(array $data) { $isValid = parent::isValidPartial($data); return $this->isValidCustomRules($data) && $isValid; } protected function isValidCustomRules(array $data) { $isValid = $this->isValidCorrectAnswer($data); $isValid = $isValid && $this->isValidAnswersCount($data); return $isValid; } protected function isValidCorrectAnswer(array $data) { if (empty($data['answers'])) { return true; } if (null === ($index = Qs_Array::get($data, 'correctAnswerIndex')) || null === Qs_Array::get($data['answers'], $index) ) { $this->getSubForm('answers')->addError('Please mark correct answer'); return false; } return true; } protected function isValidAnswersCount(array $data) { if (count(Qs_Array::get($data, 'answers', [])) < 2) { $this->getSubForm('answers')->addError('Question should have at least two answers'); return false; } return true; } public function getValues($suppressArrayNotation = false) { $values = parent::getValues($suppressArrayNotation); $values['correctAnswerIndex'] = Qs_Array::get($this->_defaults, 'correctAnswerIndex'); return $values; } }