简体   繁体   中英

How can I send tinyMCE textarea editor content to inside controller using Symfony3 and Ajax

I have two tinyMCE editor with id's like #homepage, #thankyoupage, I want to send tinymce textarea content to inside symfony controller.

This is my front end part:

在此处输入图片说明

I am trying to send normal textarea value using jQuery ajax like below but I am getting undefined value.

$(document).ready(function () {
    var array_data = {};
    array_data['dedline'] = $('#homepage').val();
    array_data['homepage'] = $('#thankyoupage').val();
    array_data['thankyoupage'] = $('#deadlinetoanswer').val();
    $.ajax({
        type: 'POST',
        url: Routing.generate("invitation"),
        contentType: 'application/x-www-form-urlencoded',
        data: {
            data_array: array_data
        },
        success: function (result, status, xhr) {
            var res = JSON.parse(result);
            console.log(res);
        },
        error: function (xhr, status, error) {
            console.log('error1');
        }
    });
});

This is my form:

$builder->add('deadlinetoanswer', ChoiceType::class, array(
    'choices' => array(
        '2 days' => 2,
        '3 days' => 3,
        '5 days' => 5,
        '7 days' => 7,
        '10 days' => 10,
        '15 days' => 15,
        'Until' => 'until'
    )
));

$builder->add('prerecwelcomemsg', TextareaType::class, array(
    'required' => true,
    'attr' => array('class' => 'tinymce', 'id' => 'homepage', 'data-theme' => 'bbcode', 'style' => 'height: 380px', 'placeholder' => "Welcome...")
));

$builder->add('prerecthankyoumsg', TextareaType::class, array(
    'required' => true,
    'attr' => array('class' => 'tinymce', 'id' => 'thankyoupage', 'data-theme' => 'bbcode', 'style' => 'height: 380px', 'placeholder' => "Thank you...")
));

This is my controller:

/**
 * @Route("/prerecorded/invitation", name="invitation", options={"expose"=true})
 */
public
function invitationAction(Request $request) {
    $em = $this - > getDoctrine() - > getManager();
    $form = $this - > createForm(InvitationType::class);
    $form - > handleRequest($request);

    if ($request - > isXmlHttpRequest()) {
        $res_arr = $request - > request - > get('data_array');
        //   $this->container->get('logger')->addInfo('somesh'.$res_arr);           
        if ($res_arr) {
            $campaignid = 1;
            $campaign = $em - > getRepository('TraceBundle:Campaign') - > findOneBy(array('id' => $campaignid));
            $campaign - > setDeadlinetoanswer('');
            $campaign - > setPrerecwelcomemsg('hello');
            $campaign - > setPrerecthankyoumsg('how r u');
            $em - > persist($campaign);
            $em - > flush();
            return new Response(json_encode($campaignid));
        }
    }
    return $this - > render('TraceBundle:Campaign:invitation.html.twig', array(
        'form' => $form - > createView(),
    ));
}

and my config.yml

stfalcon_tinymce:
    include_jquery: true
    tinymce_jquery: true
    selector: ".tinymce"
  #  base_url: "http://yourdomain.com/" # this parameter may be included if you need to override the assets_base_urls for your template engine (to override a CDN base url)
    # Get current language from the parameters.ini
    language: %locale%
    # Custom buttons
    tinymce_buttons:
        stfalcon: # Id of the first button
            title: "Stfalcon"
            image: "http://stfalcon.com/favicon.ico"

    theme:
        # Simple theme: same as default theme
        simple: ~

        # Advanced theme with almost all enabled plugins
        advanced:
             plugins:
                 - "advlist autolink lists link image charmap print preview hr anchor pagebreak"
                 - "searchreplace wordcount visualblocks visualchars code fullscreen"
                 - "insertdatetime media nonbreaking save table contextmenu directionality"
                 - "emoticons template paste textcolor"
             toolbar1: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image"
             toolbar2: "print preview media | forecolor backcolor emoticons | stfalcon | example"
             image_advtab: true
             templates:
                 - {title: 'Test template 1', content: 'Test 1'}
                 - {title: 'Test template 2', content: 'Test 2'}
        # BBCode tag compatible theme (see http://www.bbcode.org/reference.php)
        bbcode:
             plugins: ["bbcode, code, link, preview"]
             menubar: false               
             toolbar1: "styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist "

This is first time I am working tinyMCE editor, really I am not sure where I am doing wrong. Please help me anyone and let me know is there any extra information is needed.

Thanks in advance

1. Setting a custom id attribute in the form builder won't work.

There are two ways to fix that:

  • Don't change the default id

In your script, use the default id attributes, generated by Symfony. For simple properties it's the name of the form and the name of the field separated by an underscore, so you can target your fields this way (selector 'id ends with'):

array_data['homepage'] = $('[id$="_prerecwelcomemsg"]');
array_data['thankyoupage'] = $('[id$="_prerecthankyoumsg"]').val();
array_data['deadlinetoanswer'] = $('[id$="_deadlinetoanswer"]').val();

(*) check the id attributes generated in the rendered html page to be sure.
(**) notice that you swapped the fields in your script, setting array_data['dedline'] to $('#homepage').val() .

  • If you really need to change the id attributes:

You can do it in the template when you render the fields with:

{{ form_row(form.prerecwelcomemsg, { 'id': 'homepage' }) }}


2. You have to use TinyMCE's methods to get the edited content.

For this, either:

  • Call tinyMCE.triggerSave(); before getting the fields value the way you do.
  • Or get the content with tinyMCE.get('fieldFullId').getContent();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM