clinvest's avatar

Livewire / Alphine entangle (and default values)

Hi all,

I'm working on a livewire + alpineJs component. I want to first build what I need with alpinejs (pure javascript, no server request needed), then validate my array / send it with livewire.

In my view:

<div x-data="{ content: @entangle('campaignContent') }">
     <x-field.textarea x-model="content.embed_code" />
</div>

In my livewire component:

public $campaignContent = [
     'embed_code' => null
];

Here is the thing, like this, the component & entangle is working fine. However, I would like "not to be obliged to" pre-define my array keys, because for now I just want to do javascript manipulation. If I set my livewire default array like this (no default key), then livewire & alpinejs are not syncing:

public $campaignContent = [];

What if I would like to manipulate the alpinejs array as I want and it update the livewire array (empty one at first)? because I may have big data manipulation:

public $campaignContent = [
      'value_1' => null,
      'value_2' => null,
      ...
      'value_342' => null,
];

and I'm not sure the best way is to pre-set everything? Or I'm doing something wrong?

I precise that I need to entangle it, I cannot update the data on a save button.

Hope my question is understandable :) :)

0 likes
7 replies
webrobert's avatar

I would like "not to be obliged to" pre-define my array keys,

then don't use entangle.

clinvest's avatar

@webrobert agree but I need to sync it with livewire so I can ->validate() the fields on my save() method, and send it to the server / database...

Or... I should find a way to entangle it on save, just before the rest. Hmmm.

webrobert's avatar
Level 51

if you want to build it in alpine thats fine. You can absolutely pass the array into a method to save it.

<button @click="$wire.save(campaignContent)">Save what you built</button>
public function save($campaignContent)
{

	// validate stuff

	dd($campaignContent);
}
1 like
iambateman's avatar

Hey ya'll, I'm late to this but here's what I did, that worked:

<div  x-data="{
        unit: @entangle("block.content.unit"),
        setDefaultUnit() {
            if(!this.unit) {
                this.unit= 'px'
            }
        }
    }" x-init="setDefaultUnit()">

The x-init runs, and checks to see if there's already a value or not. It's pretty verbose, but is another way to think about that!

2 likes

Please or to participate in this conversation.