protected function doInitialize()
    {
        $this->collection = new FieldCollection();
        $this->collection->setGrouping($this->grouping);

        if ($this->references) {
            $repo = $this->em->getRepository(FieldValue::class);
            $instances = $repo->findBy(['id' => $this->references]);
            if ($instances === false) {
                return;
            }

            /** @var FieldValue $val */
            foreach ($instances as $val) {
                $fieldType = $val->getFieldType();
                $field = $this->em->getFieldManager()->getFieldFor($fieldType);
                $type = $field->getStorageType();
                $typeName = $type->getName();
                $typeCol = 'value_' . $typeName;
                $valCol = 'value_' . $typeName;
                if ($typeName === 'json') {
                    /** @deprecated since 3.3 to be renamed in v4. */
                    $valCol = 'value_json_array';
                }

                // Because there's a potential for custom fields that use json storage to 'double hydrate' this causes
                // json_decode to throw a warning. Here we prevent that by replacing the error handler.
                set_error_handler(
                    function ($errNo, $errStr, $errFile) {},
                    E_WARNING
                );
                $hydratedVal = $this->em->getEntityBuilder($val->getContenttype())->getHydratedValue($val->$typeCol, $val->getName(), $val->getFieldName());
                restore_error_handler();

                // If we do not have a hydrated value returned then we fall back to the one passed in
                if ($hydratedVal) {
                    $val->setValue($hydratedVal);
                } else {
                    $val->setValue($val->$valCol);
                }

                $this->collection->add($val);
            }
        }

        $this->em = null;
    }