zofe / rapyd-laravel

deprecated rewritten in rapyd-livewire
MIT License
866 stars 298 forks source link

Any sample of how to code a Cascade Dropdown using DataForm/DataEdit #144

Open mlhk2007 opened 9 years ago

mlhk2007 commented 9 years ago

I'm new to laravel4 and was wondering how to do cascade dropdown using rapyd data form and data edit

kindly appreciate your helps

zofe commented 9 years ago

Hi, if you're new to laravel I strongly suggest you to switch to laravel 5. About cascade dropdown, there is not a ready to use field, but it's possible with some code.

build your form with a filled and an empty dropdown

..
$form->add('mainfield','Main Field','select')
          ->options(array( "first"  => "First Description", "second"  =>"Second Description"));
$form->add('subfield','Sub Field','select') //empty;

make a method in your controller that return options (as json for example)

...
public function getOptions($id) {
        $subfields = Subfield::where('mainfield', '=', $id)->get();
        $options = array();
        foreach ($subfields as $subfield) {
            $options += array($subfield->id => $subfield->name);
        }
        return Response::json($options);
}

then add some javascript to the view that contains the form.

<script type="text/javascript">
    $(document).ready(function() {
        $("#mainfield").change(function() {
            $.getJSON("/myroute/options/" + $("#mainfield").val(), function(data) {
                 $("#subfield").empty();
                $.each(data, function(index, value) {
                    $("#subfield").append('<option value="'+index+'">' +value+'</option>');
                });
               $("#subfield").trigger("change");
            });
        });
    });
</script>
mlhk2007 commented 9 years ago

Ya, after looking around for plugin i notice there are getting more Laravel 5 plugin than 4. Thanks for the advice and the code assist as well.

much appreciated