Skip to content

Commit

Permalink
Element // Filter- and Validator-callbacks now will get the Element i…
Browse files Browse the repository at this point in the history
…tself as second parameter.
  • Loading branch information
Chrico committed Jun 27, 2023
1 parent 16e6b2c commit 2bf0792
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 4 deletions.
6 changes: 4 additions & 2 deletions docs/01 - create elements.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,12 +71,14 @@ print_r($text->errors()); // [ 'error-id' => 'Error message' ]
## Adding Validators and Filters
Validation callbacks can be used to validate the Element value, while Filters are being used to sanitize the Element value.

Validators and Filters receive as first parameter the `$value` and as second parameter the `Element $element` itself to have access to attributes, options, ...

```php
use ChriCo\Fields\Element\Element;

$text = (new Element('my-text'))
->withValidator(static function(string $value): ?WP_Error {
if(!is_email($value)){
->withValidator(static function($value, Element $element): ?WP_Error {
if(!is_string($value) && !is_email($value)){
return new WP_Error('my-text', __('Please insert a valid E-Mail address', 'your-textdomain'));
}
return null;
Expand Down
4 changes: 2 additions & 2 deletions src/Element/Element.php
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,7 @@ public function withFilter(callable $callable): Element
public function filter($value)
{
if ($this->filter) {
$value = ($this->filter)($value);
$value = ($this->filter)($value, $this);
}

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

$valid = true;
if ($this->validator) {
$error = ($this->validator)($value);
$error = ($this->validator)($value, $this);
if (is_wp_error($error)) {
$this->withErrors($error->get_error_messages());
$valid = false;
Expand Down

0 comments on commit 2bf0792

Please sign in to comment.