1

I have made a registration page, in which a user has to enter the country details. user will enter the country using dropdown which will get the states dropdown list using ajax and same goes for cities list. i am getting the lists but when i am trying to save the form ,it says invalid values on city and state field. Please somebody help me. Thanks. Here is my controller

public function getStateAction(Request $request)
    {               
            $em = $this->getDoctrine()->getManager();
            $data = $request->request->all();   

            $countryId = $data['id'];
            $repository = $em->getRepository('FOSUserBundle:State');
            $query = $repository->createQueryBuilder('p');
            $query->where('p.countryId ='.$countryId);
            $query->orderBy('p.stateName', 'ASC');
            $stateList = $query->getQuery('p')->getResult();
            $html='';

            foreach($stateList as $list){
                $html .="<option value=".$list->getId()." >".$list->getStateName()."</option>";
            }
            return new JsonResponse( $html );       
    }

    public function getCityAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();

            $data = $request->request->all();   

            $stateId = $data['id'];
            $repository = $em->getRepository('FOSUserBundle:City');
            $query = $repository->createQueryBuilder('p');
            $query->where('p.stateId ='.$stateId);
            $query->orderBy('p.cityName', 'ASC');
            $stateList = $query->getQuery('p')->getResult();
            $html='';
            foreach($stateList as $list){
                $html .="<option value=".$list->getId()." >".$list->getCityName()."</option>";
            }
            return new JsonResponse( $html );

    }

This is my Ajax.

{% block javascripts %}   
    <script type = 'text/javascript'>
    $(document).ready(function(){      $("#fos_user_registration_form_country_id").change(function(){
                    $("#fos_user_registration_form_state_id").empty();
                    var countryId = $(this).val();  

                    if(countryId!=0){
                      $.ajax({
                         type: "POST",
                         url: "{{ path('fos_user_registration_country') }}",
                         data: {id: countryId},
                         cache: false,
                         success: function(result){

                           $("#fos_user_registration_form_state_id").append(result);

                         }
                       });
                    }
                    });
                    $("#fos_user_registration_form_state_id").change(function(){
                     var stateId = $(this).val();
                     $("#fos_user_registration_form_city_id").empty();
                     if(stateId!=0){
                     $.ajax ({
                       type:"POST",
                       url: "{{ path('fos_user_registration_state') }}",
                       data: {id: stateId}, 
                       cache: false,
                       success: function(result){
                       $("#fos_user_registration_form_city_id").append(result);
                         }
                       });
                    }
                    else{
                        alert('Please select country');
                        return false;
                    }
                });
        });
        </script>
    {% endblock %}

I have made a registration form, whenever i try to save the details of a person then i get an error that the city_id and state_id have invalid value.

5
  • Just clarifying, is the data type of city_id is IntegerType? You may need to typecast the String value you received from the ajax request to Integer. Commented Dec 28, 2015 at 8:02
  • yeah @WillyPt the value of city_id and stae_id is integer. Commented Dec 28, 2015 at 8:32
  • How does the definition of your form type look like for which you load the additional data? Commented Dec 28, 2015 at 9:30
  • This is the definition of my form type @xabbuh $builder->add('state_id', 'choice', array('label'=>false,'required'=>false, 'choices' => array( "" => 'Select State', ))); $builder->add('city_id', 'choice', array('label'=>false,'required'=>false, 'choices' => array( "" => 'Select City', ))); Commented Dec 28, 2015 at 9:39
  • The issue with that is that the Symfony Form component does not know which choices are valid (only the choices in your front-end are populated, the PHP backend only knows the empty placeholder options, by the way, you should use the placeholder option for that). Commented Dec 28, 2015 at 10:16

2 Answers 2

1

The issue was the stateId and cityId were not going to db. The stateId and cityId are the foreign keys associated with different tables.I was able to overcome this issue by the following code.

public function saveAction(Request $request)
        {           

                $data = $request->request->all();   


                $userManager = $this->container->get('fos_user.user_manager');
                $em = $this->getDoctrine()->getManager();

                $user = $userManager->createUser();

                $countryId =$data['fos_user_registration_form']['country_id'];
                $stateId =$data['fos_user_registration_form']['state_id'];
                $cityId =$data['fos_user_registration_form']['city_id'];

                $country= $this->getDoctrine()->getRepository('FOSUserBundle:Country')->find($countryId);
                $user->setCountry($country);

                $state= $this->getDoctrine()->getRepository('FOSUserBundle:State')->find($stateId);
                $user->setState($state);

                $city= $this->getDoctrine()->getRepository('FOSUserBundle:City')->find($cityId);
                $user->setCity($city);

     /.../
}
Sign up to request clarification or add additional context in comments.

Comments

0

So what I would do to solve the problem is to just populate the state type with the full list of available states (if I understand your current solution correctly, this already happens in AJAX so there's not a real difference for the user). The city list should still be fetched through an AJAX request depending on the selected state.

However, when the form is submitted your need to listen to the form's PRE_SUBMIT event, check the selected value of the state type and populate the city choices based on that value. This way the Form component will be able to properly validate the selected city value.

You can find a similar example can be found in the cookbook: http://symfony.com/doc/current/cookbook/form/dynamic_form_modification.html#cookbook-form-events-submitted-data

1 Comment

i was able to save the data using serialize function i used serialize function to save the form data @xabbuh

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.