-
Notifications
You must be signed in to change notification settings - Fork 692
Expand file tree
/
Copy pathMatrixController.php
More file actions
249 lines (218 loc) · 8.41 KB
/
MatrixController.php
File metadata and controls
249 lines (218 loc) · 8.41 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
<?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\Element;
use craft\elements\db\EntryQuery;
use craft\elements\ElementCollection;
use craft\elements\Entry;
use craft\errors\InvalidElementException;
use craft\fields\Matrix;
use craft\helpers\ElementHelper;
use craft\helpers\StringHelper;
use craft\web\Controller;
use Throwable;
use yii\web\BadRequestHttpException;
use yii\web\ForbiddenHttpException;
use yii\web\Response;
use yii\web\ServerErrorHttpException;
/**
* Class MatrixController
*
* @author Pixel & Tonic, Inc. <support@pixelandtonic.com>
* @since 5.0.0
*/
class MatrixController extends Controller
{
/**
* @inheritdoc
*/
public function beforeAction($action): bool
{
if (!parent::beforeAction($action)) {
return false;
}
$this->requireCpRequest();
return true;
}
/**
* Renders an updated “Default Table Columns” input for the selected entry types.
*
* @return Response
*/
public function actionDefaultTableColumnOptions(): Response
{
$entryTypeIds = $this->request->getRequiredBodyParam('entryTypeIds');
$entryTypes = [];
$entriesService = Craft::$app->getEntries();
foreach ($entryTypeIds as $entryTypeId) {
$entryType = $entriesService->getEntryTypeById($entryTypeId);
if (!$entryType) {
throw new BadRequestHttpException("Invalid entry type ID: $entryTypeId");
}
$entryTypes[] = $entryType;
}
return $this->asJson([
'options' => Matrix::defaultTableColumnOptions($entryTypes),
]);
}
/**
* Creates a new entry and renders its block UI.
*
* @return Response
*/
public function actionCreateEntry(): Response
{
$fieldId = $this->request->getRequiredBodyParam('fieldId');
$entryTypeId = $this->request->getRequiredBodyParam('entryTypeId');
$ownerId = $this->request->getRequiredBodyParam('ownerId');
$ownerElementType = $this->request->getRequiredBodyParam('ownerElementType');
$siteId = $this->request->getRequiredBodyParam('siteId');
$namespace = $this->request->getRequiredBodyParam('namespace');
$staticEntries = $this->request->getBodyParam('staticEntries', false);
$elementsService = Craft::$app->getElements();
$owner = $elementsService->getElementById($ownerId, $ownerElementType, $siteId);
if (!$owner) {
throw new BadRequestHttpException("Invalid owner ID, element type, or site ID.");
}
$field = $owner->getFieldLayout()?->getFieldById($fieldId);
if (!$field instanceof Matrix) {
throw new BadRequestHttpException("Invalid Matrix field ID: $fieldId");
}
$entryType = Craft::$app->getEntries()->getEntryTypeById($entryTypeId);
if (!$entryType) {
throw new BadRequestHttpException("Invalid entry type ID: $entryTypeId");
}
$site = Craft::$app->getSites()->getSiteById($siteId, true);
if (!$site) {
throw new BadRequestHttpException("Invalid site ID: $siteId");
}
$attributes = [
'siteId' => $siteId,
'uid' => StringHelper::UUID(),
'typeId' => $entryType->id,
'fieldId' => $fieldId,
'primaryOwner' => $owner,
'owner' => $owner,
'slug' => ElementHelper::tempSlug(),
];
$user = static::currentUser();
// duplicate an existing entry?
$sourceId = $this->request->getBodyParam('duplicate');
if ($sourceId) {
$source = Entry::find()
->id($sourceId)
->siteId($siteId)
->drafts(null)
->status(null)
->one();
if (!$source) {
throw new BadRequestHttpException("Invalid source element ID: $sourceId");
}
// set owner so that the canDuplicateAsDraft checks the max entries on the right owner and not only the canonical
$source->setOwner($owner);
if (!$elementsService->canDuplicateAsDraft($source, $user)) {
throw new ForbiddenHttpException('User not authorized to duplicate this element.');
}
try {
$entry = $elementsService->duplicateElement($source, [
...$attributes,
'isProvisionalDraft' => false,
'draftId' => null,
'sortOrder' => null,
]);
} catch (InvalidElementException $e) {
return $this->asFailure(Craft::t('app', 'Couldn’t duplicate {type}.', [
'type' => Entry::lowerDisplayName(),
]));
} catch (Throwable $e) {
throw new ServerErrorHttpException('An error occurred when duplicating the element.', 0, $e);
}
} else {
/** @var Entry $entry */
$entry = Craft::createObject([
'class' => Entry::class,
...$attributes,
]);
if (!$elementsService->canSave($entry, $user)) {
throw new ForbiddenHttpException('User not authorized to create this element.');
}
$entry->setScenario(Element::SCENARIO_ESSENTIALS);
if (!Craft::$app->getDrafts()->saveElementAsDraft($entry, $user->id, markAsSaved: false)) {
return $this->asFailure(StringHelper::upperCaseFirst(Craft::t('app', 'Couldn’t create {type}.', [
'type' => Entry::lowerDisplayName(),
])));
}
}
/** @var EntryQuery|ElementCollection $value */
$value = $owner->getFieldValue($field->handle);
$view = $this->getView();
/** @var Entry[] $entries */
$entries = $value->all();
$html = $view->namespaceInputs(fn() => $view->renderTemplate('_components/fieldtypes/Matrix/block.twig', [
'name' => $field->handle,
'entryTypes' => $field->getEntryTypesForField($entries, $owner),
'entry' => $entry,
'isFresh' => true,
'staticEntries' => $staticEntries,
]), $namespace);
return $this->asJson([
'blockHtml' => $html,
'headHtml' => $view->getHeadHtml(),
'bodyHtml' => $view->getBodyHtml(),
]);
}
/**
* Renders the blocks for newly-created entries.
*
* @return Response
* @since 5.7.0
*/
public function actionRenderBlocks(): Response
{
$entryIds = $this->request->getRequiredBodyParam('entryIds');
$siteId = $this->request->getRequiredBodyParam('siteId');
$namespace = $this->request->getRequiredBodyParam('namespace');
if (empty($entryIds)) {
throw new BadRequestHttpException('Request missing required body param');
}
/** @var Entry[] $entries */
$entries = Entry::find()
->id($entryIds)
->fixedOrder()
->siteId($siteId)
->status(null)
->all();
$elementsService = Craft::$app->getElements();
$view = $this->getView();
$field = null;
$entryTypes = null;
$html = '';
if (!empty($entries)) {
foreach ($entries as $entry) {
$field ??= $entry->getField();
if (!$field instanceof Matrix || $field->id !== $entry->fieldId) {
throw new BadRequestHttpException('Entry must belong to a Matrix field.');
}
$entryTypes ??= $field->getEntryTypesForField($entries, $entry->getOwner());
if (!$elementsService->canView($entry)) {
throw new ForbiddenHttpException('User not authorized to view this element.');
}
$html .= $view->namespaceInputs(fn() => $view->renderTemplate('_components/fieldtypes/Matrix/block.twig', [
'name' => $field->handle,
'entryTypes' => $entryTypes,
'entry' => $entry,
]), $namespace);
}
}
return $this->asJson([
'blockHtml' => $html,
'headHtml' => $view->getHeadHtml(),
'bodyHtml' => $view->getBodyHtml(),
]);
}
}