Stevan Tosic
Stevan Tosic

Reputation: 7199

Disable days and month from Symfony DateType::class

->add('attendFrom', DateType::class, array(
                'widget' => 'choice',
                'html5' => false,
                'months' => array(),
                'days' => array(),
                'attr' => array(
                    'placeholder' => 'Start year, e.g., 1980 ',
                )
            ))

There is type from which I try to disable days and month. I want to show only years. Is this is possible?

I had find some solution to hide days and months from a twig but I wonder if I can disable this from FormType.

Cheers

Upvotes: 3

Views: 4158

Answers (2)

Gopal Joshi
Gopal Joshi

Reputation: 2358

Put yyyy in format option

Form:

->add('attendFrom', DateType::class, array(
    'format' => 'yyyy',
    'widget' => 'choice',
    'html5' => false,
    'attr' => array(
        'placeholder' => 'Start year, e.g., 1980 ',
    )
))

Update-1

Hide month and day control in twig

TWIG:

{{ 
    form_widget(
        form.formName.attendFrom.day, 
        { 
            'attr': { 'style': 'display:none' }
        }
    )
    form_widget(
        form.formName.attendFrom.month, 
        { 
            'attr': { 'style': 'display:none' }
        }
    ) 
}}

Ref: Link

Upvotes: 6

Jokūbas
Jokūbas

Reputation: 116

You can just simply create a ChoiceType field with

...
'choices' => range(date('Y') - 10, date('Y') + 10),
...

However, if you need to have a DateTime object after submitting your form, then you should define your own View Transformer.

In your form type class add the following lines:

public function buildForm(
    FormBuilderInterface $builder,
    array $options
)
{
    $builder
        ->add(
            $builder->create('attendFrom', DateType::class, [
                'widget' => 'choice',
            ])
            ->addViewTransformer(new IncompleteDateTransformer())
        );
}

Also, create your own View Transformer:

/**
 * Class IncompleteDateTransformer.
 */
class IncompleteDateTransformer implements DataTransformerInterface
{
    /**
     * {@inheritdoc}
     */
    public function transform($value)
    {
        return $value;
    }

    /**
     * {@inheritdoc}
     */
    public function reverseTransform($value)
    {
        if (!is_array($value)) {
            return $value;
        }

        if (empty($value['year'])) {
            return $value;
        }

        $value['day'] = $value['day'] ?? 1;
        $value['month'] = $value['month'] ?? 1;

        return $value;
    }
}

And after that, render only attendFrom.year field or hide attendFrom.month and attendFrom.day fields via attr argument in form_row/form_widget function. See Gopal Joshi answer for example on hiding other fields.

Upvotes: 3

Related Questions