Skip to content

Commit 2bf0792

Browse files
author
Christian Leucht
committed
Element // Filter- and Validator-callbacks now will get the Element itself as second parameter.
1 parent 16e6b2c commit 2bf0792

File tree

2 files changed

+6
-4
lines changed

2 files changed

+6
-4
lines changed

docs/01 - create elements.md

+4-2
Original file line numberDiff line numberDiff line change
@@ -71,12 +71,14 @@ print_r($text->errors()); // [ 'error-id' => 'Error message' ]
7171
## Adding Validators and Filters
7272
Validation callbacks can be used to validate the Element value, while Filters are being used to sanitize the Element value.
7373

74+
Validators and Filters receive as first parameter the `$value` and as second parameter the `Element $element` itself to have access to attributes, options, ...
75+
7476
```php
7577
use ChriCo\Fields\Element\Element;
7678

7779
$text = (new Element('my-text'))
78-
->withValidator(static function(string $value): ?WP_Error {
79-
if(!is_email($value)){
80+
->withValidator(static function($value, Element $element): ?WP_Error {
81+
if(!is_string($value) && !is_email($value)){
8082
return new WP_Error('my-text', __('Please insert a valid E-Mail address', 'your-textdomain'));
8183
}
8284
return null;

src/Element/Element.php

+2-2
Original file line numberDiff line numberDiff line change
@@ -211,7 +211,7 @@ public function withFilter(callable $callable): Element
211211
public function filter($value)
212212
{
213213
if ($this->filter) {
214-
$value = ($this->filter)($value);
214+
$value = ($this->filter)($value, $this);
215215
}
216216

217217
return $value;
@@ -235,7 +235,7 @@ public function validate(): bool
235235

236236
$valid = true;
237237
if ($this->validator) {
238-
$error = ($this->validator)($value);
238+
$error = ($this->validator)($value, $this);
239239
if (is_wp_error($error)) {
240240
$this->withErrors($error->get_error_messages());
241241
$valid = false;

0 commit comments

Comments
 (0)