Question

I have a section of a form that dynamically loads different sets of fields based on the user's selection in a control. I'm using a javascript event handler to detect when the selection changes, and using AJAX (with HTML payload) to pull in the proper set of fields.

I would like to be able to use Laravel's Form::getValueAttribute() method to automatically fill in the form fields' values in both the static and dynamic form parts. However, the partial view that is loaded by my AJAX call does not have the same instance of the Form class as the view with my main Form, so I can't simply call getValueAttribute() in the partial.

My thought is to make the AJAX call a POST, and serialize the necessary data (a subset of Input::old() or the model data depending whether the page is loaded as the result of validation errors, or an UPDATE request) to send along with the POST so that the HTML fragment I get back has the values set properly.

Is this the best way to get what I want? If so, does Laravel have any tools to help with the serialization of form data? If not, what might be a better approach?

Était-ce utile?

La solution

I've found an approach I like better. When the view is loaded normally I use AJAX as usual to load the partial. But when the view is loaded for a validation post-back or for editing, I use Laravel's Views' nest method to nest the partial view containing the proper fields directly into the response. The partial then has access to all the Input and error data I need. The user is still able to change the field set as usual but I put up a confirm prompt for them if they have already set some values in a field set they previously selected. If they decide to proceed anyway, the field set is cleared and a new field set is brought in via AJAX as usual.

My code looks something like this:

Controller:

public function newThing() {
  if ( Request::session()->has('errors') ) {
      // this is a validation post-back
      return View::make('thing')
        ->nest('fields', 'fields_partial');
  } else {
      // just a normal unfilled form
      return View::make('thing');
  }
}

public function editThing() {
    return View::make('thing')
        ->nest('fields', 'fields_partial');
}

View: thing.blade.php (just a snip of it)

...
<form>
    ...
    <select id="picker">...</select>
    <div class="sub-fields">
       {{ isset($fields) ? $fields : '' }}
    </div>
    ...
</form>
...
<script>
    $('#picker').change(function() {
        // if any .sub-fields inputs have been changed, get confirmation from the user

        // if user confirms, do ajax stuff to replace .sub-fields contents with new field set
        // otherwise cancel the change
    });
</script>
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top