11<?php namespace Barryvdh \Form \Extension \Session ;
22
3+ use Illuminate \Database \Eloquent \Model ;
4+ use Illuminate \Support \Collection ;
5+ use Symfony \Component \Form \Extension \Core \Type \CheckboxType ;
6+ use Symfony \Component \Form \Extension \Core \Type \ChoiceType ;
37use Symfony \Component \Form \FormEvents ;
48use Symfony \Component \Form \FormEvent ;
59use Illuminate \Session \SessionManager ;
913
1014class SessionListener implements EventSubscriberInterface
1115{
16+ const UNDEFINED = '__BARRYVDH_FORMS_UNDEFINED ' ;
17+
1218 public static function getSubscribedEvents ()
1319 {
1420 return array (
@@ -20,13 +26,17 @@ public function preSet(FormEvent $event)
2026 {
2127 $ form = $ event ->getForm ();
2228 $ rootName = $ form ->getRoot ()->getName ();
29+ $ parent = $ form ->getParent ();
2330
24- if (! $ form -> isRoot () && $ parent = $ form -> getParent ( )) {
31+ if ($ parent && !( $ parent-> getConfig ()-> getType ()-> getInnerType () instanceof ChoiceType )) {
2532 $ name = $ this ->getDottedName ($ form );
2633 $ fullName = $ this ->getFullName ($ rootName , $ name );
2734
35+ $ value = old ($ fullName , static ::UNDEFINED );
36+
2837 // Add input from the previous submit
29- if ($ form ->getName () !== '_token ' && $ value = old ($ fullName )) {
38+ if ($ form ->getName () !== '_token ' && $ value !== static ::UNDEFINED ) {
39+
3040 // Transform back to good data
3141 $ value = $ this ->transformValue ($ event , $ value );
3242
@@ -73,10 +83,26 @@ protected function getFullName($rootName, $dottedName)
7383 protected function transformValue (FormEvent $ event , $ value )
7484 {
7585 // Get all view transformers for this event
76- $ transformers = $ event ->getForm ()->getConfig ()->getViewTransformers ();
86+ $ config = $ event ->getForm ()->getConfig ();
87+
88+ // For Models, skip the transformation, that is done on children
89+ $ dataClass = $ config ->getDataClass ();
90+ if ($ dataClass && is_array ($ value ) && is_a ($ config ->getDataClass (), Model::class, true )) {
91+ return new $ dataClass ;
92+ }
93+
94+ // If array is given, check if it needs to be a Collection
95+ if (is_array ($ value ) && $ event ->getData () instanceof Collection) {
96+ $ value = $ event ->getData ()->make ($ value );
97+ }
7798
7899 // Reverse them all..
79- foreach ($ transformers as $ transformer ) {
100+ foreach ($ config ->getViewTransformers () as $ transformer ) {
101+ $ value = $ transformer ->reverseTransform ($ value );
102+ }
103+
104+ // Map the models to correct values
105+ foreach ($ config ->getModelTransformers () as $ transformer ) {
80106 $ value = $ transformer ->reverseTransform ($ value );
81107 }
82108
0 commit comments