Howell21
Howell21

Reputation: 169

Update a section of page from button click in table with laravel

I'm trying to figure out how to have a table where each row has data including a unique ID and an edit button. When the edit button is clicked I would like for another section of the page to show a form to edit the data on that line. So far I have something like:

//linePage.blade.php
<table>
    @foreach($lineList as $line)
    <tr>
       <td>{{ $line->Name }}</td>
       <td><a href="{{ action('Forms@linePage',array('lineSelected'=>$line->Name)) }}" class="btn">Edit</a></td>
    </tr>
    @endforeach
</table>

@if (!empty($lineSelected))
   {{-- show form --}}
@endif

//routes.php
Route::get('/LinePage/{lineSelected?}', 'Forms@linePage');
Route::post('/LinePage/{lineSelected?}', 'Forms@updateLinePage');

//Forms.php
public function linePage($lineSelected = NULL){
   $data = array('lineSelected=>$lineSelected);
   return View::make('Forms\linePage',$data);
}
public function updateLinePage($lineSelected = NULL){
   $data = array('lineSelected=>$lineSelected);
   return View::make('Forms\linePage',$data);
}

This is working for me but I feel like I'm making it more complicated than it needs to be. Am I going about this correctly? Also, I don't like how the address bar shows localhost/LinePage/LineName once the line is selected. Is it possible to somehow hide the data being passed within the page?

Thanks

Upvotes: 1

Views: 3132

Answers (1)

Paul Bele
Paul Bele

Reputation: 1534

a simpler method for this is to use Javascript (and/or) jQuery .

The basic idea is, when you click a button in the table, you will make an ajax request. In that ajax request, you have only the form for that particular lineName . In this way, the page will not be reloaded, and you won't get to change the URL, and it's more fast .

If you choose to do this with jQuery. You will have something like :

//linePage.blade.php
<table>
    @foreach($lineList as $line)
    <tr>
       <td>{{ $line->Name }}</td>
       <td><a href="#" id="line-{{$line->Name}}" class="btn btn-line">Edit</a></td>
    </tr>
    @endforeach
</table>

//in the footer somewhere, after you load query 
<script>
    $(function()
    {

      $('a.btn-line').click(function(event){

        var id = event.target.id;

        fieldName = id.split('-');
        lineName = fieldName[1];

        $.get(
            "{{action('Forms@lineForm'}}?lineName="+lineName,
            function(data){

                $('div#line-form').html(data);

            }
        );

});
</script>

in your routes :

Route::get('/linePage/form/', 'Forms@lineFormPage');

and in your controller, you will return the view with only the form

Maybe this is not the easiest way to do, but you won't need to refresh every time you need to reload the form, + it keeps things more separated

Upvotes: 1

Related Questions