Просмотр исходного кода

Evolution #59: Modifier le script tags en ajax

bastien 13 лет назад
Родитель
Сommit
8b4385e223
28 измененных файлов: 353 добавлений и 218 удалений
  1. 1 11
      src/Muzich/CoreBundle/Controller/CoreController.php
  2. 66 6
      src/Muzich/CoreBundle/Controller/SearchController.php
  3. 0 1
      src/Muzich/CoreBundle/ElementFactory/ElementManager.php
  4. 1 0
      src/Muzich/CoreBundle/Entity/Element.php
  5. 1 0
      src/Muzich/CoreBundle/Entity/User.php
  6. 2 15
      src/Muzich/CoreBundle/Form/Element/ElementAddForm.php
  7. 2 6
      src/Muzich/CoreBundle/Form/Group/GroupForm.php
  8. 2 13
      src/Muzich/CoreBundle/Form/Search/ElementSearchForm.php
  9. 2 6
      src/Muzich/CoreBundle/Form/Tag/TagFavoritesForm.php
  10. 1 1
      src/Muzich/CoreBundle/Repository/ElementRepository.php
  11. 18 0
      src/Muzich/CoreBundle/Repository/TagRepository.php
  12. 5 5
      src/Muzich/CoreBundle/Repository/UserRepository.php
  13. 8 0
      src/Muzich/CoreBundle/Resources/config/routing.yml
  14. 1 3
      src/Muzich/CoreBundle/Resources/views/Element/form.add.html.twig
  15. 2 5
      src/Muzich/CoreBundle/Resources/views/SearchElement/form.html.twig
  16. 6 8
      src/Muzich/CoreBundle/Resources/views/Tag/tagFavoritesForm.html.twig
  17. 19 16
      src/Muzich/CoreBundle/Resources/views/Tag/tagsPrompt.html.twig
  18. 14 4
      src/Muzich/CoreBundle/Searcher/ElementSearcher.php
  19. 2 0
      src/Muzich/CoreBundle/Validator/TagsValidator.php
  20. 8 10
      src/Muzich/CoreBundle/lib/Controller.php
  21. 23 29
      src/Muzich/GroupBundle/Controller/DefaultController.php
  22. 1 1
      src/Muzich/GroupBundle/Resources/views/Default/myList.html.twig
  23. 3 5
      src/Muzich/GroupBundle/Resources/views/Form/form.html.twig
  24. 0 1
      src/Muzich/HomeBundle/Controller/HomeController.php
  25. 1 7
      src/Muzich/HomeBundle/Controller/ShowController.php
  26. 25 20
      src/Muzich/UserBundle/Controller/UserController.php
  27. 59 0
      web/bundles/muzichcore/js/muzich.js
  28. 80 45
      web/js/tags/jquery.tagBox.js

+ 1 - 11
src/Muzich/CoreBundle/Controller/CoreController.php Просмотреть файл

@@ -155,16 +155,7 @@ class CoreController extends Controller
155 155
     }
156 156
     
157 157
     $element = new Element();
158
-    $form = $this->createForm(
159
-      new ElementAddForm(),
160
-      $element,
161
-      array(
162
-       'tags'   => $this->getTagsArray(),
163
-        // Ligne non obligatoire (cf. verif du contenu du form -> ticket)
164
-       //'groups' => $this->getGroupsArray()
165
-      )
166
-    );
167
-    
158
+    $form = $this->getAddForm($element);
168 159
     
169 160
     $form->bindRequest($this->getRequest());
170 161
     if ($form->isValid())
@@ -224,7 +215,6 @@ class CoreController extends Controller
224 215
         $add_form = $this->getAddForm();
225 216
 
226 217
         return $this->render('MuzichHomeBundle:Home:index.html.twig', array(
227
-          'tags'             => $this->getTagsArray(),
228 218
           'search_tags_id'   => $search_object->getTags(),
229 219
           'user'             => $this->getUser(),
230 220
           'add_form'         => $add_form->createView(),

+ 66 - 6
src/Muzich/CoreBundle/Controller/SearchController.php Просмотреть файл

@@ -7,6 +7,7 @@ use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
7 7
 
8 8
 use Muzich\CoreBundle\Searcher\ElementSearcher;
9 9
 use Muzich\CoreBundle\Form\Search\ElementSearchForm;
10
+use Symfony\Component\HttpFoundation\Response;
10 11
 
11 12
 class SearchController extends Controller
12 13
 {
@@ -21,11 +22,7 @@ class SearchController extends Controller
21 22
     $request = $this->getRequest();
22 23
     $search_object = $this->getElementSearcher();
23 24
     
24
-    $search_form = $this->createForm(
25
-      new ElementSearchForm(), 
26
-      $search_object->getParams(),
27
-      array('tags' => $this->getTagsArray())
28
-    );
25
+    $search_form = $this->getSearchForm($search_object);
29 26
     
30 27
     if ($request->getMethod() == 'POST')
31 28
     {
@@ -34,7 +31,15 @@ class SearchController extends Controller
34 31
       if ($search_form->isValid())
35 32
       {
36 33
         // On met a jour l'objet avec les nouveaux paramétres saisie dans le form
37
-        $search_object->update($search_form->getData());
34
+        $data = $search_form->getData();
35
+        
36
+        // Le formulaire nous permet de récupérer uniquement les ids.
37
+        // On va donc chercher les name en base pour le passer a l'objet
38
+        // ElementSearch
39
+        $data['tags'] = $this->getDoctrine()->getRepository('MuzichCoreBundle:Tag')
40
+          ->getTagsForElementSearch(json_decode($data['tags'], true));
41
+        
42
+        $search_object->update($data);
38 43
         // Et on met a jour la "mémoire" de la recherche
39 44
         $this->setElementSearcherParams($search_object->getParams());
40 45
       }
@@ -50,4 +55,59 @@ class SearchController extends Controller
50 55
     }
51 56
   }
52 57
   
58
+  /**
59
+   *
60
+   * @param string $string_search 
61
+   */
62
+  public function searchTagAction($string_search)
63
+  {
64
+    if ($this->getRequest()->isXmlHttpRequest())
65
+    {
66
+      $tags = $this->getDoctrine()->getEntityManager()->createQuery("
67
+        SELECT t.name FROM MuzichCoreBundle:Tag t
68
+        WHERE UPPER(t.name) LIKE :str
69
+        ORDER BY t.name ASC"
70
+      )->setParameter('str', '%'.strtoupper($string_search).'%')
71
+      ->getScalarResult()
72
+      ;
73
+      
74
+      $tags_response = array();
75
+      foreach ($tags as $tag)
76
+      {
77
+        $tags_response[] = $tag['name'];
78
+      }
79
+      
80
+      $response = new Response(json_encode($tags_response));
81
+      $response->headers->set('Content-Type', 'application/json; charset=utf-8');
82
+      return $response;
83
+    }
84
+    
85
+    throw $this->createNotFoundException('Cette ressource n\'est pas accessible');
86
+  }
87
+  
88
+  /**
89
+   *
90
+   * @param type $string_search
91
+   * @return Response 
92
+   */
93
+  public function searchTagIdAction($string_search)
94
+  {
95
+    if ($this->getRequest()->isXmlHttpRequest())
96
+    {
97
+      $tag_id = $this->getDoctrine()->getEntityManager()->createQuery("
98
+        SELECT t.id FROM MuzichCoreBundle:Tag t
99
+        WHERE t.name = :str
100
+        ORDER BY t.name ASC"
101
+      )->setParameter('str', $string_search)
102
+      ->getSingleScalarResult()
103
+      ;
104
+      
105
+      $response = new Response(json_encode($tag_id));
106
+      $response->headers->set('Content-Type', 'application/json; charset=utf-8');
107
+      return $response;
108
+    }
109
+    
110
+    throw $this->createNotFoundException('Cette ressource n\'est pas accessible');
111
+  }
112
+  
53 113
 }

+ 0 - 1
src/Muzich/CoreBundle/ElementFactory/ElementManager.php Просмотреть файл

@@ -79,7 +79,6 @@ class ElementManager
79 79
   {
80 80
     $this->element->setOwner($owner);
81 81
     $this->element->setTagsWithIds($this->em, $this->element->getTags());
82
-    //$this->setGroup();
83 82
     $this->determineType();
84 83
     $this->proceedExtraFields();
85 84
   }

+ 1 - 0
src/Muzich/CoreBundle/Entity/Element.php Просмотреть файл

@@ -354,6 +354,7 @@ class Element
354 354
   public function setTagsWithIds(EntityManager $em, $ids)
355 355
   {
356 356
     $this->tags = null;
357
+    $ids = json_decode($ids);
357 358
     if (count($ids))
358 359
     {
359 360
       $tags = $em->getRepository('MuzichCoreBundle:Tag')->findByIds($ids)->execute();

+ 1 - 0
src/Muzich/CoreBundle/Entity/User.php Просмотреть файл

@@ -392,6 +392,7 @@ class User extends BaseUser
392 392
    */
393 393
   public function updateTagsFavoritesById(EntityManager $em, $ids)
394 394
   {
395
+    $ids = json_decode($ids);
395 396
     $ids_to_add = $ids;
396 397
     
397 398
     // Pour chacun des tags favoris 

+ 2 - 15
src/Muzich/CoreBundle/Form/Element/ElementAddForm.php Просмотреть файл

@@ -17,20 +17,7 @@ class ElementAddForm extends AbstractType
17 17
       'required' => true,
18 18
     ));
19 19
         
20
-    $builder->add('tags', 'choice', array(
21
-      'choices'           => $options['tags'],
22
-      'expanded'          => true,
23
-      'multiple'          => true
24
-    ));
25
-    
26
-//    $options['groups'][''] = '';
27
-//    $builder->add('group', 'choice', array(
28
-//      'choices'           => $options['groups'],
29
-//      'expanded'          => false,
30
-//      'multiple'          => false,
31
-//      'required'          => false
32
-//    ));
33
-    
20
+    $builder->add('tags', 'hidden');    
34 21
   }
35 22
 
36 23
   public function getName()
@@ -43,7 +30,7 @@ class ElementAddForm extends AbstractType
43 30
     return array(
44 31
       'name' => '',
45 32
       'url' => '',
46
-      'tags' => array(),
33
+      'tags' => '',
47 34
       //'groups' => array(),
48 35
       'data_class' => 'Muzich\CoreBundle\Entity\Element'
49 36
     );

+ 2 - 6
src/Muzich/CoreBundle/Form/Group/GroupForm.php Просмотреть файл

@@ -21,11 +21,7 @@ class GroupForm extends AbstractType
21 21
       'required' => false,
22 22
     ));
23 23
         
24
-    $builder->add('tags', 'choice', array(
25
-      'choices'           => $options['tags'],
26
-      'expanded'          => true,
27
-      'multiple'          => true
28
-    ));
24
+    $builder->add('tags', 'hidden');
29 25
   }
30 26
 
31 27
   public function getName()
@@ -38,7 +34,7 @@ class GroupForm extends AbstractType
38 34
     return array(
39 35
       'name' => '',
40 36
       'open' => true,
41
-      'tags' => array(),
37
+      'tags' => '',
42 38
       'data_class' => 'Muzich\CoreBundle\Entity\Group'
43 39
     );
44 40
   }

+ 2 - 13
src/Muzich/CoreBundle/Form/Search/ElementSearchForm.php Просмотреть файл

@@ -18,17 +18,7 @@ class ElementSearchForm extends AbstractType
18 18
       'required' => true,
19 19
     ));
20 20
         
21
-    $builder->add('tags', 'choice', array(
22
-      'choices'           => $options['tags'],
23
-      'expanded'          => true,
24
-      'multiple'          => true
25
-    ));
26
-        
27
-//    $builder->add('groups', 'choice', array(
28
-//      'choices'           => $options['groups'],
29
-//      'expanded'          => true,
30
-//      'multiple'          => true
31
-//    ));
21
+    $builder->add('tags', 'hidden');
32 22
   }
33 23
 
34 24
   public function getName()
@@ -39,8 +29,7 @@ class ElementSearchForm extends AbstractType
39 29
   public function getDefaultOptions(array $options)
40 30
   {
41 31
     return array(
42
-      'tags' => array(),
43
-//      'groups' => array(),
32
+      'tags' => ''
44 33
     );
45 34
   }
46 35
 }

+ 2 - 6
src/Muzich/CoreBundle/Form/Tag/TagFavoritesForm.php Просмотреть файл

@@ -9,11 +9,7 @@ class TagFavoritesForm extends AbstractType
9 9
 {
10 10
   public function buildForm(FormBuilder $builder, array $options)
11 11
   {    
12
-    $builder->add('tags', 'choice', array(
13
-      'choices'           => $options['tags'],
14
-      'expanded'          => true,
15
-      'multiple'          => true
16
-    ));
12
+    $builder->add('tags', 'hidden');
17 13
   }
18 14
 
19 15
   public function getName()
@@ -24,7 +20,7 @@ class TagFavoritesForm extends AbstractType
24 20
   public function getDefaultOptions(array $options)
25 21
   {
26 22
     return array(
27
-      'tags' => array(),
23
+      'tags' => '',
28 24
     );
29 25
   }
30 26
 }

+ 1 - 1
src/Muzich/CoreBundle/Repository/ElementRepository.php Просмотреть файл

@@ -46,7 +46,7 @@ class ElementRepository extends EntityRepository
46 46
     $join_tags  = '';
47 47
     if (count(($tags = $searcher->getTags())))
48 48
     {
49
-      foreach ($tags as $tag_id)
49
+      foreach ($tags as $tag_id => $tag_name)
50 50
       {
51 51
         // LEFT JOIN car un element n'est pas obligatoirement lié a un/des tags
52 52
         $join_tags = " LEFT JOIN e_.tags t_";

+ 18 - 0
src/Muzich/CoreBundle/Repository/TagRepository.php Просмотреть файл

@@ -41,5 +41,23 @@ class TagRepository extends EntityRepository
41 41
     ")->setParameter('tids', $ids);
42 42
   }
43 43
   
44
+  public function getTagsForElementSearch($ids)
45
+  {
46
+    $tags = array();
47
+    foreach ($this->getEntityManager()
48
+      ->createQuery('
49
+        SELECT t.id, t.name FROM MuzichCoreBundle:Tag t
50
+        WHERE t.id IN (:ids)
51
+        ORDER BY t.name ASC'
52
+      )
53
+      ->setParameter('ids', $ids)
54
+      ->getArrayResult() as $tag)
55
+    {
56
+      $tags[$tag['id']] = $tag['name'];
57
+    }
58
+    
59
+    return $tags;
60
+  }
61
+  
44 62
 }
45 63
   

+ 5 - 5
src/Muzich/CoreBundle/Repository/UserRepository.php Просмотреть файл

@@ -70,12 +70,12 @@ class UserRepository extends EntityRepository
70 70
    * @param int $limit
71 71
    * @return array 
72 72
    */
73
-  public function getTagIdsFavorites($user_id, $limit = null)
73
+  public function getTagsFavorites($user_id, $limit = null)
74 74
   {
75
-    $tag_ids = array();
75
+    $tags = array();
76 76
     foreach ($this->getEntityManager()
77 77
       ->createQuery('
78
-        SELECT t.id FROM MuzichCoreBundle:Tag t 
78
+        SELECT t.id, t.name FROM MuzichCoreBundle:Tag t 
79 79
         JOIN t.users_favorites uf
80 80
         JOIN uf.user u
81 81
         WHERE u.id = :uid
@@ -85,9 +85,9 @@ class UserRepository extends EntityRepository
85 85
       ->setMaxResults($limit)
86 86
       ->getArrayResult() as $tag)
87 87
     {
88
-      $tag_ids[] = $tag['id'];
88
+      $tags[$tag['id']] = $tag['name'];
89 89
     }
90
-    return $tag_ids;
90
+    return $tags;
91 91
   }
92 92
   
93 93
   /**

+ 8 - 0
src/Muzich/CoreBundle/Resources/config/routing.yml Просмотреть файл

@@ -11,3 +11,11 @@ follow:
11 11
 element_add:
12 12
   pattern:  /element/add/{group_slug}
13 13
   defaults: { _controller: MuzichCoreBundle:Core:elementAdd, group_slug: null }
14
+
15
+search_tag:
16
+  pattern: /search/tag/{string_search}
17
+  defaults: { _controller: MuzichCoreBundle:Search:searchTag, string_search: null }
18
+  
19
+search_tag_ig_by_name:
20
+  pattern: /search/tagid/{string_search}
21
+  defaults: { _controller: MuzichCoreBundle:Search:searchTagId, string_search: null }

+ 1 - 3
src/Muzich/CoreBundle/Resources/views/Element/form.add.html.twig Просмотреть файл

@@ -14,10 +14,8 @@
14 14
   {{ form_widget(form.url) }}
15 15
 </div>
16 16
 
17
-{% if  app.environment != 'test' %}
18 17
   {% include "MuzichCoreBundle:Tag:tagsPrompt.html.twig" with { 'form_name': form_name } %}
19
-{% else %}
18
+
20 19
   {{ form_row(form.tags) }}
21
-{% endif %}
22 20
 
23 21
 {{ form_row(form._token) }}

+ 2 - 5
src/Muzich/CoreBundle/Resources/views/SearchElement/form.html.twig Просмотреть файл

@@ -4,12 +4,9 @@
4 4
 
5 5
   {{ form_row(search_form.network) }}
6 6
 
7
-  {% if  app.environment != 'test' %}
8
-    {% include "MuzichCoreBundle:Tag:tagsPrompt.html.twig" with { 'form_name': form_name } %}
9
-  {% else %}
10
-    {{ form_row(search_form.tags) }}
11
-  {% endif %}
7
+  {% include "MuzichCoreBundle:Tag:tagsPrompt.html.twig" with { 'form_name': form_name } %}
12 8
   
9
+  {{ form_row(search_form.tags) }}
13 10
   {{ form_row(search_form._token) }}
14 11
 
15 12
   <input type="submit" />

+ 6 - 8
src/Muzich/CoreBundle/Resources/views/Tag/tagFavoritesForm.html.twig Просмотреть файл

@@ -2,14 +2,12 @@
2 2
   
3 3
   {{ form_errors(form) }}
4 4
 
5
-  {% if  app.environment != 'test' %}
6
-    {% include "MuzichCoreBundle:Tag:tagsPrompt.html.twig" with { 
7
-      'form_name'   : form_name,
8
-      'search_tags' : favorite_tags_id
9
-    } %}
10
-  {% else %}
11
-    {{ form_row(form.tags) }}
12
-  {% endif %}
5
+  {% include "MuzichCoreBundle:Tag:tagsPrompt.html.twig" with { 
6
+    'form_name'   : form_name,
7
+    'search_tags' : favorite_tags_id
8
+  } %}
9
+  
10
+  {{ form_row(form.tags) }}
13 11
 
14 12
   {{ form_row(form._token) }}
15 13
 

+ 19 - 16
src/Muzich/CoreBundle/Resources/views/Tag/tagsPrompt.html.twig Просмотреть файл

@@ -6,22 +6,15 @@
6 6
 </div>
7 7
 
8 8
 <script language="javascript" type="text/javascript">
9
-
10
-  if (typeof(taglist) == 'undefined')
11
-  {
12
-    taglist = new Array({{ tags|length }});
13
-    {% for i, tag in tags %}taglist[{{ i }}] = "{{ tag }}"; {% endfor %}
14
-  }
15 9
   
16 10
   var taginit = new Array();
17 11
   {% if search_tags is defined %}
18
-    {% for tid in search_tags %}
19
-      taginit[{{ tid }}] = {{ tid }};
12
+    {% for tid, tname in search_tags %}
13
+      taginit[{{ loop.index0 }}] = {"id":"{{ tid }}", "name":"{{ tname }}"};
20 14
     {% endfor %}
21 15
   {% endif %}
22 16
   
23 17
   var options = new Array();
24
-  options.tag_values = taglist;
25 18
   options.form_name  = "{{ form_name }}";
26 19
   options.tag_init   = taginit;
27 20
   
@@ -45,13 +38,23 @@
45 38
   // The autocomplete for the last tagbox
46 39
   $("#tags_prompt_{{ form_name }} ul.tagbox li.input input").autocomplete({
47 40
       source: function(req, responseFn) {
48
-          var sstr = $.trim(req.term);
49
-          var re = $.ui.autocomplete.escapeRegex(sstr);
50
-          var matcher = new RegExp(re, "i" );
51
-          var a = $.grep( taglist, function(item,index){
52
-              return matcher.test(item);
53
-          });
54
-          responseFn( a );
41
+        
42
+        // ici il faut faire une ajax q pour obtenir la liste
43
+        // ou a est un tableau de strings
44
+        
45
+        $.getJSON('/app_dev.php/fr/search/tag/'+req.term, function(data) {
46
+          responseFn( data );
47
+        });
48
+        
49
+          //var sstr = $.trim(req.term);
50
+          //var re = $.ui.autocomplete.escapeRegex(sstr);
51
+          //var matcher = new RegExp(re, "i" );
52
+          //var a = $.grep( taglist, function(item,index){
53
+          //    return matcher.test(item);
54
+          //});
55
+          //console.debug(a);
56
+          
57
+          //responseFn( a );
55 58
       },
56 59
       minLength: 2,
57 60
       select: function(e, ui) {

+ 14 - 4
src/Muzich/CoreBundle/Searcher/ElementSearcher.php Просмотреть файл

@@ -99,11 +99,11 @@ class ElementSearcher extends Searcher implements SearcherInterface
99 99
    * 
100 100
    * @return array 
101 101
    */
102
-  public function getParams()
102
+  public function getParams($tags_string = false)
103 103
   {
104 104
     return array(
105 105
       'network'  => $this->getNetwork(),
106
-      'tags'     => $this->getTags(),
106
+      'tags'     => $this->getTags($tags_string),
107 107
       'count'    => $this->getCount(),
108 108
       'user_id'  => $this->getUserId(),
109 109
       'group_id' => $this->getGroupId(),
@@ -116,9 +116,19 @@ class ElementSearcher extends Searcher implements SearcherInterface
116 116
     return $this->network;
117 117
   }
118 118
   
119
-  public function getTags()
119
+  public function getTags($tags_string = false)
120 120
   {
121
-    return $this->tags;
121
+    if (!$tags_string)
122
+    {
123
+      return $this->tags;
124
+    }
125
+    
126
+    $ids = array();
127
+    foreach ($this->tags as $id => $name)
128
+    {
129
+      $ids[] = $id;
130
+    }
131
+    return json_encode($ids);
122 132
   }
123 133
   
124 134
   public function getCount()

+ 2 - 0
src/Muzich/CoreBundle/Validator/TagsValidator.php Просмотреть файл

@@ -18,6 +18,8 @@ class TagsValidator extends ConstraintValidator
18 18
   
19 19
   public function isValid($value, Constraint $constraint)
20 20
   {
21
+    $value = json_decode($value);
22
+    
21 23
     if (count($value))
22 24
     {
23 25
       if (array_diff($value, array_unique($value)))

+ 8 - 10
src/Muzich/CoreBundle/lib/Controller.php Просмотреть файл

@@ -54,7 +54,7 @@ class Controller extends BaseController
54 54
       $this->ElementSearcher = new ElementSearcher();
55 55
       $this->ElementSearcher->init(array(
56 56
         'tags' => $this->getDoctrine()->getRepository('MuzichCoreBundle:User')
57
-          ->getTagIdsFavorites(
57
+          ->getTagsFavorites(
58 58
             $this->getUserId(),
59 59
             $this->container->getParameter('search_default_favorites_tags_count')
60 60
           ),
@@ -157,6 +157,8 @@ class Controller extends BaseController
157 157
    */
158 158
   protected function getTagsArray($force_refresh = false)
159 159
   {
160
+    throw new \Exception("Cette méthode ne doit plus être utilisé.");
161
+    
160 162
     if (!count(self::$tags) || $force_refresh)
161 163
     {
162 164
       return self::$tags = $this->getDoctrine()->getRepository('MuzichCoreBundle:Tag')->getTagsArray();
@@ -242,21 +244,17 @@ class Controller extends BaseController
242 244
   {
243 245
     return $this->createForm(
244 246
       new ElementSearchForm(), 
245
-      $search_object->getParams(),
246
-      array(
247
-        'tags' => $this->getTagsArray()
248
-      )
247
+      $search_object->getParams(true),
248
+      array()
249 249
     );
250 250
   }
251 251
   
252
-  protected function getAddForm()
252
+  protected function getAddForm($element = array())
253 253
   {
254 254
     return $this->createForm(
255 255
       new ElementAddForm(),
256
-      array(),
257
-      array(
258
-        'tags' => $this->getTagsArray()
259
-      )
256
+      $element,
257
+      array()
260 258
     );
261 259
   }
262 260
   

+ 23 - 29
src/Muzich/GroupBundle/Controller/DefaultController.php Просмотреть файл

@@ -12,6 +12,14 @@ use Muzich\CoreBundle\Managers\GroupManager;
12 12
 class DefaultController extends Controller
13 13
 {
14 14
   
15
+  protected function getGroupForm($group)
16
+  {
17
+    return $this->createForm(
18
+      new GroupForm(), 
19
+      $group
20
+    );
21
+  }
22
+  
15 23
   /**
16 24
    * Page listant les groupes possédés par l'utilisateur. Comporte egallement
17 25
    * un formulaire pour ajouter un groupe.
@@ -25,15 +33,12 @@ class DefaultController extends Controller
25 33
     )));
26 34
     
27 35
     $new_group = new Group();
28
-    $form_new = $this->createForm(
29
-      new GroupForm(), 
30
-      $new_group,
31
-      array('tags' => $this->getTagsArray())
32
-    );
36
+    $form_new = $this->getGroupForm($new_group);
33 37
     
34 38
     return array(
35
-      'groups'   => $user->getGroupsOwned(),
36
-      'form_new' => $form_new->createView()
39
+      'groups'        => $user->getGroupsOwned(),
40
+      'form_new'      => $form_new->createView(),
41
+      'form_new_name' => $form_new->getName()
37 42
     );
38 43
   }
39 44
   
@@ -63,11 +68,7 @@ class DefaultController extends Controller
63 68
     
64 69
     $new_group = new Group();
65 70
     $new_group->setOwner($user);
66
-    $form_new = $this->createForm(
67
-      new GroupForm(), 
68
-      $new_group,
69
-      array('tags' => $this->getTagsArray())
70
-    );
71
+    $form_new = $this->getGroupForm($new_group);
71 72
     
72 73
     $form_new->bindRequest($request);
73 74
     
@@ -93,8 +94,9 @@ class DefaultController extends Controller
93 94
       return $this->render(
94 95
         'MuzichGroupBundle:Default:myList.html.twig', 
95 96
          array(
96
-           'groups'   => $user->getGroupsOwned(),
97
-           'form_new' => $form_new->createView()
97
+           'groups'        => $user->getGroupsOwned(),
98
+           'form_new'      => $form_new->createView(),
99
+           'form_new_name' => $form_new->getName()
98 100
          )
99 101
       );
100 102
     }
@@ -130,16 +132,12 @@ class DefaultController extends Controller
130 132
     }
131 133
     
132 134
     $group->setTagsToIds();
133
-    
134
-    $form = $this->createForm(
135
-      new GroupForm(), 
136
-      $group,
137
-      array('tags' => $this->getTagsArray())
138
-    );
135
+    $form = $this->getGroupForm($group);
139 136
     
140 137
     return array(
141
-      'group' => $group,
142
-      'form'  => $form->createView()        
138
+      'group'     => $group,
139
+      'form'      => $form->createView()  ,
140
+      'form_name' => $form->getName()      
143 141
     );
144 142
   }
145 143
   
@@ -156,12 +154,7 @@ class DefaultController extends Controller
156 154
     // Pour être compatible avec le formulaire, la collection de tags dois être
157 155
     // une collection d'id
158 156
     $group->setTagsToIds();
159
-    
160
-    $form = $this->createForm(
161
-      new GroupForm(), 
162
-      $group,
163
-      array('tags' => $this->getTagsArray())
164
-    );
157
+    $form = $this->getGroupForm($group);
165 158
     
166 159
     $form->bindRequest($request);
167 160
     
@@ -183,7 +176,8 @@ class DefaultController extends Controller
183 176
       return $this->render(
184 177
         'GroupBundle:Default:edit.html.twig', 
185 178
          array(
186
-           'form_new' => $form->createView()
179
+           'form_new'      => $form->createView(),
180
+           'form_new_name' => $form_new->getName()
187 181
          )
188 182
       );
189 183
     }

+ 1 - 1
src/Muzich/GroupBundle/Resources/views/Default/myList.html.twig Просмотреть файл

@@ -26,7 +26,7 @@
26 26
 
27 27
   <form action="{{ path('group_add') }}" method="post" {{ form_enctype(form_new) }}>
28 28
     
29
-    {% include "MuzichGroupBundle:Form:form.html.twig" with { 'form': form_new } %}
29
+    {% include "MuzichGroupBundle:Form:form.html.twig" with { 'form': form_new, 'form_name': form_new_name } %}
30 30
 
31 31
     <input type="submit" />
32 32
   </form>

+ 3 - 5
src/Muzich/GroupBundle/Resources/views/Form/form.html.twig Просмотреть файл

@@ -22,10 +22,8 @@
22 22
   {{ form_widget(form.open) }}
23 23
 </div>
24 24
 
25
-<div class="field">
26
-  {{ form_errors(form.tags) }}
27
-  {{ form_label(form.tags, 'tags'|trans({}, 'groupform')) }}
28
-  {{ form_widget(form.tags) }}
29
-</div>
25
+{% include "MuzichCoreBundle:Tag:tagsPrompt.html.twig" with { 'form_name': form_name } %}
26
+
27
+{{ form_row(form.tags) }}
30 28
 
31 29
 {{ form_rest(form) }}

+ 0 - 1
src/Muzich/HomeBundle/Controller/HomeController.php Просмотреть файл

@@ -29,7 +29,6 @@ class HomeController extends Controller
29 29
     $add_form = $this->getAddForm();
30 30
     
31 31
     return array(
32
-      'tags'             => $this->getTagsArray(),
33 32
       'search_tags_id'   => $search_object->getTags(),
34 33
       'user'             => $this->getUser(),
35 34
       'add_form'         => $add_form->createView(),

+ 1 - 7
src/Muzich/HomeBundle/Controller/ShowController.php Просмотреть файл

@@ -53,13 +53,7 @@ class ShowController extends Controller
53 53
     ($group->getOwner()->getId() == $this->getUserId()) ? $his = true : $his = false;
54 54
     if ($his || $group->getOpen())
55 55
     {      
56
-      $add_form = $this->createForm(
57
-        new ElementAddForm(),
58
-        array(),
59
-        array(
60
-          'tags' => $this->getTagsArray()
61
-        )
62
-      );
56
+      $add_form = $this->getAddForm();
63 57
     }
64 58
     
65 59
     return array(

+ 25 - 20
src/Muzich/UserBundle/Controller/UserController.php Просмотреть файл

@@ -14,7 +14,7 @@ use Symfony\Component\Validator\Constraints\Collection;
14 14
 class UserController extends Controller
15 15
 {
16 16
   
17
-  protected $tags_favorites = array();
17
+  protected $tags_favorites = null;
18 18
   
19 19
   protected function getChangeEmailForm()
20 20
   {
@@ -32,15 +32,30 @@ class UserController extends Controller
32 32
   
33 33
   protected function getTagsFavoritesForm($user)
34 34
   {
35
+    $ids = array();
36
+    foreach ($this->getTagsFavorites() as $id => $name)
37
+    {
38
+      $ids[] = $id;
39
+    }
40
+    
35 41
     return $this->createForm(
36 42
       new TagFavoritesForm(), 
37
-      array('tags' => $this->tags_favorites = $this->getDoctrine()->getRepository('MuzichCoreBundle:User')
38
-        ->getTagIdsFavorites($user->getId())
39
-      ),
40
-      array('tags' => $this->getTagsArray())
43
+      array('tags' => json_encode($ids))
41 44
     );
42 45
   }
43 46
   
47
+  protected function getTagsFavorites($force = false)
48
+  {
49
+    if ($this->tags_favorites === null || $force)
50
+    {
51
+      $this->tags_favorites = $this->getDoctrine()->getRepository('MuzichCoreBundle:User')
52
+        ->getTagsFavorites($this->getUser()->getId())
53
+      ;
54
+    }
55
+    
56
+    return $this->tags_favorites;
57
+  }
58
+  
44 59
   /**
45 60
    * Page de configuration de son compte
46 61
    *
@@ -54,12 +69,11 @@ class UserController extends Controller
54 69
     $change_email_form = $this->getChangeEmailForm();
55 70
     
56 71
     return array(
57
-      'tags'                     => $this->getTagsArray(),
58 72
       'user'                     => $user,
59 73
       'form_password'            => $form_password->createView(),
60 74
       'form_tags_favorites'      => $form_tags_favorites->createView(),
61 75
       'form_tags_favorites_name' => $form_tags_favorites->getName(),
62
-      'favorite_tags_id'         => $this->tags_favorites,
76
+      'favorite_tags_id'         => $this->getTagsFavorites(),
63 77
       'change_email_form'        => $change_email_form->createView()
64 78
     );
65 79
   }
@@ -223,13 +237,12 @@ class UserController extends Controller
223 237
       return $this->container->get('templating')->renderResponse(
224 238
         'MuzichUserBundle:User:account.html.twig',
225 239
         array(
226
-          'tags'                     => $this->getTagsArray(),
227 240
           'form_password'            => $form->createView(),
228 241
           'errors_pers'              => $errors,
229 242
           'user'                     => $user,
230 243
           'form_tags_favorites'      => $form_tags_favorites->createView(),
231 244
           'form_tags_favorites_name' => $form_tags_favorites->getName(),
232
-          'favorite_tags_id'         => $this->tags_favorites,
245
+          'favorite_tags_id'         => $this->getTagsFavorites(),
233 246
           'change_email_form'        => $change_email_form->createView()
234 247
         )
235 248
       );
@@ -250,8 +263,7 @@ class UserController extends Controller
250 263
     $form_tags_favorites = $this->getTagsFavoritesForm($user);
251 264
     
252 265
     return array(
253
-      'tags'                     => $this->getTagsArray(),
254
-      'favorite_tags_id'         => $this->tags_favorites,
266
+      'favorite_tags_id'         => $this->getTagsFavorites(),
255 267
       'form_tags_favorites'      => $form_tags_favorites->createView(),
256 268
       'form_tags_favorites_name' => $form_tags_favorites->getName(),
257 269
     );
@@ -278,13 +290,7 @@ class UserController extends Controller
278 290
       )->getSingleResult();
279 291
     }
280 292
     
281
-    $form = $this->createForm(
282
-      new TagFavoritesForm(), 
283
-      array('tags' => $this->getDoctrine()->getRepository('MuzichCoreBundle:User')
284
-        ->getTagIdsFavorites($user->getId())
285
-      ),
286
-      array('tags' => $this->getTagsArray())
287
-    );
293
+    $form = $this->getTagsFavoritesForm($user);
288 294
     
289 295
     if ($request->getMethod() == 'POST')
290 296
     {
@@ -411,12 +417,11 @@ class UserController extends Controller
411 417
     return $this->container->get('templating')->renderResponse(
412 418
       'MuzichUserBundle:User:account.html.twig',
413 419
       array(
414
-        'tags'                     => $this->getTagsArray(),
415 420
         'user'                     => $user,
416 421
         'form_password'            => $form_password->createView(),
417 422
         'form_tags_favorites'      => $form_tags_favorites->createView(),
418 423
         'form_tags_favorites_name' => $form_tags_favorites->getName(),
419
-        'favorite_tags_id'         => $this->tags_favorites,
424
+        'favorite_tags_id'         => $this->getTagsFavorites(),
420 425
         'change_email_form'        => $change_email_form->createView()
421 426
       )
422 427
     );

+ 59 - 0
web/bundles/muzichcore/js/muzich.js Просмотреть файл

@@ -46,6 +46,65 @@ function findKeyWithValue(arrayt, value)
46 46
   return "";
47 47
 }
48 48
 
49
+function json_to_array(json_string)
50
+{
51
+  if (json_string.length)
52
+  {
53
+    return eval("(" + json_string + ")");
54
+  }
55
+  return new Array();
56
+}
57
+
58
+/**
59
+ * Converts the given data structure to a JSON string.
60
+ * Argument: arr - The data structure that must be converted to JSON
61
+ * Example: var json_string = array2json(['e', {pluribus: 'unum'}]);
62
+ * 			var json = array2json({"success":"Sweet","failure":false,"empty_array":[],"numbers":[1,2,3],"info":{"name":"Binny","site":"http:\/\/www.openjs.com\/"}});
63
+ * http://www.openjs.com/scripts/data/json_encode.php
64
+ */
65
+function array2json(arr) {
66
+    var parts = [];
67
+    var is_list = (Object.prototype.toString.apply(arr) === '[object Array]');
68
+
69
+    for(var key in arr) {
70
+    	var value = arr[key];
71
+        if(typeof value == "object") { //Custom handling for arrays
72
+            if(is_list) parts.push(array2json(value)); /* :RECURSION: */
73
+            else parts[key] = array2json(value); /* :RECURSION: */
74
+        } else {
75
+            var str = "";
76
+            if(!is_list) str = '"' + key + '":';
77
+
78
+            //Custom handling for multiple data types
79
+            if(typeof value == "number") str += value; //Numbers
80
+            else if(value === false) str += 'false'; //The booleans
81
+            else if(value === true) str += 'true';
82
+            else str += '"' + value + '"'; //All other things
83
+            // :TODO: Is there any more datatype we should be in the lookout for? (Functions?)
84
+
85
+            parts.push(str);
86
+        }
87
+    }
88
+    var json = parts.join(",");
89
+    
90
+    if(is_list) return '[' + json + ']';//Return numerical JSON
91
+    return '{' + json + '}';//Return associative JSON
92
+}
93
+
94
+function isInteger(s) {
95
+  return (s.toString().search(/^-?[0-9]+$/) == 0);
96
+}
97
+
98
+function inArray(array, p_val) {
99
+    var l = array.length;
100
+    for(var i = 0; i < l; i++) {
101
+        if(array[i] == p_val) {
102
+            return true;
103
+        }
104
+    }
105
+    return false;
106
+}
107
+
49 108
 if(typeof(String.prototype.trim) === "undefined")
50 109
 {
51 110
     String.prototype.trim = function() 

+ 80 - 45
web/js/tags/jquery.tagBox.js Просмотреть файл

@@ -35,8 +35,6 @@
35 35
             self.delimit_key = 32 
36 36
             self.delimit_expr = /\s+/
37 37
         }
38
-
39
-        var values = options.tag_values;
40 38
  
41 39
         var val = input.val();
42 40
         var tags = []
@@ -57,12 +55,23 @@
57 55
             }
58 56
         });
59 57
         
60
-        self.tagInput.bind("selectTag", function() {
61
-            if(!$(this).val()) {
62
-                return;
58
+        self.tagInput.bind("selectTag", function(event) {
59
+          if(!$(this).val()) {
60
+              return;
61
+          }
62
+          
63
+          input = $(this);
64
+
65
+          // Ici il faut faire un ajax q pour connaitre l'id, on a que le string
66
+          $.getJSON('/app_dev.php/fr/search/tagid/'+$(this).val(), function(data) {
67
+            if (isInteger(data))
68
+            {
69
+              self.addTag(input.val(), data, options.form_name, false);
70
+              input.val("");
63 71
             }
64
-            self.addTag($(this).val(), findKeyWithValue(values, $(this).val()), options.form_name);
65
-            $(this).val("");
72
+          });
73
+
74
+          
66 75
         });
67 76
         
68 77
         self.tagbox = $('<ul>', {
@@ -81,14 +90,17 @@
81 90
         self.inputHolder.append(self.tagInput);
82 91
         self.tagInput.autoGrowInput();
83 92
         
84
-        for(tag in tags) {
85
-            self.addTag(tags[tag], findKeyWithValue(values, tags[tag]), options.form_name);
86
-        }
93
+        // On désactive l'ajout de tags basé sur le contenu du input
94
+        // ona notre propre système (taginit)
95
+        //for(tag in tags) {
96
+        //    self.addTag(tags[tag], findKeyWithValue(values, tags[tag]), options.form_name, true);
97
+        //}
87 98
         
88 99
         if (options.tag_init.length)
89 100
         {
90
-          for(tagid in options.tag_init) {
91
-              self.addTag(values[tagid], tagid, options.form_name);
101
+          for(i in options.tag_init) {
102
+            tag = options.tag_init[i];
103
+            self.addTag(tag.name, tag.id, options.form_name, true);
92 104
           }
93 105
         }
94 106
         
@@ -96,47 +108,70 @@
96 108
     
97 109
     TagBox.prototype = {
98 110
         
99
-        addTag : function(label, id, form_name) {
100
-            
101
-            // Nos conditions pour ajouter le tag:
102
-            // * N'a pas déjà été ajouté a ce champ
103
-            // * Est dans la liste des tags existants
104
-            if (id && !findKeyWithValue(tagsAddeds[form_name], id))
105
-            {
106
-              var self = this;
107
-              var tag = $('<li class="tag">' + $('<div>').text(label).remove().html() + '</li>');
111
+        addTag : function(label, id, form_name, force) {
112
+          
113
+          // On n'ajoute pas deux fois le même tag
114
+          if (id && !findKeyWithValue(tagsAddeds[form_name], id))
115
+          {
116
+            var self = this;
117
+            var tag = $('<li class="tag">' + $('<div>').text(label).remove().html() + '</li>');
108 118
 
109
-              this.tags.push(label);
119
+            this.tags.push(label);
120
+
121
+            tag.append($('<a>', {
122
+                "href" : "#",
123
+                "class": "close",
124
+                "text": "close",
125
+                click: function(e) {
126
+                    e.preventDefault();
127
+                    var index = self.tagbox.find("li").index($(this).parent());
128
+                    self.removeTag(index, id, form_name);
129
+                }
130
+            }));
110 131
 
111
-              tag.append($('<a>', {
112
-                  "href" : "#",
113
-                  "class": "close",
114
-                  "text": "close",
115
-                  click: function(e) {
116
-                      e.preventDefault();
117
-                      var index = self.tagbox.find("li").index($(this).parent());
118
-                      self.removeTag(index);
119
-                  }
120
-              })).append($('<input>', {
121
-                'type'   : 'checkbox',
122
-                'style'  : 'display: none;',
123
-                'value'  : id,
124
-                'name'   : form_name+'[tags]['+id+']',
125
-                'id'     : form_name+'_tags_'+id,
126
-                'checked': 'checked'
127
-              }));
128
-              
129
-              tagsAddeds[form_name][id] = id;
130
-              self.inputHolder.before(tag);
131
-              self.updateInput();
132
+            // si on force, on ne touche pas l'inpu (il contient déjà ces valeurs)
133
+            if (!force)
134
+            {
135
+              var input_tags = $('input#'+form_name+'_tags');
136
+              if (input_tags.length)
137
+              {
138
+                // array des ids de tags
139
+                var input_values = json_to_array(input_tags.val());
140
+                if (!inArray(input_values, id))
141
+                {
142
+                  input_values[input_values.length] = parseInt(id);
143
+                  $('input#'+form_name+'_tags').val(array2json(input_values));
144
+                }
145
+              }
132 146
             }
133
-            
147
+            //
148
+
149
+            tagsAddeds[form_name][id] = id;
150
+            self.inputHolder.before(tag);
151
+            self.updateInput();
152
+             
153
+          }
134 154
         },
135
-        removeTag : function(index) {
155
+        removeTag : function(index, id, form_name) {
136 156
             
137 157
             this.tagbox.find("li").eq(index).remove();
138 158
             this.tags.splice(index, 1);
139 159
             this.updateInput();
160
+            
161
+            input_tags = $('input#'+form_name+'_tags');
162
+            if (input_tags.length)
163
+            {
164
+              // array des ids de tags
165
+              input_values = json_to_array(input_tags.val());
166
+              for(var i = 0; i < input_values.length; i++)
167
+              {
168
+                if (input_values[i] == id)
169
+                {
170
+                  delete input_values[i];
171
+                }
172
+              }
173
+              $('input#'+form_name+'_tags').val(array2json(input_values));
174
+            }
140 175
         },
141 176
         updateInput : function() {
142 177