Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
{block content}
{control articleForm}
<?php declare(strict_types=1);
namespace App\Presenters;
use Nette\Application\UI\Form;
use Nette\Application\UI\Presenter;
use Nette\Forms\Controls\TextInput;
use Nette\Utils\DateTime;
class ProductArticlePresenter extends Presenter
{
public function actionDefault(string $serialNumber = null)
{
if ($serialNumber) {
if (!($data = $this->loadDataBySN($serialNumber))) {
$this->flashMessage("Serial number $serialNumber is not valid");
$this->redirect('this', [null]);
}
/** @var Form $articleForm */
$articleForm = $this['articleForm'];
$articleForm->setDefaults($data);
}
}
public function createComponentArticleForm()
{
$form = new Form();
$sn = $form->addText('serialNumber', 'SN');
$sn->addRule(function (TextInput $textInput) {
$error = $this->validateSerialNumber($textInput->getValue());
if ($error) {
$textInput->addError($error);
return false;
}
return true;
}, 'Serial number invalid');
$form->addSubmit('loadProductBySN', 'Load by SN');
$form->addSelect('product', 'Product', $this->loadProducts());
$form->addText('configuration', 'Configuration');
$form->addText('manufacturedOn', 'Manufactured date');
$form->addSubmit('save', 'Save article');
$form->onSuccess[] = function (Form $form, $values) {
if ($form->isSubmitted() == $form['loadProductBySN']) {
$this->redirect('this', $values['serialNumber']);
}
$this->saveArticle($form, $values);
};
return $form;
}
private function loadProducts()
{
return [
'p1' => 'Teapot',
'p2' => 'Fridge',
'p3' => 'Pizza oven',
];
}
private function loadDataBySN($serialNumber)
{
if ($this->validateSerialNumber($serialNumber)) {
return null;
}
list($productId, $configuration) = explode(':', $serialNumber);
return [
'serialNumber' => $serialNumber,
'product' => $productId,
'configuration' => $configuration,
'manufacturedOn' => (new DateTime())->modify('-30 days')->format('Y-m-d'),
];
}
/** @return string error message or null */
public function validateSerialNumber($value)
{
$parts = explode(':', $value);
if (count($parts) != 2) {
return 'invalid-sn-format';
}
if (!isset($this->loadProducts()[$parts[0]])) {
return 'unknown-product';
}
return null;
}
private function saveArticle(Form $form, $values)
{
$sn = $values['product'] . ':' . $values['configuration'];
$this->flashMessage("Article with serial number '$sn' saved");
$this->redirect('default', null);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment