diff --git a/src/Forms/JsDrivers/AbstractJsDriver.php b/src/Forms/JsDrivers/AbstractJsDriver.php index a864d196ae..ec2e37367a 100644 --- a/src/Forms/JsDrivers/AbstractJsDriver.php +++ b/src/Forms/JsDrivers/AbstractJsDriver.php @@ -4,21 +4,24 @@ use Statamic\Forms\Form; use Statamic\Support\Str; +use Statamic\Tags\Parameters; abstract class AbstractJsDriver implements JsDriver { protected $form; protected $options; + protected $params; /** * Instantiate JS driver. * * @param array $options */ - public function __construct(Form $form, $options = []) + public function __construct(Form $form, $options = [], ?Parameters $params = null) { $this->form = $form; $this->options = $options; + $this->params = $params; if (method_exists($this, 'parseOptions')) { $this->parseOptions($options); diff --git a/src/Forms/JsDrivers/Alpine.php b/src/Forms/JsDrivers/Alpine.php index ddec16e4f0..e69d824f57 100644 --- a/src/Forms/JsDrivers/Alpine.php +++ b/src/Forms/JsDrivers/Alpine.php @@ -25,8 +25,14 @@ protected function parseOptions($options) */ public function addToFormAttributes() { + $extraData = $this->params->pull('x-data', []); + + if (is_string($extraData)) { + $extraData = json_decode($extraData); + } + return [ - 'x-data' => $this->renderAlpineXData($this->getInitialFormData(), $this->scope), + 'x-data' => $this->renderAlpineXData(collect($this->getInitialFormData())->merge($extraData)->all(), $this->scope), ]; } diff --git a/src/Forms/Tags.php b/src/Forms/Tags.php index 1800713d82..d6c9bd59df 100644 --- a/src/Forms/Tags.php +++ b/src/Forms/Tags.php @@ -300,7 +300,7 @@ protected function parseJsParamDriverAndOptions($value, $form) throw new \Exception("Cannot find JS driver class for [{$handle}]!"); } - $instance = new $class($form, $options); + $instance = new $class($form, $options, $this->params); if (! $instance instanceof JsDriver) { throw new \Exception("JS driver must implement [Statamic\Forms\JsDrivers\JsDriver] interface!"); diff --git a/tests/Tags/Form/FormCreateAlpineTest.php b/tests/Tags/Form/FormCreateAlpineTest.php index 4648398e30..8ae48b5231 100644 --- a/tests/Tags/Form/FormCreateAlpineTest.php +++ b/tests/Tags/Form/FormCreateAlpineTest.php @@ -430,6 +430,50 @@ public function it_dynamically_renders_field_with_fallback_to_default_partial_x_ $this->assertFieldRendersHtml('', $config, [], ['js' => 'alpine:my_form']); } + /** @test */ + public function it_merges_any_x_data_passed_to_the_tag() + { + $output = $this->tag('{{ form:contact js="alpine:my_form" \x-data=\'{"extra":"yes"}\' }}{{ /form:contact }}'); + + $expectedXData = $this->jsonEncode([ + 'my_form' => [ + 'name' => null, + 'email' => null, + 'message' => null, + 'fav_animals' => [], + 'fav_colour' => null, + 'fav_subject' => null, + 'winnie' => null, + 'extra' => 'yes', + ], + ]); + + $expected = '