Skip to content

Commit

Permalink
wip (#1)
Browse files Browse the repository at this point in the history
  • Loading branch information
sertxudev authored Jul 6, 2022
1 parent 5f2972f commit f1f7c7b
Showing 1 changed file with 34 additions and 4 deletions.
38 changes: 34 additions & 4 deletions src/Components/Combobox.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,13 @@ abstract class Combobox extends Component {
/** If set to false, will not keep the selection, useful if you want to make a list. */
public bool $keepSelection = true;

/**
* The initial selection of the combobox.
*
* @var Model|null
*/
public ?Model $init = null;

/**
* The columns that should be obtained.
*
Expand Down Expand Up @@ -70,13 +77,27 @@ abstract class Combobox extends Component {
*/
public bool $selectOnlyResult = true;

/**
* The properties that should be reset once a selection is made.
*
* @var array
*/
protected array $resets = [
//
];

/**
* Mount the component.
*
* @return void
*/
public function mount(): void {
if (!$this->label) $this->label = Str::headline($this->name);

if ($this->init && !$this->selected && !$this->search && $this->keepSelection) {
if (!$this->init instanceof $this->model) return;
$this->selectModel($this->init, true);
}
}

/**
Expand All @@ -94,11 +115,12 @@ public function render(): View {
* Select the given model.
*
* @param mixed $id
* @param bool $silent
* @return void
*/
public function select(mixed $id): void {
public function select(mixed $id, bool $silent = false): void {
$model = $this->model::query()->find($id, $this->columns);
if ($model) $this->selectModel($model);
if ($model) $this->selectModel($model, $silent);
}

/**
Expand Down Expand Up @@ -150,15 +172,23 @@ protected function queryModel(): Collection {
* Set as selected the provided model and emit the selected event.
*
* @param mixed $model
* @param bool $silent
* @return void
*/
protected function selectModel(mixed $model): void {
protected function selectModel(mixed $model, bool $silent = false): void {
if ($this->keepSelection) {
$this->selected = $model;
$this->search = $model->{$this->labelColumn};
}

$this->emitUp("selected-$this->name", $model);
if (!$silent) {
$this->emitUp("selected-$this->name", $model);

// Prevent the component from resetting all the properties if array is empty
if (!empty($this->resets)) {
$this->reset($this->resets);
}
}
}

/**
Expand Down

0 comments on commit f1f7c7b

Please sign in to comment.