Skip to content

Commit

Permalink
add unique field handling
Browse files Browse the repository at this point in the history
  • Loading branch information
RobinSecondred committed Jul 12, 2024
1 parent 403249c commit fae273b
Show file tree
Hide file tree
Showing 16 changed files with 660 additions and 46 deletions.
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
# Craft Seeder Changelog

## 5.0.0.3 - 2024-07-12

### added

- enhance unique field handling
- added an event to register unique fields

## 5.0.0.2 - 2024-07-10

### added
Expand Down
96 changes: 95 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -115,4 +115,98 @@ You can choose which fields should be populated individually and Craft will seed

The same can be done with multiple elements via element index

![seed-element-index.png](resources/seed-element-index.png)
![seed-element-index.png](resources/seed-element-index.png)

## Events

### Register Field Type Event

to include custom fields, you can use the `anubarak\seeder\events\RegisterFieldTypeEvent` event.

```php
\yii\base\Event::on(
\anubarak\seeder\services\SeederService::class,
\anubarak\seeder\services\SeederService::REGISTER_FIELD_TYPES,
static function(\anubarak\seeder\events\RegisterFieldTypeEvent $event){
$event->types['my\field\Class'] = MyCustomField::class;
}
);
```
My Custom field could then look like the following
```php
use craft\base\ElementInterface;
use craft\base\FieldInterface;
use anubarak\seeder\services\fields\BaseField

class PlainText extends BaseField
{
/**
* @inheritDoc
*/
public function generate(\craft\fields\PlainText|FieldInterface $field, ElementInterface $element = null)
{
if(!$field->multiline){
return $this->factory->text($field->charLimit ?: 200);
}

return $this->factory->realText($field->charLimit ?: 200);
}
}
```

### Register Unique Field Event

To register a unique field that should be able to the unique matrix fields

```php
\yii\base\Event::on(
\anubarak\seeder\services\UniqueFields::class,
\anubarak\seeder\services\UniqueFields::EVENT_REGISTER_UNIQUE_FIELDS,
static function(\anubarak\seeder\events\RegisterUniqueFieldEvent $event){
$event->fields[] = MyCustomUniqueField::class;
}
);
```
```php
class DropdownUniqueField implements UniqueFieldInterface
{
/**
* @param \craft\fields\BaseOptionsField $field
*
* @inheritDoc
*/
public function getDescription(Field $field): string
{
$options = [];
foreach ($field->options as $option) {
$options[] = '<code>' . $option['value'] . '</code>';
}

return 'Options: ' . join(' | ', $options);
}

/**
* @param BaseOptionsField $field
*
* @inheritDoc
*/
public function getValues(Field $field): array
{
$options = [];
foreach ($field->options as $option) {
$options[] = $option['value'];
}

return $options;
}

/**
* @inheritDoc
*/
public function getFieldClass(): string
{
return BaseOptionsField::class;
}
}
```
You can take a look at the existing unique Fields
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.2",
"version": "5.0.0.3",
"type": "craft-plugin",
"keywords": [
"craft",
Expand Down
18 changes: 10 additions & 8 deletions src/Seeder.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
use anubarak\seeder\services\fields\Fields;
use anubarak\seeder\services\SeederService;
use anubarak\seeder\services\Entries as EntriesService;
use anubarak\seeder\services\UniqueFields;
use anubarak\seeder\services\Users;
use anubarak\seeder\services\Weeder as WeederService;
use anubarak\seeder\services\Users as UsersService;
Expand Down Expand Up @@ -85,12 +86,13 @@ 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,
UniqueFields::class => UniqueFields::class
];

Event::on(
Expand Down Expand Up @@ -179,11 +181,11 @@ static function(DefineHtmlEvent $event) {
Element::class,
Element::EVENT_REGISTER_ACTIONS,
static function(RegisterElementActionsEvent $event) {
if(!\Craft::$app->getConfig()->getGeneral()->devMode){
if (!\Craft::$app->getConfig()->getGeneral()->devMode) {
return;
}

if(!\Craft::$app->getUser()->getIsAdmin()){
if (!\Craft::$app->getUser()->getIsAdmin()) {
return;
}
$event->actions[] = PopulateAction::class;
Expand Down
44 changes: 22 additions & 22 deletions src/controllers/SeederController.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,17 @@
use anubarak\seeder\records\SeederEntryRecord;
use anubarak\seeder\records\SeederUserRecord;
use anubarak\seeder\Seeder;
use anubarak\seeder\services\UniqueFields;
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\BaseRelationField;
use craft\fields\Lightswitch;
use craft\fields\Matrix;
use craft\fields\PlainText;
use craft\models\EntryType;
use craft\web\Controller;
use yii\web\HttpException;
Expand Down Expand Up @@ -97,18 +100,23 @@ public function actionClean()
* @author Robin Schambach
* @since 20/12/2023
*/
public function actionElementMatrixModal(): Response
public function actionElementMatrixModal(UniqueFields $uniqueService): Response
{
$elementId = $this->request->getQueryParam('elementId');
$element = Craft::$app->getElements()->getElementById($elementId);
$matrixFields = [];

foreach ($element->getFieldLayout()?->getCustomFields() as $field) {
if ($field instanceof Matrix) {
foreach ($field->getEntryTypes() as $entryType) {
$subFields = [];
foreach ($entryType->getFieldLayout()->getCustomFields() as $entryTypeField) {
if ($entryTypeField instanceof BaseOptionsField || $entryTypeField instanceof Lightswitch) {
$subFields[] = $entryTypeField;
$uniqueField = $uniqueService->getUniqueFieldByType($entryTypeField::class);
if ($uniqueField) {
$subFields[] = [
'field' => $entryTypeField,
'description' => $uniqueField->getDescription($entryTypeField)
];
}
}

Expand Down Expand Up @@ -138,6 +146,7 @@ public function actionElementMatrixModal(): Response
* actionElementContentModal
*
* @return \yii\web\Response
* @throws \yii\web\HttpException
* @author Robin Schambach
* @since 08.07.2024
*/
Expand Down Expand Up @@ -256,7 +265,7 @@ public function actionGenerateContent(): Response
* @author Robin Schambach
* @since 19/12/2023
*/
public function actionGenerateMatrix(): Response
public function actionGenerateMatrix(UniqueFields $uniqueService): Response
{
$this->requirePostRequest();
$elementId = $this->request->getBodyParam('elementId');
Expand Down Expand Up @@ -287,7 +296,7 @@ public function actionGenerateMatrix(): Response
}

if ($fields) {
$uniqueBlocks = $this->createUniqueBlocks($entryType, $fields, $i);
$uniqueBlocks = $this->createUniqueBlocks($entryType, $fields, $uniqueService, $i);
foreach ($uniqueBlocks as $key => $block) {
$fieldValue[$key] = $block;
}
Expand Down Expand Up @@ -335,25 +344,14 @@ public function actionGenerateMatrix(): Response
* @author Robin Schambach
* @since 20/12/2023
*/
public function createUniqueBlocks(EntryType $blockType, array $fields, &$i): array
public function createUniqueBlocks(EntryType $blockType, array $fields, UniqueFields $uniqueFields, &$i): array
{
$uniques = [];
foreach ($fields as $field) {
switch (true) {
case $field instanceof Lightswitch:
$uniques[$field->handle] = [
true,
false
];
break;
case $field instanceof BaseOptionsField:
$options = [];
foreach ($field->options as $option) {
$options[] = $option['value'];
}

$uniques[$field->handle] = $options;
break;
$uniqueField = $uniqueFields->getUniqueFieldByType($field::class);
if($uniqueField !== null){
$uniques[$field->handle] = $uniqueField->getValues($field);
}
}

Expand All @@ -363,13 +361,15 @@ public function createUniqueBlocks(EntryType $blockType, array $fields, &$i): ar
foreach ($allCombinations as $key => $combination) {
$f = [];
foreach ($fields as $j => $field) {
$f[$field->handle] = $combination[$j];
$v = is_callable($combination[$j]) ? $combination[$j]() : $combination[$j];

$f[$field->handle] = $v;
}

// add the rest of the fields
foreach ($blockType->getFieldLayout()->getCustomFields() as $customField) {
// skip if it is already there
if (isset($f[$customField->handle])) {
if (array_key_exists($customField->handle, $f)) {
continue;
}

Expand Down
29 changes: 29 additions & 0 deletions src/events/RegisterUniqueFieldEvent.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php
/**
* Craft CMS Plugins
*
* Created with PhpStorm.
*
* @link https://github.com/Anubarak/
* @email [email protected]
* @copyright Copyright (c) 2024 Robin Schambach|Secondred Newmedia GmbH
*/

namespace anubarak\seeder\events;

use craft\base\Event;

/**
* Class RegisterUniqueFieldEvent
*
* @package anubarak\seeder\events
* @since 10.07.2024
* @author by Robin Schambach
*/
class RegisterUniqueFieldEvent extends Event
{
/**
* @var \anubarak\seeder\services\unique\UniqueFieldInterface[] $fields
*/
public array $fields = [];
}
3 changes: 2 additions & 1 deletion src/services/SeederService.php
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ public function __construct(array $config = [])

/**
* @param ElementInterface $element
* @param array $fieldHandles
*
* @return \craft\base\ElementInterface
* @throws \yii\base\ExitException
Expand Down Expand Up @@ -119,7 +120,7 @@ public function populateFields(ElementInterface $element, array $fieldHandles =
} catch (FieldNotFoundException $e) {
if (Seeder::$plugin->getSettings()->debug) {
Craft::dd($e);
} else {
} elseif (Craft::$app->getRequest()->getIsConsoleRequest()) {
echo 'Fieldtype not supported:' . get_class($field) . "\n";
}
}
Expand Down
Loading

0 comments on commit fae273b

Please sign in to comment.