Wijnand
Wijnand

Reputation: 1191

Yii2 CKeditor not initialized when requested via ajax

I am trying to add a from with a CKeditor widget imbedded via an AJAX request. The request itself works fine and returns the general partial view as I want it. Except for the Ckeditor widget, a normal textbox is return instead.

When the item is added to the group and the page is reloaded, the same partialView is being rendered (in a foreach with all group-items) and this time the CKeditor is nicely in place.

Posted my controller, initialization of the CKeditor and Scipt with AJAX request below. (The CKeditor is inlcuded in the _ContentItemHtml view)

I have taken a look at this, but I cannot call any CKeditor functions from JS since it is loaded as a widget.

Controller Action

public function actionCreateHtml($contentitemgroupid)
{
    $model = new ContentItemHtml();
    if (isset(Yii::$app->request->post()['ContentItemHtml'])) {
        $item = Yii::$app->request->post()['ContentItemHtml'];
        $model->contentitemgroupid = $contentitemgroupid;
        $model->title = $item['title'];
        $model->body = $item['body'];
        $model->save();
        // return $this->redirect(['edit', 'id' => $model->contentitemgroupid]);
    }
    else
        return $this->renderPartial('_ContentItemHtml', ['model' => $model]);
}

Active form in view:

echo $form->field($model, 'body')->widget(CKEditor::className(), [
    'preset' => 'custom',
    'clientOptions' => [
        'height' => 200,
        'toolbarGroups' => [
        ['name' => 'basicstyles', 'groups' => ['basicstyles', 'cleanup']],
        ['name' => 'paragraph', 'groups' => ['templates', 'list']],
        ['name' => 'mode']]
    ]])->label(false);

Script.js

$('#addNewContentItem').on('click', function (e) {
  e.preventDefault();
  var url = 'create-' + $('#itemSelector').val().toLowerCase() + '?contentitemgroupid=' + $('#itemSelector').attr('contentitemgroupid');
  $.ajax({
    type: 'POST',
    url: url,
    cache: false,
    success: function(res) {
      $('.contentItemsManager').append('<div class="ContentItemContainer row">' + res + '</div>');
      AddSaveEventListener();
      AddSaveMediafileEventListener();
      AddRemoveEventListener();
    }
  });
});

Upvotes: 1

Views: 784

Answers (1)

topher
topher

Reputation: 14860

Use renderAjax instead of renderPartial. From the docs:

[renderAjax] Renders a view in response to an AJAX request.

This method is similar to renderPartial() except that it will inject into the rendering result with JS/CSS scripts and files which are registered with the view. For this reason, you should use this method instead of renderPartial() to render a view to respond to an AJAX request.

Upvotes: 4

Related Questions