2amigos / yii2-selectize-widget

Selectize From Brian Reavis Yii2 Widget
Other
73 stars 41 forks source link

Add/edit tags #37

Closed ArneBeise closed 6 years ago

ArneBeise commented 6 years ago

Forgive my lack of experience, but I really need help.

I've managed to make one of my classes (Message) tagable using the examples found. I can add tags to records and they get saved to the DB. I've also managed to display tags for any given record using the following lines in the DetailView::widget displaying the tags in raw text.

[
    'label' => 'Taggz',
    'attribute' => 'tags.tagname',
    'value' => function ($model) {
        $tags = ArrayHelper::map($model->tags, 'id', 'name');
        return implode(', ', $tags);
        },
    'format' => 'raw'
],

In the _form partial I successfully manage to add new tags on existing records. It successfully makes an ajax-request and displays sugestions. Problem is that I don't know how to use the widget in order to display existing tags on a given message. There is neither any tags show, nor an ajax request done upon page load. In _form.php I have the following code:

  <?= $form->field($model, 'tagNames')->widget(SelectizeTextInput::className(), [
      // calls an action that returns a JSON object with matched
      // tags
      'loadUrl' => ['tag/list'],
      'options' => ['class' => 'form-control'],
      //'items'=>$model->tags,
      'clientOptions' => [
          'delimiter' => ',', // <----- ADD THIS! ALSO, USE MASTER AS I MADE A FIX
          'plugins' => ['remove_button'],
          'valueField' => 'name',
          'labelField' => 'name',
          'searchField' => ['name'],
          'create' => true,
      ],
  ])->hint('...') ?>

tagNames is defined as string in the model-class, which is what I believe the widget is expecting, since it throws an error if I feed it with an array.

tonydspaniard commented 6 years ago

If you use the text input, your tagNames attributes, should be imploded in comma separated tags. You could do that on the afterFind event for example.

ArneBeise commented 6 years ago

Great!

This made it work, but is it the way to go?

public function afterFind() {
      $temp = ArrayHelper::map($this->tags, 'id', 'name');
      $this->tagNames = implode(', ', $temp);
    }
tonydspaniard commented 6 years ago

Yes!