Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Custom validation #940

Open
lineke opened this issue Sep 9, 2024 · 0 comments
Open

Custom validation #940

lineke opened this issue Sep 9, 2024 · 0 comments
Labels

Comments

@lineke
Copy link

lineke commented Sep 9, 2024

What question would you like to ask?

Hi,

I am trying to add some custom validation to a specific neo block type attribute. I am using the code below in my validator (based on https://nystudio107.com/blog/custom-matrix-block-validation-rules). I tried several things and it does show a general error, however I would like the block and the specific field to show the error as well (same as with required fields for example). Any pointers on how to achieve this?

public function validateAttribute($model, $attribute)
{
    $builderQuery = $model->$attribute;
    // Iterate through all of the blocks
    $blocks = $builderQuery->getCachedResult() ?? $builderQuery->limit(null)->anyStatus()->all();
    $hasError = false;
    foreach ($blocks as $block) {
        switch ($block->type) {
            case 'articleGroup':
                if ($block->groupType->value === 'video-preview' && $block->articleGroupCollectionSource->value === 'priority') {
                    $hasError = true;
                    $block->addError('groupType', 'Article group type "video-preview" requires collection type "collection"');
                    Craft::$app->getElements()->saveElement($block);
                }
                break;
        }
    }
    $builderQuery->setCachedResult($blocks);
    if ($hasError) {
        $model->addError($attribute, 'One or more blocks have errors');
    }
}

It does get in the if statement, so that works ($hasError is true). It also shows the "One or more blocks have errors", but it just does not show in the block itself. Since we have pages with 40-60 blocks on there, just showing a error on the top and bottom is not really what we want. Is there any way to get the $block->addError part also working so it will show an error in the specific block as well?

@lineke lineke added the question label Sep 9, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant