RushVan's avatar

How do I assign the existing value to a select?

I have a select that is contained in a model bound form. The select is populated by a collection.

    <!-- Home Team Form Input -->
<div class="form-group col-xs-4">
    {!! Form::label('home_team', 'Home:') !!}
    {!! Form::select('home_team', $teams, Input::old('id'), ['class' => 'form-control']) !!}
</div>

I am trying to pre select the option from the value that exists in the model I have bound. I can't seem to get it to work. What am I missing? Thanks.

0 likes
10 replies
tykus's avatar

If you have used form model binding, then there is a precedence to the data that is used in a form input

  • Session Flash Data (Old Input)
  • Explicitly Passed Value
  • Model Attribute Data
{!! Form::select('home_team', $teams, null, ['class' => 'form-control']) !!}
RushVan's avatar

Thanks for the replies but I am still not able to get it to work.

The model binding is working as other fields are populating with the values. For example;

    <!-- Date Form Input -->
<div class="form-group col-xs-4">
    {!! Form::label('date', 'Date:') !!}
    {!! Form::input('date', 'date', null, ['class' => 'form-control']) !!}
</div>

@myrdsrn - I rewatched that cast. JW shows how to use a function to pass the values. I have tried this also but no dice.

In my controller;

    public function getHomeTeam(){
    return $this->game->home_team->first('name');
}

and this in form;

<!-- Home Team Form Input -->
<div class="form-group col-xs-4">
    {!! Form::label('home_team', 'Home:') !!}
    {!! Form::select('home_team', $teams, null, ['class' => 'form-control']) !!}
</div>

Still nothing. Same for all the select fields on the form.

RushVan's avatar

Incidentally, the home_team value will display in a text field, just an issue with select.

jlrdw's avatar

I don't use blade that much, but in a regular script I get that data field and use the selected.

$vseries = $data['row'][0]->series;
echo '<select name="series">';
echo '<option value="">Select...</option>';
foreach ($data['series'] as $series) {  // looping over the list of items to display.
    if ($vseries == $series->seriesname) {   // $vseries is value already stored in database.
        echo "<option value='" . $series->seriesname . "'" . " selected" . ">" . $series->seriesname . "</option>";
    }
    else {
       echo "<option value='" . $series->seriesname . "'" . ">" . $series->seriesname . "</option>"; 
    }
}

One way or the other you have to let your option tag know that a certain item was already stored in the database.
So however this would convert to blade, I don't know, but this is a way of dealing with selects.
And sorry if i mis-understand the question, it sounds like you want existing database field in select.

myrdsrn's avatar

I just made a form with model-binding and did it similar to the below code.

It might be that $teams needs to be a list.

Also you may want to change your username. @Maskers-1 . You can see that the -1 gets left out. Or ask JW to fix change/fix his code.

    $teams = Team::lists('name', 'id');
    // Controller
    public function getGame($id)
    {
        $game = Game::where('id', $id)->firstOrFail();

        $teams = Team::lists('name', 'id'); // <------

        return view('edit.view', compact('game', 'teams'));
    }
    // View
    {!! Form::model($game, ['route' => [ 'postRoute', $game->id ], 'class' => 'form']) !!}

        <div class="form-group{{ $errors->has('home_team') ? ' has-error' : '' }}">

            {!! Form::label('home_team', 'Home Team:') !!}

            {!! Form::select('home_team', $teams, null, [ 'class' => 'form-control']) !!}

        </div>

        <div class="box-footer">
            {!! Form::submit('Update Game', ['class'=>'btn btn-primary']) !!}
        </div>

    {!! Form::close() !!}
tykus's avatar

It is possible that your form select name doesn't match the name of the attribute in the Game model. What is the name of the home_team field in your games database table?

In the tutorial, Jeffrey was creating a virtual attribute in order to pass an array of id's to the view, this is not necessary for a single select as is your use case - there is not pivot.

I also don't know why you are having to fetch the home_team in your controller, and like this:

public function getHomeTeam()
{
    return $this->game->home_team->first('name');
}

If you have the relationships properly setup in your Game model, then this would be unnecessary. Do you have a home_team relationship?

// Game.php
public function home_team()
{
    return $this->belongsTo('App\Team', 'home_team_id'); // I have assumed that 'home_team_id' is the name of the database column
}
RushVan's avatar

Thanks again for the replies. This is very odd.

Here is what I have in the controller;

    public function gamesEdit($id){
    $game = Schedule::where('id', $id)->first();
    $teams = Team::lists('name', 'id');
    $officials = Official::lists('firstName', 'id');
    return view ('admin/gamesEdit', compact('game', 'teams', 'officials'));
}

Schedule is the name of the model that holds the game details.

Here is my form binding;

                        {!! Form::model($game,['method' => 'POST', 'url' => ['team/update', $game->id]]) !!}
                    @include ('gamesForm', ['submitButtonText' => 'Update'])
                    {!! Form::close() !!}

Here is the form partial (just the select in question);

    <!-- Home Team Form Input -->
<div class="form-group col-xs-4">
    {!! Form::label('home_team', 'Home:') !!}
    {!! Form::select('home_team', $teams,  null, ['class' => 'form-control']) !!}
</div>

'home_team' is the name of the col in 'schedules'. If I use 'home_team' for a text input, the binding works. Not so much for a select.

I have also added this to my Schedule class;

   public function home_team()
{
    return $this->belongsTo('App\Schedule', 'home_team'); 
}

Still not working...

tykus's avatar

There's a number of things to pick thru here...

  1. Why is your game edit form POSTing and why does it POST to ...'team/update', $game->id... (this is unrelated to the current issue, but worrying nonetheless)
  2. Because your database column name is home_team, the relationship cannot have the same name - ideally the column should have been called home_team_id; but we can get around this...
  3. The relationship has not been set up correctly, you have effectively, but incorrectly created a self-referencing relationship on the Schedule model. Instead, in your Schedule model, you should be defining the relationship to the App\Team model using home_team column. I had previously assumed that 'home_team_id' is the name of the database column on the schedules table
// Schedule.php
public function hometeam()
{
    return $this->belongsTo('App\Team', 'home_team'); }

So now, a game (instance of Schedule model) will have access to a Team instance through the relationship using $game->hometeam or to the id of the team using $game->home_team.

As for the form binding; having the input name should mean that the current value is being output; for now, just force the current value of home_team in

    <!-- Home Team Form Input -->
<div class="form-group col-xs-4">
    {!! Form::label('home_team', 'Home:') !!}
    {!! Form::select('home_team', $teams,  $game->home_team, ['class' => 'form-control']) !!}
</div>

Please or to participate in this conversation.