protected function buildFieldSet($widgetManager, $palette, $propertyValues)
    {
        $environment         = $this->getEnvironment();
        $definition          = $this->getDataDefinition();
        $translator          = $environment->getTranslator();
        $propertyDefinitions = $definition->getPropertiesDefinition();
        $isAutoSubmit        = ('auto' === $environment->getInputProvider()->getValue('SUBMIT_TYPE'));
        $legendStates        = $this->getLegendStates();
        $editInformation     = $GLOBALS['container']['dc-general.edit-information'];

        $fieldSets = [];
        $first     = true;
        foreach ($palette->getLegends() as $legend) {
            $legendName = $translator->translate(
                $legend->getName() . '_legend',
                $definition->getName()
            );
            $fields     = [];
            $properties = $legend->getProperties($this->model, $propertyValues);

            if (!$properties) {
                continue;
            }

            $legendVisible = $this->isLegendVisible($legend, $legendStates);

            foreach ($properties as $property) {
                $this->ensurePropertyExists($property->getName(), $propertyDefinitions);

                // If this property is invalid, fetch the error.
                if ((!$isAutoSubmit)
                    && $propertyValues
                    && $propertyValues->hasPropertyValue($property->getName())
                    && $propertyValues->isPropertyValueInvalid($property->getName())
                ) {
                    // Force legend open on error.
                    $legendVisible = true;

                    $editInformation->setModelError(
                        $this->model,
                        $propertyValues->getPropertyValueErrors($property->getName()),
                        $propertyDefinitions->getProperty($property->getName())
                    );
                }

                $fields[] = $widgetManager->renderWidget($property->getName(), $isAutoSubmit, $propertyValues);
            }

            $fieldSet['label']   = $legendName;
            $fieldSet['class']   = $this->getLegendClass($first, $legendVisible);
            $fieldSet['palette'] = \implode('', $fields);
            $fieldSet['legend']  = $legend->getName();
            $fieldSets[]         = $fieldSet;

            $first = false;
        }

        // Check if input mask has visible properties.
        if (!$fieldSets) {
            // @codingStandardsIgnoreStart
            \trigger_error('No visible properties for this edit mask defined!', E_USER_ERROR);
            // @codingStandardsIgnoreEnd
        }

        return $fieldSets;
    }