Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 70 additions & 4 deletions Resources/doc/javascript.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@ Here is a sneak preview of what you'll get.

![tag](https://cloud.githubusercontent.com/assets/179866/7724813/3e1d5b50-fef5-11e4-83f1-e05615518548.png)

#### 1. Controller
#### COOKBOOK - 1

##### 1. Controller

Create an action like the following:

Expand All @@ -24,7 +26,7 @@ Create an action like the following:
}
```

#### 2. Template
##### 2. Template

Create a template like the following:

Expand All @@ -37,7 +39,7 @@ Create a template like the following:
]
```

#### 3. Form
##### 3. Form

Your form needs to know the `tags` route. Here is an example:

Expand Down Expand Up @@ -92,7 +94,7 @@ class TagsTextType extends AbstractType

```

#### 4. Javascript
##### 4. Javascript

Add this snippet to your Javascript:

Expand Down Expand Up @@ -158,5 +160,69 @@ $(document).ready(function () {
}());
});
```
#### ALTERNATE - 2

##### 1. Template

Create a form_row like the following:
(src/AppBundle/Resources/views/post.html.twig)

```twig
...
{{ form_row(form.tagsText, {'attr': {'style': 'display:none !important'}}) }}
...
```

##### 2. Javascript

Add this snippet to your Javascript:
(src/AppBundle/Resources/views/post.html.twig)

```javascript
$(document).ready(function () {
(function () {
var $tagInput = $('input[name$="[tagsText]"]');
$('<select id="tagsText" multiple="multiple"></select>').insertAfter('#post_tagsText');

var selectTags = '#tagsText';
var arrayTags = $tagInput.val().indexOf(",") > -1 ? $tagInput.val().split(',') : $tagInput.val().split(' ').filter(function(item){ return item.trim().length > 0 });

function tags() {
$.each(arrayTags, function (key, value) {
$(selectTags).append($("<option></option>")
.attr("value",value).attr("selected","selected")
.text(value));
});
}
function addTag($tag) {
arrayTags.push($tag);
$tagInput.val(arrayTags);
console.log('tag:'+arrayTags);
}
function removeTag($tag) {
arrayTags = jQuery.grep(arrayTags, function( a ) {
return a !== $tag;
});
$tagInput.val(arrayTags);
console.log('tag:'+arrayTags);
}

$(selectTags).on("select2:select", function (e) { addTag(e.params.data.text); });
$(selectTags).on("select2:unselect", function (e) { removeTag(e.params.data.text); });


if ($tagInput.length > 0) {
tags();
}

$(selectTags).select2({
tags: true,
tokenSeparators: [',', ' '],
placeholder: "Enter Tag"
});
}());
});
```


[← back to documentation index](index.md)