80 lines
2.0 KiB
PHP
80 lines
2.0 KiB
PHP
<?php
|
|
|
|
namespace App\Controllers;
|
|
|
|
use App\Models\InstrumentModel;
|
|
|
|
class Instruments extends BaseController
|
|
{
|
|
private function model(): InstrumentModel
|
|
{
|
|
return model(InstrumentModel::class);
|
|
}
|
|
|
|
public function index()
|
|
{
|
|
return view('instruments/index', [
|
|
'title' => 'Instrumenty',
|
|
'instruments' => $this->model()->withStats(),
|
|
]);
|
|
}
|
|
|
|
public function new()
|
|
{
|
|
return view('instruments/form', [
|
|
'title' => 'Nowy instrument',
|
|
'instrument' => null,
|
|
]);
|
|
}
|
|
|
|
public function create()
|
|
{
|
|
return $this->persist(null);
|
|
}
|
|
|
|
public function edit($id)
|
|
{
|
|
$instrument = $this->model()->find((int) $id);
|
|
if (! $instrument) {
|
|
return redirect()->to('/instruments')->with('error', 'Nie znaleziono instrumentu.');
|
|
}
|
|
|
|
return view('instruments/form', [
|
|
'title' => 'Edycja instrumentu',
|
|
'instrument' => $instrument,
|
|
]);
|
|
}
|
|
|
|
public function update($id)
|
|
{
|
|
return $this->persist((int) $id);
|
|
}
|
|
|
|
public function delete($id)
|
|
{
|
|
$id = (int) $id;
|
|
if ($this->model()->hasChildren($id)) {
|
|
return redirect()->to('/instruments')
|
|
->with('error', 'Nie można usunąć instrumentu z operacjami lub wycenami. Najpierw usuń powiązane wpisy.');
|
|
}
|
|
$this->model()->delete($id);
|
|
|
|
return redirect()->to('/instruments')->with('success', 'Instrument usunięty.');
|
|
}
|
|
|
|
private function persist(?int $id)
|
|
{
|
|
$data = ['name' => trim((string) $this->request->getPost('name'))];
|
|
|
|
$model = $this->model();
|
|
$ok = $id !== null ? $model->update($id, $data) : $model->insert($data);
|
|
|
|
if ($ok === false) {
|
|
return redirect()->back()->withInput()
|
|
->with('error', implode(' ', $model->errors()));
|
|
}
|
|
|
|
return redirect()->to('/instruments')->with('success', 'Zapisano instrument.');
|
|
}
|
|
}
|