Jump to content

Custom fields validation inside Images field.


PawelGIX
 Share

Recommended Posts

I have some custom fields and I wanted to add validation to them using hooks.
Unfortunately, I cannot access the fields inside the images field.

How to run custom validations on them and return an error when editing the page

I want to add validation to aspect_ratio only when we have a given URL to the video

image.thumb.png.f7f25cd786b343622ca4095006118475.png

I have this much for now but I don't know how to move on.

<?php
wire()->addHookAfter('ProcessPageEdit::processInput', null, 'checkAspectRatio'); 

function checkAspectRatio($event) {
    $form = $event->arguments(0);

    
    // ProcessPageEdit's processInput function may go recursive, so we want to skip
    // the instances where it does that by checking the second argument named "level"
    $level = $event->arguments(1);
    if($level > 0) return;

    
    if($form->get("additional_images")){



    }

}

 

Link to comment
Share on other sites

I was going to suggest using inputfield dependencies as this would be the simplest option but it turns out there's a problem when using these with custom image fields: https://github.com/processwire/processwire-issues/issues/1889

So here's a hook instead. In this demo I want to show an error message if text_2 is left empty when text_1 is populated. You can adapt the names/labels/logic to your case.

$wire->addHookAfter('InputfieldText::processInput', function(HookEvent $event) {
	$inputfield = $event->object;
	$field = $inputfield->hasField;
	$page = $inputfield->hasPage;
	// Only for an inputfield associated with field "text_2"
	// Adjust the field name to suit
	if($field && $field->name === 'text_2') {
		// Only for an inputfield that is associated with a page using the custom image fields template
		// Adjust the template name to suit
		if($page && $page->template == 'field-images_custom') {
			/** @var InputfieldWrapper $wrapper */
			$wrapper = $inputfield->parent;
			// Get sibling inputfield by label because the name will include a random string
			// Adjust inputfield label to suit
			$text_1 = $wrapper->children->get('label="Text 1"');
			// Show an error message if text_2 is left empty when text_1 is populated
			if($text_1 && $text_1->value && !$inputfield->value) {
				$inputfield->error('A value for "Text 2" is required when "Text 1" is populated.');
			}
		}
	}
});

image.png.8a22c012a115e926f1dc55405ce2d355.png

  • Like 1
  • Thanks 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...