genemu / GenemuFormBundle

Extra Form : Captcha GD, Tinymce, Recaptcha, JQueryDate, JQueryAutocomplete, JQuerySlider, JQueryFile, JQueryImage
587 stars 263 forks source link

many-to-many wth select2 #218

Open nephilimdie opened 11 years ago

nephilimdie commented 11 years ago

Hi, thanks for your bundle. i use this with select2 but i have a problem to managment in controller the data. My relation is between one_table m2m with media table. one_tableType:

....
 ->add('medias', 'genemu_jqueryselect2_hidden', array(
    'configs' => array(
        'multiple' => true // Wether or not multiple values are allowed (default to false)
     )
))
....

template

{% extends '::base.html.twig' %}

{% form_theme form _self %}
{% block content %}
{{ form_stylesheet(form) }}
{{ form_javascript(form) }}
<form style="margin: 0px;" action="{{ path('nasd2_tabellagenerale_create') }}" method="post" {{ form_enctype(form) }}>
    <div class="modal-body"> 
        {{ form_widget(form) }}
    </div>
    <button type="submit" class="btn">Create</button>
</form>
{% endblock content %}

{% block genemu_jqueryselect2_javascript %}
<style type="text/css">
    .zebra { background-color: #efefef !important; }

    img.flag { height: 10px !important; width: 15px !important; padding-right: 10px !important; }

    .media-result td {vertical-align: top }
    .media-image { width: 40px !important; }
    .media-image img { height: 40px !important; width: 40px !important;  }
    .media-info { padding-left: 10px !important; vertical-align: top; }
    .media-title { font-size: 1.2em; padding-bottom: 0px !important; }
    .media-synopsis { font-size: .8em; color: #888; }
    .select2-highlighted .media-synopsis { font-size: .8em; color: #eee; }
    .bigdrop.select2-container .select2-results {max-height: 300px !important; width: 600px !important;}
    .bigdrop .select2-results {max-height: 300px !important;}
</style>
<script type="text/javascript">

$(window).load(function(){
    function mediaFormatResult(media) {
        var markup = "<table class='media-result'><tr>";
        if (media.name !== undefined) {
            markup += "<td class='media-image'><img src='{{ asset('uploads/thumbnails/') }}" + media.name + "'/></td>";
        }
        markup += "<td class='media-info'><div class='media-title'>" + media.name + "</div>";
        if (media.size !== undefined) {
            markup += "<div class='media-synopsis'>" + media.size + "</div>";
        }
        else if (media.mime !== undefined) {
            markup += "<div class='media-synopsis'>" + media.mime + "</div>";
        }
        markup += "</td></tr></table>"
        //return markup;
        return markup;
    }

    function mediaFormatSelection(media) {
        return "<img src='{{ asset('uploads/thumbnails/') }}" + media.name + "'/><br /><p>"+ media.name +"</p>";
    }
    $field = $('#{{ id }}');
    var $configs = {{ configs|json_encode|raw }};
    // custom configs
    $configs = $.extend($configs, {
        ajax: { 
            quietMillis: 100,
            url: "{{ path('media_getmediafromquery') }}",
            dataType: 'json',
            data: function (term, page) {
                return {
                    q: term,
                    // search term
                    page_limit: 10
                };
            },
            results: function (data, page) {
                return {results: data.results};
            }
        },
        formatResult: mediaFormatResult, 
        formatSelection: mediaFormatSelection, 
        dropdownCssClass: "bigdrop", // apply css that makes the dropdown taller
        initSelection: function(element, callback) {
            var data = [];
            $(element.val().split(",")).each(function(i) {
                var item = this.split(':');
                data.push({
                    id: item[0],
                    name: item[1]
                });
            });
            //$(element).val('');
            callback(data);
        }
    });
    // end of custom configs
    $field.select2($configs);
});
</script>
{% endblock %}

and one_table controller

....
    public function createAction(Request $request)
    {
        die(var_dump($request));
        $entity  = new one_table();
        $form = $this->createForm(new one_tableType(), $entity);
        $form->bind($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

            $vettore = '';
            foreach ($entity->getMedias() as $file)
                $vettore .= $file->getName().' | ';
            $entity->setMediastring($vettore);
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('nasd2_one_table_show', array('id' => $entity->getId())));
        }
....

in media controller

    /**
     * @Route("/getmediafromquery", name="media_getmediafromquery")
     */
    public function getmediafromquery(Request $request)
    {
        $value = $request->get('q');
        $callback = $request->get('callback');
        $em = $this->getDoctrine()->getManager();
        $entities = $em->getRepository('MediaMediaBundle:Media')->findAll();//findBy(array('name'=>$value));
        $json = array();
        foreach ($entities as $member) {
            $json[] = array(
                'id'    =>  $member->getId(),
                'name'  =>  $member->getName(),
                'size'  =>  $member->getSize(),
                'mime'  =>  $member->getMime()
            );
        }

        $response = new Response();
        //die(var_dump($json));
        $response->headers->set('Content-Type', 'application/json');
        $result = array('results'=>$json);
        $result["total"] = 959; //change in count
        $response->setContent(json_encode($result));

        return $response;
    }
Catchable Fatal Error: Argument 1 passed to Nasd2\TabBundle\Entity\Tabellagenerale::addMedia() must be an instance of Media\MediaBundle\Entity\Media, string given in /home/nasd/symfony-bootstrap/src/Nasd2/TabBundle/Entity/Tabellagenerale.php line 560

i know the m2m in request need a array for m2m but i don't understand why the genemu_jqueryselect2_hidden create only a hidden input. how can I manage the datas in controller?

thanks in advance SB

ikleiman commented 10 years ago

I know this issue is old, but I'm having exactly the same problem and it's breaking my head off. Any solution?

imulot commented 10 years ago

As you use ajax, you need a ModelTransformer to convert view data (hidden field value : string format) to model data (your Media entity).

ikleiman commented 10 years ago

Thanks, that fixed it. Just create the Transformers you need and attach them to the respective FormType fields.