Skip to content

Instantly share code, notes, and snippets.

@janpecha janpecha/SenderFacade.php

Last active Jun 20, 2020
Embed
What would you like to do?
Model with LeanMapper + Nette Forms
<?php
namespace App\Model;
use Libs\IDateTimeFactory;
class SenderFacade
{
/** @var IDateTimeFactory */
private $dateTimeFactory;
/** @var Repository\SenderRepository */
private $senderRepository;
public function __construct(
IDateTimeFactory $dateTimeFactory,
Repository\SenderRepository $senderRepository
)
{
$this->dateTimeFactory = $dateTimeFactory;
$this->senderRepository = $senderRepository;
}
/**
* @return Entity\Sender
* @throws \App\NotFoundException
*/
public function get($id)
{
return $this->senderRepository->get($id);
}
/**
* @return Entity\Sender
*/
public function create($name, $email)
{
$sender = new Entity\Sender;
$sender->name = $name;
$sender->email = $email;
$sender->created = $this->dateTimeFactory->create();
$this->senderRepository->persist($sender);
return $sender;
}
/**
* @return void
*/
public function update(Entity\Sender $sender, $name, $email)
{
$sender->name = $name;
$sender->email = $email;
$sender->updated = $this->dateTimeFactory->create();
$this->senderRepository->persist($sender);
}
}
<?php
namespace App\Admin\Forms;
use App\Forms;
use App\Model;
use App\Model\Entity;
use Nette;
use Nette\Application\UI\Form;
class SenderFormFactory
{
/** @var Model\SenderFacade */
private $senderFacade;
/** @var Forms\FormFactory */
private $formFactory;
public function __construct(
Model\SenderFacade $senderFacade,
Forms\FormFactory $formFactory
)
{
$this->senderFacade = $senderFacade;
$this->formFactory = $formFactory;
}
public function create(Entity\Sender $sender = NULL, $onSuccess)
{
$form = $this->formFactory->create();
$form->addText('name', 'Název')
->setRequired('Zadejte prosím název odesílatele.');
$form->addEmail('email', 'E-mail')
->setRequired('Zadejte prosím e-mail odesílatele.');
$form->addSubmit('save', 'Uložit odesílatele');
if ($sender) {
$form->setDefaults(array(
'name' => $sender->name,
'email' => $sender->email,
));
}
$form->onSuccess[] = function (Form $form, $values) use ($sender, $onSuccess) {
if ($sender) {
$this->senderFacade->update(
$sender,
$values->name,
$values->email
);
} else {
$sender = $this->senderFacade->create(
$values->name,
$values->email
);
}
$onSuccess($sender);
};
return $form;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.