View source
<?php
namespace Drupal\simple_multistep;
use Drupal\Core\Form\FormStateInterface;
class FormStep {
protected $form;
protected $formState;
protected $currentStep;
protected $steps;
protected $stepSettings;
public function __construct(array &$form, FormStateInterface $form_state) {
$this->form = $form;
$this->formState = $form_state;
$this->currentStep = 0;
$this
->updateStepInfo();
}
public function updateStepInfo() {
$this
->fetchSteps();
$this
->fetchStepSettings();
}
public function getCurrentStep() {
return $this->currentStep;
}
public function increaseStep() {
$this->currentStep++;
}
public function reduceStep() {
$this->currentStep--;
}
protected function setCurrentStep() {
$this->currentStep = 0;
$this->currentStep = empty($this->formState
->get('step')) ? 0 : $this->formState
->get('step');
}
public function getSteps() {
return $this->steps;
}
protected function fetchSteps() {
$steps = array();
if (isset($this->form['#fieldgroups']) && is_array($this->form['#fieldgroups'])) {
foreach ($this->form['#fieldgroups'] as $field_group) {
if ($field_group->format_type == 'form_step') {
$steps[] = $field_group;
}
}
usort($steps, array(
$this,
'sortStep',
));
}
$this->steps = $steps;
}
protected static function sortStep($first_object, $second_object) {
if ($first_object->weight == $second_object->weight) {
return 0;
}
return $first_object->weight < $second_object->weight ? -1 : 1;
}
public function getStepSettings() {
return $this->stepSettings;
}
protected function fetchStepSettings() {
$step_settings = array();
if (isset($this->form['#fieldgroups'])) {
$form_steps = $this
->getSteps();
if (!empty($form_steps) && isset($form_steps[$this->currentStep])) {
$step_settings = $form_steps[$this->currentStep];
}
}
$this->stepSettings = $step_settings;
}
public function setFormState(FormStateInterface $form_state) {
$this->formState = $form_state;
}
public function getStepValues($step) {
$list_value = array();
$all_children = $this
->getAllChildren($step);
$current_user_input = $this->formState
->getValues();
foreach ($all_children as $field_name) {
if (isset($current_user_input[$field_name])) {
$list_value[$field_name] = $current_user_input[$field_name];
}
}
return $list_value;
}
protected function getAllChildren($fieldgroup, array $child = []) {
if ($group_children = $fieldgroup->children) {
foreach ($group_children as $form_element_id) {
if (isset($this->form[$form_element_id])) {
$child[] = $form_element_id;
}
elseif (isset($this->form['#fieldgroups'][$form_element_id]->children)) {
$child = $this
->getAllChildren($this->form['#fieldgroups'][$form_element_id], $child);
}
}
}
return $child;
}
}