diff --git a/src/Form/ContenttypeType.php b/src/Form/ContenttypeType.php index 59421eb..270157f 100644 --- a/src/Form/ContenttypeType.php +++ b/src/Form/ContenttypeType.php @@ -14,14 +14,17 @@ use Symfony\Component\Form\FormInterface; use Symfony\Component\Form\FormView; use Symfony\Component\OptionsResolver\OptionsResolver; +use Symfony\Contracts\Cache\CacheInterface; class ContenttypeType extends AbstractType { private $query; + private $cache; - public function __construct(Query $query) + public function __construct(Query $query, CacheInterface $cache) { $this->query = $query; + $this->cache = $cache; } public function configureOptions(OptionsResolver $resolver): void @@ -41,6 +44,8 @@ private function getDefaultParams(): array 'limit' => 4, 'sort' => 'title', 'criteria' => [], + 'cache' => false, + 'cache_lifetime' => 3600 ]; } @@ -62,10 +67,27 @@ public function buildForm(FormBuilderInterface $builder, array $options): void $entries = $this->query->getContent($params['contenttype'], $criteria); $choices = []; - foreach ($entries->getCurrentPageResults() as $entry) { - $value = $entry->getFieldValue($params['value']); - $label = $entry->getFieldValue($params['label']); - $choices[$label] = $value; + if ($params['cache']) { + $cachedChoices = $this->cache->getItem('choices'); + + if (!$cachedChoices->isHit()) { + foreach ($entries->getCurrentPageResults() as $entry) { + $value = $entry->getFieldValue($params['value']); + $label = $entry->getFieldValue($params['label']); + $choices[$label] = $value; + } + $cachedChoices->set($choices); + $cachedChoices->expiresAfter($params['cache_lifetime']); + $this->cache->save($cachedChoices); + } + + $choices = $cachedChoices->get(); + } else { + foreach ($entries->getCurrentPageResults() as $entry) { + $value = $entry->getFieldValue($params['value']); + $label = $entry->getFieldValue($params['label']); + $choices[$label] = $value; + } } $options['choices'] = $choices; diff --git a/src/FormBuilder.php b/src/FormBuilder.php index 39728ce..60b82e4 100644 --- a/src/FormBuilder.php +++ b/src/FormBuilder.php @@ -43,7 +43,7 @@ public function build(string $formName, array $data, Collection $config, EventDi foreach ($config->get($formName)['fields'] as $name => $field) { // If we passed in a default value, set it as the Field's `data`-value if (array_key_exists($name, $data)) { - if(is_iterable($data[$name])){ + if (is_iterable($data[$name])) { $field['options'] = array_merge($field['options'], $data[$name]['options']); } else { $field['options']['data'] = $data[$name];