Skip to content

Commit

Permalink
add an option to populate existing elements via CP
Browse files Browse the repository at this point in the history
  • Loading branch information
RobinSecondred committed Jul 10, 2024
1 parent 1129b91 commit 403249c
Show file tree
Hide file tree
Showing 16 changed files with 338 additions and 88 deletions.
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
# Craft Seeder Changelog

## 5.0.0.2 - 2024-07-10

### added

- added a new bulk-populate option from ElementIndex-Pages

## 5.0.0.1 - 2024-07-08

### added
Expand Down
30 changes: 29 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,4 +87,32 @@ return $config->toArray([], ['fieldsConfig'], false);
Would create a custom callback while seeding fields for entries in the section `news` for fields
`date`, `date2` and `text`.
Text would call the `Faker` function `$faker->text` and `date` and `date2` would call the callback function in order to
populate fields with custom conditions
populate fields with custom conditions

## Populate Elements via CP

### Matrix with unique Value

When an entry has a matrix field you can populate these matrix fields with blocks or with unique values in case their field layout allows it.
For example when a block has a Dropdown field with 3 options and a Lightswitch field (with 2 options) you can generate 6 unique value combinations.
In that case it will automatically create 6 blocks with each combination. Otherwise it will create the number of blocks set in the number field

![seed-matrix-1.png](resources/seed-matrix-1.png)

![seed-matrix-2.png](resources/seed-matrix-2.png)

### Populate fields

Another option is to seed content in general.

![seed-content-1.png](resources/seed-content-1.png)

You can choose which fields should be populated individually and Craft will seed it

![seed-content-2.png](resources/seed-content-2.png)

### Populate multiple elements

The same can be done with multiple elements via element index

![seed-element-index.png](resources/seed-element-index.png)
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "anubarak/craft-seeder",
"description": "Easy entries seeder for Craft CMS",
"version": "5.0.0.1",
"version": "5.0.0.2",
"type": "craft-plugin",
"keywords": [
"craft",
Expand Down
Binary file added resources/seed-content-1.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added resources/seed-content-2.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added resources/seed-element-index.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added resources/seed-matrix-1.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added resources/seed-matrix-2.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
54 changes: 36 additions & 18 deletions src/Seeder.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

namespace anubarak\seeder;

use anubarak\seeder\elements\actions\PopulateAction;
use anubarak\seeder\models\Settings;
use anubarak\seeder\services\Assets;
use anubarak\seeder\services\Entries;
Expand All @@ -16,8 +17,10 @@
use anubarak\seeder\web\assets\cp\SeederAssetBundle;
use craft\base\Element;
use craft\base\Plugin;
use craft\elements\Asset;
use craft\elements\Entry;
use craft\events\DefineHtmlEvent;
use craft\events\RegisterElementActionsEvent;
use craft\fields\Matrix;
use craft\helpers\Html;
use craft\web\UrlManager;
Expand All @@ -28,12 +31,12 @@
*
* @package Seeder
* @since 1.0.0
* @property SeederService seeder
* @property WeederService weeder
* @property EntriesService entries
* @property UsersService users
* @property FieldsService fields
* @property Settings $settings
* @property SeederService seeder
* @property WeederService weeder
* @property EntriesService entries
* @property UsersService users
* @property FieldsService fields
* @property Settings $settings
* @method Settings getSettings()
*/
class Seeder extends Plugin
Expand Down Expand Up @@ -82,12 +85,12 @@ public function init(): void
self::$plugin = $this;

$this->components = [
'seeder' => SeederService::class,
'weeder' => WeederService::class,
'entries' => Entries::class,
'users' => Users::class,
'fields' => Fields::class,
'assets' => Assets::class,
'seeder' => SeederService::class,
'weeder' => WeederService::class,
'entries' => Entries::class,
'users' => Users::class,
'fields' => Fields::class,
'assets' => Assets::class,
];

Event::on(
Expand Down Expand Up @@ -134,9 +137,9 @@ static function(DefineHtmlEvent $event) {
$div = Html::tag('div', '', [
'data-icon' => 'wand-magic-sparkles'
]);
$content = Html::tag('button', $div. 'Seed Content', [
'type' => 'button',
'data' => [
$content = Html::tag('button', $div . 'Seed Content', [
'type' => 'button',
'data' => [
'element-id' => $event->sender->id
],
'class' => [
Expand All @@ -149,10 +152,10 @@ static function(DefineHtmlEvent $event) {
$div = Html::tag('div', '', [
'data-icon' => 'wand-magic-sparkles'
]);
$content .= Html::tag('button', $div. 'Seed Matrix', [
$content .= Html::tag('button', $div . 'Seed Matrix', [
'type' => 'button',

'data' => [
'data' => [
'element-id' => $event->sender->id
],
'class' => [
Expand All @@ -162,13 +165,28 @@ static function(DefineHtmlEvent $event) {
]);
}

$outerDiv = Html::tag('div', $content , [
$outerDiv = Html::tag('div', $content, [
'class' => [
'flex'
]
]);
$event->html = $outerDiv;
}
);


Event::on(
Element::class,
Element::EVENT_REGISTER_ACTIONS,
static function(RegisterElementActionsEvent $event) {
if(!\Craft::$app->getConfig()->getGeneral()->devMode){
return;
}

if(!\Craft::$app->getUser()->getIsAdmin()){
return;
}
$event->actions[] = PopulateAction::class;
}
);
}
Expand Down
99 changes: 75 additions & 24 deletions src/controllers/SeederController.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,16 @@
use anubarak\seeder\records\SeederUserRecord;
use anubarak\seeder\Seeder;
use Craft;
use craft\db\Query;
use craft\db\Table;
use craft\errors\ElementException;
use craft\fieldlayoutelements\CustomField;
use craft\fields\BaseOptionsField;
use craft\fields\Lightswitch;
use craft\fields\Matrix;
use craft\models\EntryType;
use craft\web\Controller;
use yii\web\HttpException;
use yii\web\Response;

/**
Expand Down Expand Up @@ -139,11 +143,36 @@ public function actionElementMatrixModal(): Response
*/
public function actionElementContentModal(): Response
{
$ids = [];
$elementId = $this->request->getQueryParam('elementId');
$element = Craft::$app->getElements()->getElementById($elementId);
if ($elementId) {
$ids = [$elementId];
}
$elementIds = $this->request->getQueryParam('elementIds');
if ($elementIds) {
$ids = $elementIds;
}

if (empty($ids)) {
throw new HttpException(400, 'required ids are missing');
}


$handledLayouts = [];

$data = [];
if ($element->getFieldLayout()) {
foreach ($element->getFieldLayout()->getTabs() as $tab) {
foreach ($this->getElementsByIds($ids) as $element) {
$layout = $element->getFieldLayout();
if (!$layout) {
continue;
}

if (\in_array($layout->id, $handledLayouts, true)) {
continue;
}
$handledLayouts[] = $layout->id;

foreach ($layout->getTabs() as $tab) {
$d = [
'tab' => $tab->name,
'fields' => []
Expand All @@ -159,8 +188,8 @@ public function actionElementContentModal(): Response

return $this->asCpScreen()
->contentTemplate('element-seeder/generateContent.twig', [
'elementId' => $element->id,
'fieldData' => $data,
'elementIds' => $ids,
'fieldData' => $data,
]);
}

Expand All @@ -181,8 +210,8 @@ public function actionElementContentModal(): Response
public function actionGenerateContent(): Response
{
$this->requirePostRequest();
$elementId = $this->request->getBodyParam('elementId');
$element = Craft::$app->getElements()->getElementById($elementId);
$elementIds = $this->request->getBodyParam('elementIds');
$elements = $this->getElementsByIds($elementIds);

$seeder = Seeder::$plugin->getSeeder();

Expand All @@ -193,9 +222,20 @@ public function actionGenerateContent(): Response
$fieldHandles[] = $handle;
}
}
$seeder->populateFields($element, $fieldHandles);
if (!\Craft::$app->getElements()->saveElement($element)) {
return $this->asModelFailure($element, 'Could not save Element due to validation errors');

$transaction = Craft::$app->getDb()->beginTransaction();
$elementService = Craft::$app->getElements();
try {
foreach ($elements as $element) {
$seeder->populateFields($element, $fieldHandles);
if (!$elementService->saveElement($element)) {
throw new ElementException($element, 'Could not save element due to validation errors');
}
}
$transaction->commit();
} catch (\Throwable $throwable) {
$transaction->rollBack();
throw $throwable;
}

return $this->asSuccess('Content generated successfully');
Expand Down Expand Up @@ -256,20 +296,7 @@ public function actionGenerateMatrix(): Response
$nr = $blockTypeConfig['number'] ?? null;
if ($nr) {
for ($x = 0; $x < $nr; $x++) {
// just add random blocks
$f = [];
foreach ($entryType->getFieldLayout()->getCustomFields() as $blockTypeField) {
$v = $seeder->getFieldData($blockTypeField);
if ($v) {
$f[$blockTypeField->handle] = $v;
}
}

$fieldValue['new:' . $i] = [
'type' => $entryType->handle,
'title' => Seeder::$plugin->fields->Title(),
'fields' => $f
];
$fieldValue['new' . $i] = $seeder->getSerializedEntryData($entryType);
$i++;
}
}
Expand Down Expand Up @@ -354,6 +381,7 @@ public function createUniqueBlocks(EntryType $blockType, array $fields, &$i): ar

$fieldValue['new' . $i] = [
'type' => $blockType->handle,
'title' => $blockType->hasTitleField ? Seeder::$plugin->fields->Title() : null,
'fields' => $f
];
$i++;
Expand Down Expand Up @@ -385,4 +413,27 @@ public function getAllCombinations(array $arrays): iterable
}
}
}

/**
* getElementsByIds
*
* @param array $ids
*
* @return \craft\base\ElementInterface[]
* @author Robin Schambach
* @since 09.07.2024
*/
protected function getElementsByIds(array $ids): array
{
// we always use the same element type
$class = (new Query())
->select(['type'])
->from([Table::ELEMENTS])
->where(['id' => $ids[0]])
->scalar();

$query = Craft::$app->getElements()->createElementQuery($class);

return $query->status(null)->id($ids)->all();
}
}
Loading

0 comments on commit 403249c

Please sign in to comment.