繁体   English   中英

如何使用Symfony3和Ajax将tinyMCE textarea编辑器内容发送到内部控制器

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

我有两个id为#homepage,#thankyoupage的tinyMCE编辑器,我想将tinymce textarea内容发送到symfony控制器内部。

这是我的前端部分:

在此处输入图片说明

我正在尝试使用jQuery ajax发送正常的textarea值,如下所示,但我正在获得未定义的值。

$(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');
        }
    });
});

这是我的表格:

$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...")
));

这是我的控制器:

/**
 * @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(),
    ));
}

和我的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 "

这是我第一次使用tinyMCE编辑器,实际上我不确定我在哪里做错了。 请任何人帮助我,让我知道是否需要任何其他信息。

提前致谢

1.在表单构建器中设置自定义id属性将不起作用。

有两种解决方法:

  • 请勿更改默认ID

在脚本中,使用由Symfony生成的默认id属性。 对于简单属性,它是表单的名称和由下划线分隔的字段的名称,因此您可以按以下方式定位字段(选择器“ id结尾于”):

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

(*)确保在呈现的html页面中生成的id属性。
(**)注意,您交换了脚本中的字段,将array_data['dedline']$('#homepage').val()

  • 如果您确实需要更改id属性,请执行以下操作:

使用以下方法渲染字段时,可以在模板中完成此操作:

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


2.您必须使用TinyMCE的方法来获取编辑的内容。

为此,可以:

  • 调用tinyMCE.triggerSave(); 在获取字段之前,请先确定您的方式。
  • 或者使用tinyMCE.get('fieldFullId').getContent();获取内容tinyMCE.get('fieldFullId').getContent();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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