33namespace SumoCoders \FrameworkCoreBundle \Form \Extension ;
44
55use Symfony \Component \Form \AbstractTypeExtension ;
6+ use Symfony \Component \Form \FormEvent ;
7+ use Symfony \Component \Form \FormEvents ;
68use Symfony \Component \Form \FormInterface ;
79use Symfony \Component \Form \FormView ;
810use Symfony \Component \OptionsResolver \OptionsResolver ;
911use Symfony \Component \Form \Extension \Core \Type \CollectionType ;
12+ use Symfony \Component \Form \FormBuilderInterface ;
13+ use Symfony \Component \Form \FormError ;
1014
1115final class CollectionTypeExtension extends AbstractTypeExtension
1216{
@@ -24,13 +28,57 @@ public function configureOptions(OptionsResolver $resolver): void
2428 [
2529 'allow_drag_and_drop ' => true ,
2630 'add_button_label ' => 'forms.buttons.addItem ' ,
31+ 'minimum_required_items ' => 0 ,
32+ 'maximum_required_items ' => null ,
33+ 'error_bubbling ' => false ,
2734 ]
2835 );
2936 }
3037
38+ public function buildForm (FormBuilderInterface $ builder , array $ options ): void
39+ {
40+ parent ::buildForm ($ builder , $ options );
41+
42+ if ($ options ['minimum_required_items ' ] < 0 ) {
43+ throw new \InvalidArgumentException ('minimum_required_items cannot be lower than 0 ' );
44+ }
45+
46+ if ($ options ['maximum_required_items ' ] !== null && $ options ['maximum_required_items ' ] < $ options ['minimum_required_items ' ]) {
47+ throw new \InvalidArgumentException ('maximum_required_items cannot be lower than minimum_required_items ' );
48+ }
49+
50+ $ builder ->addEventListener (FormEvents::POST_SUBMIT , function (FormEvent $ event ) {
51+ $ form = $ event ->getForm ();
52+ $ min = $ form ->getConfig ()->getOption ('minimum_required_items ' );
53+ $ max = $ form ->getConfig ()->getOption ('maximum_required_items ' );
54+
55+ if ($ form ->count () < $ min ) {
56+ $ error = new FormError (
57+ message: 'You must add at least ' .$ min .' items ' ,
58+ messageTemplate: 'You must add at least %count% items ' ,
59+ messageParameters: ['%count% ' => $ min ]
60+ );
61+ $ error ->setOrigin ($ form );
62+ $ form ->addError ($ error );
63+ }
64+
65+ if ($ max !== null && $ form ->count () > $ max ) {
66+ $ error = new FormError (
67+ message: 'You can add a maximum of ' .$ max .' items ' ,
68+ messageTemplate: 'You can add a maximum of %count% items ' ,
69+ messageParameters: ['%count% ' => $ max ]
70+ );
71+ $ error ->setOrigin ($ form );
72+ $ form ->addError ($ error );
73+ }
74+ });
75+ }
76+
3177 public function buildView (FormView $ view , FormInterface $ form , array $ options ): void
3278 {
3379 $ view ->vars ['allow_drag_and_drop ' ] = $ options ['allow_drag_and_drop ' ];
3480 $ view ->vars ['add_button_label ' ] = $ options ['add_button_label ' ];
81+ $ view ->vars ['minimum_required_items ' ] = $ options ['minimum_required_items ' ];
82+ $ view ->vars ['maximum_required_items ' ] = $ options ['maximum_required_items ' ];
3583 }
3684}
0 commit comments