Add page option to fieldMethods

Hi! I am using fieldMethods option in my plugin to format price properly.

Like this

'fieldMethods' => [
        'price' => function ($field) {
          return number_format((float)$field->value, 2, ',', '.');
        }
      ]

But I would like to add an option in the panel to choose a custom separator.
Price options are in the page, not in the site blueprint.

I tried this approach, but it doesn’t work:

'fieldMethods' => [
        'price' => function ($site, $field) {
          $shop = $site->children()->findBy('intendedTemplate', 'shop');
          return number_format((float)$field->value, 2, ',', $shop->thousandSeparator());
        }
      ]

Any help is highly appreciated.

I believe the callback function always receives the $field object as first argument.

You could either reference the site object using the site() helper…

// call with $field->price()
'fieldMethods' => [
  'price' => function ($field) {
    $shop = site()->children()->findBy('intendedTemplate', 'shop');
    return number_format((float)$field->value, 2, ',', $shop->thousandSeparator());
  }
]

…or pass the according page to the callback function using an additional parameter:

// call with $field->price($site->children()->findBy('intendedTemplate', 'shop'))
'fieldMethods' => [
  'price' => function ($field, $shop) {
    return number_format((float)$field->value, 2, ',', $shop->thousandSeparator());
  }
]

(untested)

1 Like

You are the man! :grin:

Tried the first solution and it works!

Thank you! :pray: