-
Notifications
You must be signed in to change notification settings - Fork 689
Expand file tree
/
Copy pathEntryTypesController.php
More file actions
416 lines (359 loc) · 15.4 KB
/
EntryTypesController.php
File metadata and controls
416 lines (359 loc) · 15.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
<?php
/**
* @link https://craftcms.com/
* @copyright Copyright (c) Pixel & Tonic, Inc.
* @license https://craftcms.github.io/license/
*/
namespace craft\controllers;
use Craft;
use craft\base\ElementContainerFieldInterface;
use craft\base\FieldInterface;
use craft\base\FieldLayoutElement;
use craft\elements\Entry;
use craft\enums\Color;
use craft\fieldlayoutelements\entries\EntryTitleField;
use craft\helpers\ArrayHelper;
use craft\helpers\Cp;
use craft\helpers\Html;
use craft\helpers\StringHelper;
use craft\models\EntryType;
use craft\models\Section;
use craft\web\Controller;
use yii\web\BadRequestHttpException;
use yii\web\ForbiddenHttpException;
use yii\web\NotFoundHttpException;
use yii\web\Response;
/**
* EntryTypesController handles various entry type-related tasks.
*
* Note that all actions in this controller require administrator access in order to execute.
*
* @author Pixel & Tonic, Inc. <support@pixelandtonic.com>
* @since 5.0.0
*/
class EntryTypesController extends Controller
{
private bool $readOnly;
/**
* @inheritdoc
*/
public function beforeAction($action): bool
{
// All actions require an admin account (but not allowAdminChanges)
$this->requireAdmin(false);
$viewActions = ['edit', 'table-data'];
if (in_array($action->id, $viewActions)) {
// Some actions require admin but not allowAdminChanges
$this->requireAdmin(false);
} else {
// All other actions require an admin & allowAdminChanges
$this->requireAdmin();
}
$this->readOnly = !Craft::$app->getConfig()->getGeneral()->allowAdminChanges;
return parent::beforeAction($action);
}
/**
* Edit an entry type
*
* @param int|null $entryTypeId The entry type’s ID, if any.
* @param EntryType|null $entryType The entry type being edited, if there were any validation errors.
* @return Response
* @throws NotFoundHttpException if the requested entry type cannot be found
*/
public function actionEdit(?int $entryTypeId = null, ?EntryType $entryType = null): Response
{
if ($entryTypeId === null && $this->readOnly) {
throw new ForbiddenHttpException('Administrative changes are disallowed in this environment.');
}
if ($entryTypeId !== null) {
if ($entryType === null) {
$entryType = Craft::$app->getEntries()->getEntryTypeById($entryTypeId);
if (!$entryType) {
throw new NotFoundHttpException('Entry type not found');
}
}
$title = trim($entryType->name) ?: Craft::t('app', 'Edit Entry Type');
} else {
if ($entryType === null) {
$entryType = new EntryType();
}
$title = Craft::t('app', 'Create a new entry type');
}
$fieldLayout = $entryType->getFieldLayout();
if ($entryType->hasTitleField) {
// Ensure the Title field is present
if (!$fieldLayout->isFieldIncluded('title')) {
$fieldLayout->prependElements([new EntryTitleField()]);
}
} else {
// Remove the title field
foreach ($fieldLayout->getTabs() as $tab) {
$elements = array_filter($tab->getElements(), fn(FieldLayoutElement $element) => !$element instanceof EntryTitleField);
$tab->setElements($elements);
}
}
$response = $this->asCpScreen()
->editUrl($entryType->getCpEditUrl())
->title($title)
->addCrumb(Craft::t('app', 'Settings'), 'settings')
->addCrumb(Craft::t('app', 'Entry Types'), 'settings/entry-types')
->contentTemplate('settings/entry-types/_edit.twig', [
'entryTypeId' => $entryTypeId,
'entryType' => $entryType,
'typeName' => Entry::displayName(),
'lowerTypeName' => Entry::lowerDisplayName(),
'readOnly' => $this->readOnly,
]);
if (!$this->readOnly) {
$response
->action('entry-types/save')
->redirectUrl('settings/entry-types')
->addAltAction(Craft::t('app', 'Save and continue editing'), [
'redirect' => 'settings/entry-types/{id}',
'shortcut' => true,
'retainScroll' => true,
]);
if ($entryType->id) {
$response->addAltAction(Craft::t('app', 'Save as a new entry type'), [
'params' => ['saveAsNew' => true],
'redirect' => 'settings/entry-types/{id}',
]);
}
} else {
$response->noticeHtml(Cp::readOnlyNoticeHtml());
}
if ($entryType->id) {
if (!$this->readOnly) {
$response->addAltAction(Craft::t('app', 'Delete'), [
'action' => 'entry-types/delete',
'destructive' => true,
]);
}
$response
->metaSidebarHtml(Cp::metadataHtml([
Craft::t('app', 'ID') => $entryType->id,
Craft::t('app', 'Used by') => function() use ($entryType) {
$usages = $entryType->findUsages();
if (empty($usages)) {
return Html::tag('i', Craft::t('app', 'No usages'));
}
$labels = [];
$items = array_map(function(Section|ElementContainerFieldInterface $usage) use (&$labels) {
$icon = $usage instanceof FieldInterface ? $usage::icon() : $usage->getIcon();
$label = $labels[] = $usage->getUiLabel();
$labelHtml = Html::beginTag('span', [
'class' => ['flex', 'flex-nowrap', 'gap-s'],
]) .
Html::tag('div', Cp::iconSvg($icon), [
'class' => ['cp-icon', 'small'],
]) .
Html::tag('span', Html::encode($label)) .
Html::endTag('span');
return Html::a($labelHtml, $usage->getCpEditUrl());
}, $entryType->findUsages());
// sort by label
array_multisort($labels, SORT_ASC, $items);
return Html::ul($items, [
'encode' => false,
]);
},
]));
}
return $response;
}
/**
* Saves an entry type.
*
* @return Response|null
* @throws BadRequestHttpException
*/
public function actionSave(): ?Response
{
$this->requirePostRequest();
$entriesService = Craft::$app->getEntries();
$entryTypeId = $this->request->getBodyParam('entryTypeId');
if ($entryTypeId) {
$entryType = $entriesService->getEntryTypeById($entryTypeId);
if (!$entryType) {
throw new BadRequestHttpException("Invalid entry type ID: $entryTypeId");
}
$saveAsNew = $this->request->getBodyParam('saveAsNew');
if ($saveAsNew) {
$originalEntryType = $entryType;
$entryType = clone $entryType;
$entryType->id = $entryType->uid = null;
}
} else {
$entryType = new EntryType();
$saveAsNew = false;
}
// Set the simple stuff
$entryType->name = $this->request->getBodyParam('name', $entryType->name);
$entryType->handle = $this->request->getBodyParam('handle', $entryType->handle);
$entryType->description = $this->request->getBodyParam('description', $entryType->description);
$entryType->icon = $this->request->getBodyParam('icon', $entryType->icon);
$color = $this->request->getBodyParam('color', $entryType->color?->value);
$entryType->color = $color && $color !== '__blank__' ? Color::from($color) : null;
$entryType->titleTranslationMethod = $this->request->getBodyParam('titleTranslationMethod', $entryType->titleTranslationMethod);
$entryType->titleTranslationKeyFormat = $this->request->getBodyParam('titleTranslationKeyFormat', $entryType->titleTranslationKeyFormat);
$entryType->titleFormat = $this->request->getBodyParam('titleFormat', $entryType->titleFormat);
$entryType->showSlugField = $this->request->getBodyParam('showSlugField', $entryType->showSlugField);
$entryType->slugTranslationMethod = $this->request->getBodyParam('slugTranslationMethod', $entryType->slugTranslationMethod);
$entryType->slugTranslationKeyFormat = $this->request->getBodyParam('slugTranslationKeyFormat', $entryType->slugTranslationKeyFormat);
$entryType->showStatusField = $this->request->getBodyParam('showStatusField', $entryType->showStatusField);
$entryType->showPostDateField = $this->request->getBodyParam('showPostDateField', $entryType->showPostDateField);
$entryType->showExpiryDateField = $this->request->getBodyParam('showExpiryDateField', $entryType->showExpiryDateField);
// If we're duplicating the entry type and the handle hasn't changed, find a unique one
if ($entryType->handle === ($originalEntryType->handle ?? null)) {
if (preg_match('/^(.*?)(\d+)$/', $entryType->handle, $match)) {
$baseHandle = $match[1];
$i = (int)$match[2];
} else {
$baseHandle = $entryType->handle;
$i = 1;
}
do {
$testHandle = sprintf('%s%s', $baseHandle, ++$i);
if (!$entriesService->getEntryTypeByHandle($testHandle)) {
$entryType->handle = $testHandle;
break;
}
} while (true);
}
// Set the field layout
$fieldLayout = Craft::$app->getFields()->assembleLayoutFromPost();
$fieldLayout->type = Entry::class;
$entryType->setFieldLayout($fieldLayout);
if (!$entryType->validate()) {
if (isset($originalEntryType)) {
$entryType->id = $originalEntryType->id;
$entryType->uid = $originalEntryType->uid;
}
return $this->asModelFailure($entryType, Craft::t('app', 'Couldn’t save entry type.'), 'entryType');
}
if ($saveAsNew) {
$fieldLayout->resetUids();
}
// Save it
$entriesService->saveEntryType($entryType, false);
return $this->asModelSuccess($entryType, Craft::t('app', 'Entry type saved.'), 'entryType');
}
/**
* Deletes an entry type.
*
* @return Response
*/
public function actionDelete(): Response
{
$this->requirePostRequest();
$entryTypeId = $this->request->getBodyParam('entryTypeId') ?? $this->request->getRequiredBodyParam('id');
$entriesService = Craft::$app->getEntries();
$entryType = $entriesService->getEntryTypeById($entryTypeId);
if (!$entryType) {
throw new BadRequestHttpException("Invalid entry type ID: $entryType");
}
if (!$entriesService->deleteEntryType($entryType)) {
return $this->asFailure(Craft::t('app', 'Couldn’t delete “{name}”.', [
'name' => $entryType->getUiLabel(),
]));
}
return $this->asSuccess(Craft::t('app', '“{name}” deleted.', [
'name' => $entryType->getUiLabel(),
]));
}
/**
* Returns data formatted for AdminTable vue component
*
* @return Response
* @throws BadRequestHttpException
*/
public function actionTableData(): Response
{
$this->requireAcceptsJson();
$entriesService = Craft::$app->getEntries();
$page = (int)$this->request->getParam('page', 1);
$limit = (int)$this->request->getParam('per_page', 100);
$searchTerm = $this->request->getParam('search');
$orderBy = match ($this->request->getParam('sort.0.field')) {
'__slot:handle' => 'handle',
default => 'name',
};
$sortDir = match ($this->request->getParam('sort.0.direction')) {
'desc' => SORT_DESC,
default => SORT_ASC,
};
[$pagination, $tableData] = $entriesService->getTableData($page, $limit, $searchTerm, $orderBy, $sortDir);
return $this->asSuccess(data: [
'pagination' => $pagination,
'data' => $tableData,
]);
}
/**
* Renders an entry type’s override settings for an entry type select input.
*
* @return Response
* @since 5.6.0
*/
public function actionRenderOverrideSettings(): Response
{
$entryType = $this->_entryTypeForSelectInput();
$entryType->name = $this->request->getBodyParam('name') ?? $entryType->name;
$entryType->handle = $this->request->getBodyParam('handle') ?? $entryType->handle;
$entryType->description = $this->request->getBodyParam('description') ?? $entryType->description;
$namespace = StringHelper::randomString(10);
$view = Craft::$app->getView();
$html = $view->namespaceInputs(
fn() => $view->renderTemplate('_includes/forms/entry-type-select/selection-settings.twig', [
'entryType' => $entryType,
]),
$namespace,
);
return $this->asJson([
'settingsHtml' => $html,
'namespace' => $namespace,
'headHtml' => $view->getHeadHtml(),
'bodyHtml' => $view->getBodyHtml(),
]);
}
/**
* Validates and returns an entry type’s override settings for an entry type select input.
*
* @return Response
* @since 5.6.0
*/
public function actionApplyOverrideSettings(): Response
{
$entryType = $this->_entryTypeForSelectInput();
$settingsStr = $this->request->getBodyParam('settings');
parse_str($settingsStr, $postedSettings);
$settingsNamespace = $this->request->getRequiredBodyParam('settingsNamespace');
$settings = array_filter(ArrayHelper::getValue($postedSettings, $settingsNamespace, []));
if (!empty($settings)) {
Craft::configure($entryType, $settings);
$entryType->validateHandleUniqueness = false;
if (!$entryType->validate(array_keys($settings))) {
return $this->asModelFailure($entryType, Craft::t('app', 'Couldn’t apply changes.'), 'entryType');
}
}
$chipHtml = Cp::chipHtml($entryType, [
'showHandle' => true,
'showIndicators' => true,
'showDescription' => true,
]);
return $this->asJson([
'config' => $entryType->toArray(['id', 'name', 'handle', 'description']),
'chipHtml' => $chipHtml,
]);
}
private function _entryTypeForSelectInput(): EntryType
{
$id = $this->request->getRequiredBodyParam('id');
$original = Craft::$app->getEntries()->getEntryTypeById($id);
if (!$original) {
throw new BadRequestHttpException("Invalid entry type ID: $id");
}
$entryType = clone $original;
$entryType->original = $original;
return $entryType;
}
}