conandor
conandor

Reputation: 3707

How do I assign the existing value to a select?

I have Region as lookup table for Server. There is no issue listing saved entries on the table. However when I edit the entry, the field not pre-select saved value. How can I set it?

-- Table --

Schema::create('servers', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name')->unique();
    $table->integer('region_id')->unsigned();
    $table->timestamps();

Schema::table('servers', function(Blueprint $table) {
    $table->foreign('region_id')->references('id')->on('lookup_regions')->onDelete('restrict')->onUpdate('restrict');
});

Schema::create('lookup_regions', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name')->unique();
    $table->timestamps();
});


-- Model --

class Server extends Model
{
  public function region()
  {
    return $this->hasOne('App\Models\Region', 'id', 'region_id');
  }
}

class Region extends Model
{
  public function server()
  {
    return $this->belongsTo('App\Models\Server', 'id', 'region_id');
  }
}


-- Controller --

class ServerCrudController extends CrudController
{
  $this->crud->addColumn([
    'label' => 'Region',
    'type' => 'select',
    'name' => 'region_id',
    'entity' => 'region',
    'attribute' => 'name',
    'model' => 'App\Models\Region'
  ]);

  $this->crud->addField([
    'label' => 'Region',
    'type' => 'select',
    'name' => 'region_id',
    'entity' => 'region',
    'attribute' => 'name',
    'model' => 'App\Models\Region',
  ]);
}

Upvotes: 0

Views: 82

Answers (2)

conandor
conandor

Reputation: 3707

Placing correct hasOne and belongsTo in model fixed the problem

-- Model --
-- Server.php --

public function provider()
{
    return $this->belongsTo('App\Models\Provider', 'provider_id', 'id');
}

-- Region.php --

public function proxy()
{
    return $this->hasOne('App\Models\Proxy', 'id', 'region_id');
}


-- Controller --
-- ServerCrudController.php --

$this->crud->addField([
    'label' => 'Region',
    'type' => 'select',
    'name' => 'region_id',
    'entity' => 'region',
    'attribute' => 'name',
    'model' => 'App\Models\Region',
]);

Upvotes: 1

kshitij
kshitij

Reputation: 710

Try default attribute e.g.

$this->crud->addColumn([
    'label' => 'Region',
    'type' => 'select_from_array',
    'name' => 'region_id',
    'entity' => 'region',
    'attribute' => 'name',
    'model' => 'App\Models\Region'
    'options'     => [ 
                    'val1' => "value1",
                    'val2' => "value2"
                ],
     'default' => 'val1',
 ]);

Hope this helps.

Upvotes: 0

Related Questions