jeudi 19 janvier 2017

Laravel5 repopulate old value in view failed

I use the Form:: facade in my view to build two select boxes,the 1st select box is car's brand (Toyota,Ford,BMW ..),the 2nd select box is the models of the brand which I choose(if the 1st is toyota,the camery/pruis.. will show ).

The problem is :When validation fails the page will not repopulate the model's old value, but the brand will repopulate the old value I choose.and if I change the brand again,the model list will show normally. The only difference between brand select box and model select box is model will be reset if I choose the different brand.

(Validation fails because some other textbox is not filled when submit the form).

I tried a lot,when removed the jquery,everything is ok,but I need to make the model list changed with the brand,and show the old value to someone who submit incorrect info. Could I get some idea to fix this problem?

the version info: Laravel5.2 Jquery2.2.3

My view's code is like this:

car_choose.php
Brand:
Model:

and the Jquery to get the 2nd select box's contents:

$(function(){$("select[name=brand_name]").change(function(){
        var brandName= $(this).val();
        //this custom method is get data from database by ajax
        getModelsByBrand(brandName);
    });
}};
function getModelsByBrand(brand){
    $.get(someURL,
            {p_Brand:brand},
            function(data){
                $("select[name=brand_name]").children().remove();
                $.each(data,function(k,v){
                $("select[name=brand_name]").append($('<option></option>').val(k).html(v));
                });
            },
            "JSON");

I use the laravel's form request to do validation:

class RegisterCarRequest extends Request
{
public function authorize()
{
    return true;
}
public function rules()
{
    return [
        'brand_name' => 'required',
        'model_name' => 'required',
        'other_textbox' => 'required',
        ];
}
}

the controller like this:

class CarController extends Controller{
    //initialize the car choose page
    public function index()
    {
        //get the car's brand list from database
        $brands = ...;
        //get the models of one default brand from database
        $models = getModels(the_default_brand);
        return view('car_choose',compact('brands','models'));
    }

    //insert the page info to database
    public function register(RegisterCarRequest $request)
    {
         try{
            //insert the info to database(car's brand,model and others choosed in the page )
            ...
         } catch(Exception $e){
             return Redirect::back()->withErrors($e)->withInput();
         }
    }
}



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2jv3Roh
via IFTTT

Aucun commentaire:

Enregistrer un commentaire