phplaravellaravel-livewirelaravel-filament

How to Update Textarea Values in Filament Component with JavaScript?


I want to update the value of textarea with JavaScript but when i submit the words i can only get data that users typed directly inside textarea and not changes by JavaScript
what should i do?
here is my code:

Translate::make()
  ->locales(['fa', 'en'])
  ->columnSpanFull()
  ->columns(2)
  ->schema(fn (string $locale) => [
    Forms\Components\Select::make('variables')
      ->extraAttributes([
        'onchange' => 'insertToTextarea("'.$locale.'")'
      ])
      ->options(NotificationTemplateVariableEnums::class),
    Forms\Components\Textarea::make('template')
      ->required()
      ->columnSpanFull()
      ->reactive(),
  ])
// javascript

function insertToTextarea(locale) {
  const textarea = document.getElementById('data.template.'+locale+'');
  const variable = document.getElementById('data.variables.'+locale+'').value;
  if (!textarea) return;

  const start = textarea.selectionStart;
  const end   = textarea.selectionEnd;

  const value    = textarea.value;
  textarea.value = value.slice(0, start) + variable + value.slice(end);

  textarea.selectionStart = textarea.selectionEnd = start + variable.length;

  textarea.focus();
}
protected function mutateFormDataBeforeSave(array $data): array
    { dd($data);
    }

Solution

  • I updated js script and the issue fixes

    function insertToTextarea(locale) {
    const textarea = document.getElementById('data.template.'+locale+'');
    const variable = document.getElementById('data.variables.'+locale+'').value;
    if (!textarea) return;
    
    
    const start = textarea.selectionStart;
    const end = textarea.selectionEnd;
    
    const value = textarea.value;
    textarea.value = value.slice(0, start) + variable + value.slice(end);
    
    textarea.selectionStart = textarea.selectionEnd = start + variable.length;
    
    
    textarea.focus();
    Livewire.find(document.querySelector('[wire\\:id]').getAttribute('wire:id')).set(`data.template.${locale}`, textarea.value);
    

    }