Skip to content

Commit

Permalink
Create full CRUD
Browse files Browse the repository at this point in the history
  • Loading branch information
michielgerritsen committed Jun 26, 2024
1 parent 29817d1 commit fcc86bb
Show file tree
Hide file tree
Showing 32 changed files with 726 additions and 35 deletions.
33 changes: 33 additions & 0 deletions assets/stubs/Block/Adminhtml/ModelName/Edit/BackButton.php.stub
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php
namespace {{VendorName}}\{{ModuleName}}\Block\Adminhtml\{{ModelName}}\Edit;

use Magento\Framework\View\Element\UiComponent\Control\ButtonProviderInterface;

/**
* Class BackButton
*/
class BackButton extends GenericButton implements ButtonProviderInterface
{
/**
* @return array
*/
public function getButtonData()
{
return [
'label' => __('Back'),
'on_click' => sprintf("location.href = '%s';", $this->getBackUrl()),
'class' => 'back',
'sort_order' => 10
];
}

/**
* Get URL for back (reset) button
*
* @return string
*/
public function getBackUrl()
{
return $this->getUrl('*/*/');
}
}
39 changes: 39 additions & 0 deletions assets/stubs/Block/Adminhtml/ModelName/Edit/DeleteButton.php.stub
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?php
namespace {{VendorName}}\{{ModuleName}}\Block\Adminhtml\{{ModelName}}\Edit;

use Magento\Framework\View\Element\UiComponent\Control\ButtonProviderInterface;

/**
* Class DeleteButton
*/
class DeleteButton extends GenericButton implements ButtonProviderInterface
{
/**
* @inheritDoc
*/
public function getButtonData()
{
$data = [];
if ($this->getId()) {
$data = [
'label' => __('Delete Item'),
'class' => 'delete',
'on_click' => 'deleteConfirm(\'' . __(
'Are you sure you want to do this?'
) . '\', \'' . $this->getDeleteUrl() . '\', {"data": {}})',
'sort_order' => 20,
];
}
return $data;
}

/**
* URL to send delete requests to.
*
* @return string
*/
public function getDeleteUrl()
{
return $this->getUrl('*/*/delete', ['{{ FieldIndex }}' => $this->getId()]);
}
}
57 changes: 57 additions & 0 deletions assets/stubs/Block/Adminhtml/ModelName/Edit/GenericButton.php.stub
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
<?php
namespace {{VendorName}}\{{ModuleName}}\Block\Adminhtml\{{ModelName}}\Edit;

use Magento\Backend\Block\Widget\Context;
use {{VendorName}}\{{ModuleName}}\Api\{{ModelName}}RepositoryInterface;
use Magento\Framework\Exception\NoSuchEntityException;

class GenericButton
{
/**
* @var Context
*/
protected $context;

/**
* @var {{ModelName}}RepositoryInterface
*/
protected $repository;

/**
* @param Context $context
* @param {{ModelName}}RepositoryInterface $repository
*/
public function __construct(
Context $context,
{{ModelName}}RepositoryInterface $repository
) {
$this->context = $context;
$this->repository = $repository;
}

public function getId(): ?int
{
$id = $this->context->getRequest()->getParam('{{ IndexField }}');
if (!$id) {
return null;
}

try {
return $this->repository->get($id)->getId();
} catch (NoSuchEntityException $e) {
}
return null;
}

/**
* Generate url by route and parameters
*
* @param string $route
* @param array $params
* @return string
*/
public function getUrl($route = '', $params = [])
{
return $this->context->getUrlBuilder()->getUrl($route, $params);
}
}
39 changes: 39 additions & 0 deletions assets/stubs/Block/Adminhtml/ModelName/Edit/SaveButton.php.stub
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?php
namespace {{VendorName}}\{{ModuleName}}\Block\Adminhtml\{{ModelName}}\Edit;

use Magento\Framework\View\Element\UiComponent\Control\ButtonProviderInterface;
use Magento\Ui\Component\Control\Container;

class SaveButton extends GenericButton implements ButtonProviderInterface
{
/**
* Get button data
*
* @return array
*/
public function getButtonData()
{
return [
'label' => __('Save'),
'class' => 'save primary',
'data_attribute' => [
'mage-init' => [
'buttonAdapter' => [
'actions' => [
[
'targetName' => '{{ FormName }}.{{ FormName }}',
'actionName' => 'save',
'params' => [
true,
[
'back' => 'continue'
]
]
]
]
]
]
],
];
}
}
16 changes: 11 additions & 5 deletions assets/stubs/Controller/Adminhtml/ModelName/Delete.php.stub
Original file line number Diff line number Diff line change
Expand Up @@ -10,26 +10,32 @@ use {{ VendorName }}\{{ ModuleName }}\Model\ResourceModel\{{ ModelName }} as Mod
use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Backend\Model\View\Result\Redirect;
use Magento\Framework\App\Action\HttpGetActionInterface;
use Magento\Framework\App\Action\HttpPostActionInterface;
use Magento\Framework\Controller\ResultFactory;

class Delete extends Action implements HttpGetActionInterface
class Delete extends Action implements HttpPostActionInterface
{
public const ADMIN_RESOURCE = '{{ VendorName }}_{{ ModuleName }}::{{ ModelName }}_delete';

private {{ ModelName }}Factory $modelFactory;
private ModelResource $modelResource;

public function __construct(
Context $context,
private readonly ModelFactory $modelFactory,
private readonly ModelResource $modelResource
{{ ModelName }}Factory $modelFactory,
ModelResource $modelResource
) {
parent::__construct($context);

$this->modelFactory = $modelFactory;
$this->modelResource = $modelResource;
}

/** @thows \Exception */
public function execute(): Redirect
{
try {
$id = $this->getRequest()->getParam('id');
$id = $this->getRequest()->getParam('{{ IndexField }}');
/** @var {{ ModelName }} $model */
$model = $this->modelFactory->create();
$this->modelResource->load($model, $id);
Expand Down
48 changes: 48 additions & 0 deletions assets/stubs/Controller/Adminhtml/ModelName/Save.php.stub
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<?php
declare(strict_types=1);

namespace {{ VendorName }}\{{ ModuleName }}\Controller\Adminhtml\{{ ModelName }};

use Magento\Framework\App\Action\HttpPostActionInterface;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Controller\Result\RedirectFactory;
use Magento\Framework\Message\ManagerInterface;
use {{ VendorName }}\{{ ModuleName }}\Api\{{ ModelName }}RepositoryInterface;
use {{ VendorName }}\{{ ModuleName }}\Model\{{ ModelName }}Factory;

class Save implements HttpPostActionInterface
{
const ADMIN_RESOURCE = '{{ VendorName }}_{{ ModuleName }}::{{ ModelName }}_save';

public function __construct(
private readonly RequestInterface $request,
private readonly ManagerInterface $messageManager,
private readonly RedirectFactory $resultRedirectFactory,
private readonly {{ ModelName }}RepositoryInterface $repository,
private readonly {{ ModelName }}Factory $modelFactory,
) {}

public function execute()
{
$id = $this->request->getParam('{{ IndexField }}');
$data = $this->request->getPostValue();

$model = $this->modelFactory->create();
if ($id) {
$model = $this->repository->get((int)$id);
}

$model->setData($data);

try {
$model = $this->repository->save($model);
$this->messageManager->addSuccessMessage(__('You saved the item.'));
} catch (\Exception $e) {
$this->messageManager->addErrorMessage($e->getMessage());
return $this->resultRedirectFactory->create()->setPath('*');
}

return $this->resultRedirectFactory->create()
->setPath('*/*/edit', ['entity_id' => $model->getId()]);
}
}
32 changes: 32 additions & 0 deletions assets/stubs/Model/ModelName/DataProvider.php.stub
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php
namespace {{VendorName}}\{{ModuleName}}\Model\{{ModelName}};

use Magento\Ui\DataProvider\AbstractDataProvider;
use {{VendorName}}\{{ModuleName}}\Model\ResourceModel\{{ ModelName }}\CollectionFactory;

class DataProvider extends AbstractDataProvider
{
public function __construct(
$name,
$primaryFieldName,
$requestFieldName,
CollectionFactory $collectionFactory,
array $meta = [],
array $data = []
) {
parent::__construct($name, $primaryFieldName, $requestFieldName, $meta, $data);
$this->collection = $collectionFactory->create();
}

public function getData(): array
{
$data = parent::getData();

$items = [];
foreach ($data['items'] as $item) {
$items[$item['entity_id']] = $item;
}

return $items;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ class {{ ModelName }}Repository implements {{ ModelName }}RepositoryInterface
if (!${{ VariableName }}->getId()) {
throw new NoSuchEntityException(__('{{ ModelName }} with id "%1" does not exist.', $id));
}
return ${{ VariableName }}->getDataModel();
return ${{ VariableName }};
}

/**
Expand Down
98 changes: 98 additions & 0 deletions assets/stubs/Ui/Component/Listing/Column/Actions.php.stub
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
<?php
namespace {{VendorName}}\{{ModuleName}}\Ui\Component\Listing\Column;

use Magento\Framework\UrlInterface;
use Magento\Framework\View\Element\UiComponent\ContextInterface;
use Magento\Framework\View\Element\UiComponentFactory;
use Magento\Ui\Component\Listing\Columns\Column;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\Escaper;

class Actions extends Column
{
public const URL_PATH_EDIT = '{{{ BaseRoute }}}edit';
public const URL_PATH_DELETE = '{{{ BaseRoute }}}delete';

/**
* @var UrlInterface
*/
protected $urlBuilder;

/**
* @var Escaper
*/
private $escaper;

/**
* @param ContextInterface $context
* @param UiComponentFactory $uiComponentFactory
* @param UrlInterface $urlBuilder
* @param array $components
* @param array $data
*/
public function __construct(
ContextInterface $context,
UiComponentFactory $uiComponentFactory,
UrlInterface $urlBuilder,
array $components = [],
array $data = []
) {
$this->urlBuilder = $urlBuilder;
parent::__construct($context, $uiComponentFactory, $components, $data);
}

/**
* @inheritDoc
*/
public function prepareDataSource(array $dataSource)
{
if (isset($dataSource['data']['items'])) {
foreach ($dataSource['data']['items'] as & $item) {
if (isset($item['{{ IndexField }}'])) {
$item[$this->getData('name')] = [
'edit' => [
'href' => $this->urlBuilder->getUrl(
static::URL_PATH_EDIT,
[
'{{ IndexField }}' => $item['{{ IndexField }}']
]
),
'label' => __('Edit')
],
'delete' => [
'href' => $this->urlBuilder->getUrl(
static::URL_PATH_DELETE,
[
'{{ IndexField }}' => $item['{{ IndexField }}']
]
),
'label' => __('Delete'),
'confirm' => [
'title' => __('Delete item'),
'message' => __('Are you sure you want to delete this record?')
],
'post' => true
],
];
}
}
}

return $dataSource;
}

/**
* Get instance of escaper
*
* @return Escaper
* @deprecated 101.0.7
*/
private function getEscaper()
{
if (!$this->escaper) {
// phpcs:ignore Magento2.PHP.AutogeneratedClassNotInConstructor
$this->escaper = ObjectManager::getInstance()->get(Escaper::class);
}
return $this->escaper;
}
}
Loading

0 comments on commit fcc86bb

Please sign in to comment.