2017-02-18 70 views
2

我有定義如下(減去非相關的字段爲簡潔)Symfony的形式:使用Vue.js結合輸入字段的值到第二輸入欄

<?php 

namespace AppBundle\Form; 

use AppBundle\Entity\Category; 
use Symfony\Component\Form\AbstractType; 
use Symfony\Component\Form\Extension\Core\Type\TextType; 
use Symfony\Component\Form\FormBuilderInterface; 
use Symfony\Component\OptionsResolver\OptionsResolver; 

class CategoryType extends AbstractType 
{ 
    public function buildForm(FormBuilderInterface $builder, array $options) 
    { 
     $builder 
      ->add('label', TextType::class, [ 
       'label' => 'label.display_name', 
       'attr' => [ 
        'placeholder' => 'placeholder.category_name', 
        'class' => 'label', 
        '@input' => 'vUpdateSlug' 
       ] 
      ]) 
      ->add('slug', TextType::class, [ 
       'label' => 'label.slug', 
       'attr' => [ 
        'class' => 'slug', 
        '@input' => 'vUpdateSlug', 
        ':value' => 'slug' 
       ] 
      ]); 
    } 

    public function configureOptions(OptionsResolver $resolver) 
    { 
     $resolver->setDefaults([ 
      'data_class' => Category::class, 
      'category_id' => null 
     ]); 
    } 
} 

我附上Vue.js指令到input這兩個字段。這個想法是,當有人輸入label字段時,slug字段會自動更新爲labelinput值,並進行一些較小的更改(用連字符替換空格)。我仍然希望用戶能夠根據需要更改slu but,但不能更新標籤。

v-on:input/@input指令行爲的作品,但是,我剛開始用Vue.js和我的感覺執行一個有點麻煩(重複) - 見下文:

new Vue({ 
    delimiters: ['[[', ']]'], 
    el: '#category-form', 
    data: { 
     slug: this.slug = $('[name="category[slug]"]').val() 
    }, 
    ready: function() { 
     this.slug = $('[name="category[slug]"]').val(); 
    }, 
    methods: { 
     vUpdateSlug: function (event) { 
      var str = event.target.value.replace(/[^a-zA-Z0-9 -]/g, '').replace(/\s+/g, '-').toLowerCase(); 
      return this.slug = str; 
     } 
    } 
}); 

是否有更好的解決我的問題?

回答

1

更多的研究和修修補補後,我想出了產生期望的結果如下:

CategoryType

public function buildForm(FormBuilderInterface $builder, array $options) 
{ 
    $builder 
     ->add('label', TextType::class, [ 
      'label' => 'label.display_name', 
      'attr' => [ 
       'placeholder' => 'placeholder.category_name', 
       'class' => 'label', 
       'v-model' => 'label' 
      ] 
     ]) 
     ->add('slug', TextType::class, [ 
      'label' => 'label.slug', 
      'attr' => [ 
       'class' => 'slug', 
       '@input' => 'setSlug', 
       ':value' => 'slug' 
      ] 
     ]); 
} 

Vue腳本

new Vue({ 
    delimiters: ['[[', ']]'], 
    el: '#form-wrapper', 
    data: { 
     label: $('[name="category[label]"]').val(), 
     slug: $('[name="category[slug]"]').val() 
    }, 
    watch: { 
     label: function(newLabel) { 
      this.slug = this.compileSlug(newLabel) 
     } 
    }, 
    methods: { 
     compileSlug: function(input) { 
      return input.replace(/[^a-zA-Z0-9 -]/g, '') 
       .replace(/\s+/g, '-') 
       .toLowerCase(); 
     }, 
     setSlug: function (input) { 
      this.slug = this.compileSlug(input.target.value) 
     } 
    } 
}); 

JSFiddle functioning example

相關問題