Clean up index functionality in Repeater widget (#4424)

- Remove $indexCount property, as it is no longer needed
- Determine highest key number in data, and increment when adding item
- Remove some old code and dependencies

Fixes #4402.
This commit is contained in:
Ben Thomson 2019-06-29 13:42:45 +08:00 committed by GitHub
parent 31b6a1f471
commit 3eac21219f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -3,7 +3,6 @@
use Lang;
use ApplicationException;
use Backend\Classes\FormWidgetBase;
use October\Rain\Html\Helper as HtmlHelper;
/**
* Repeater Form Widget
@ -53,11 +52,6 @@ class Repeater extends FormWidgetBase
*/
protected $defaultAlias = 'repeater';
/**
* @var int Count of repeated items.
*/
protected $indexCount = 0;
/**
* @var array Meta data associated to each field, organised by index
*/
@ -107,8 +101,6 @@ class Repeater extends FormWidgetBase
$this->loaded = true;
}
$fieldName = $this->formField->getName(false);
$this->processGroupMode();
if (!self::$onAddItemCalled) {
@ -214,10 +206,9 @@ class Repeater extends FormWidgetBase
: $this->getLoadValue();
if ($currentValue === null) {
$this->indexCount = 0;
$this->formWidgets = [];
return;
}
}
// Ensure that the minimum number of items are preinitialized
// ONLY DONE WHEN NOT IN GROUP MODE
@ -233,16 +224,14 @@ class Repeater extends FormWidgetBase
}
}
}
if (!is_array($currentValue)) {
return;
}
collect($currentValue)->each(function ($value, $index) {
$this->makeItemFormWidget($index, array_get($value, '_group', null));
});
$this->indexCount = max(count($currentValue), $this->indexCount);
}
/**
@ -304,15 +293,14 @@ class Repeater extends FormWidgetBase
$groupCode = post('_repeater_group');
$index = $this->getNextIndex();
$this->prepareVars();
$this->vars['widget'] = $this->makeItemFormWidget($this->indexCount, $groupCode);
$this->vars['indexValue'] = $this->indexCount;
$this->vars['widget'] = $this->makeItemFormWidget($index, $groupCode);
$this->vars['indexValue'] = $index;
$itemContainer = '@#' . $this->getId('items');
// Increase index count after item is created
++$this->indexCount;
return [
$itemContainer => $this->makePartial('repeater_item')
];
@ -333,6 +321,30 @@ class Repeater extends FormWidgetBase
return $widget->onRefresh();
}
/**
* Determines the next available index number for assigning to a new repeater item.
*
* @return int
*/
protected function getNextIndex()
{
if ($this->loaded === true) {
$data = post($this->formField->getName());
if (is_array($data) && count($data)) {
return (max(array_keys($data)) + 1);
}
} else {
$data = $this->getLoadValue();
if (is_array($data)) {
return count($data);
}
}
return 0;
}
//
// Group mode
//