Tinymce multiple instances in same page - tinymce

I am using tinymce multiple instances in same page. When I try to insert image, I can but it will be added always in last text area fields( I have same 10 textarea with different name and id).
Html
<div class="admin__field field field-options_options_fieldset3ad06b8f111bff0225b3ee56e2a93cc4_content_1 with-note">
<label class="label admin__field-label" for="options_fieldset3ad06b8f111bff0225b3ee56e2a93cc4_content_1" data-ui-id="adminhtml-widget-form-field-wysiwygeditor-0-text-parameters-content-1-label"><span>Content 1</span></label>
<div class="admin__field-control control">
<textarea id="options_fieldset3ad06b8f111bff0225b3ee56e2a93cc4_content_13662927431522736609" name="parameters[content_1]" class="textarea admin__control-textarea wysiwyg-editor" rows="5" cols="15" data-ui-id="product-tabs-attributes-tab-fieldset-element-textarea-parameters[content_1]" aria-hidden="true"></textarea>
<button id="id_5abf1b8e544f38a8ca21aa8815613abd" title="WYSIWYG Editor" type="button" class="action-default scalable action-wysiwyg hidden" onclick="basewidgetWysiwygEditor.open('http://cei-shop.local/admin/catalog/product/wysiwyg/key/0367c4936326c7be6bf0fda5c407d274c1f3e4a9922173f53b72e75411d13406/', 'options_fieldset3ad06b8f111bff0225b3ee56e2a93cc4_content_13662927431522736609')" data-ui-id="widget-button-0">
<span>WYSIWYG Editor</span>
</button>
<button type="button" class="scalable action-show-hide" style="" id="toggleoptions_fieldset3ad06b8f111bff0225b3ee56e2a93cc4_content_13662927431522736609"><span><span><span>Show / Hide Editor</span></span></span></button>
</div>
</div>
<div class="admin__field field field-options_options_fieldset3ad06b8f111bff0225b3ee56e2a93cc4_content_2 with-note">
<label class="label admin__field-label" for="options_fieldset3ad06b8f111bff0225b3ee56e2a93cc4_content_2" data-ui-id="adminhtml-widget-form-field-wysiwygeditor-1-text-parameters-content-2-label"><span>Content 2</span></label>
<div class="admin__field-control control">
<textarea id="options_fieldset3ad06b8f111bff0225b3ee56e2a93cc4_content_26925735391522736609" name="parameters[content_2]" class="textarea admin__control-textarea wysiwyg-editor" rows="5" cols="15" data-ui-id="product-tabs-attributes-tab-fieldset-element-textarea-parameters[content_2]" aria-hidden="true"></textarea>
<button id="id_504c308d5e46c342e202e961e97b2904" title="WYSIWYG Editor" type="button" class="action-default scalable action-wysiwyg hidden" onclick="basewidgetWysiwygEditor.open('http://cei-shop.local/admin/catalog/product/wysiwyg/key/0367c4936326c7be6bf0fda5c407d274c1f3e4a9922173f53b72e75411d13406/', 'options_fieldset3ad06b8f111bff0225b3ee56e2a93cc4_content_26925735391522736609')" data-ui-id="widget-button-1">
<span>WYSIWYG Editor</span>
</button>
<button type="button" class="scalable action-show-hide" style="" id="toggleoptions_fieldset3ad06b8f111bff0225b3ee56e2a93cc4_content_26925735391522736609"><span><span><span>Show / Hide Editor</span></span></span></button>
</div>
</div>
setup.js
define([
'jquery',
'underscore',
'tinymce',
'mage/adminhtml/wysiwyg/tiny_mce/html5-schema',
'mage/translate',
'prototype',
'mage/adminhtml/events',
'mage/adminhtml/browser'
], function(jQuery, _, tinyMCE, html5Schema) {
vesBaseTinyMceWysiwygSetup = Class.create();
vesBaseTinyMceWysiwygSetup.prototype = {
mediaBrowserOpener: null,
mediaBrowserTargetElementId: null,
initialize: function(htmlId, config) {
if (config.baseStaticUrl && config.baseStaticDefaultUrl) {
tinyMCE.baseURL = tinyMCE.baseURL.replace(config.baseStaticUrl, config.baseStaticDefaultUrl);
}
this.id = htmlId;
this.config = config;
this.schema = config.schema || html5Schema;
_.bindAll(this, 'beforeSetContent', 'saveContent', 'onChangeContent', 'openFileBrowser', 'updateTextArea');
varienGlobalEvents.attachEventHandler('tinymceChange', this.onChangeContent);
varienGlobalEvents.attachEventHandler('tinymceBeforeSetContent', this.beforeSetContent);
varienGlobalEvents.attachEventHandler('tinymceSaveContent', this.saveContent);
if (typeof tinyMceEditors == 'undefined') {
tinyMceEditors = $H({});
}
tinyMceEditors.set(this.id, this);
},
setup: function(mode) {
if (this.config.widget_plugin_src) {
tinyMCE.PluginManager.load('magentowidget', this.config.widget_plugin_src);
}
if (this.config.plugins) {
this.config.plugins.each(function(plugin) {
tinyMCE.PluginManager.load(plugin.name, plugin.src);
});
}
if (jQuery.isReady) {
tinyMCE.dom.Event.domLoaded = true;
}
tinyMCE.init(this.getSettings(mode));
},
getSettings: function(mode) {
var plugins = 'inlinepopups,safari,pagebreak,style,layer,table,advhr,advimage,emotions,iespell,media,searchreplace,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras',
self = this;
if (this.config.widget_plugin_src) {
plugins = 'magentowidget,' + plugins;
}
var magentoPluginsOptions = $H({});
var magentoPlugins = '';
if (this.config.plugins) {
this.config.plugins.each(function(plugin) {
magentoPlugins = plugin.name + ',' + magentoPlugins;
magentoPluginsOptions.set(plugin.name, plugin.options);
});
if (magentoPlugins) {
plugins = '-' + magentoPlugins + plugins;
}
}
var settings = {
mode: (mode != undefined ? mode : 'none'),
elements: this.id,
theme: 'advanced',
plugins: plugins,
theme_advanced_buttons1: magentoPlugins + 'magentowidget,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect',
theme_advanced_buttons2: 'cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,forecolor,backcolor',
theme_advanced_buttons3: 'tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,iespell,media,advhr,|,ltr,rtl,|,fullscreen',
theme_advanced_buttons4: 'insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,pagebreak',
theme_advanced_toolbar_location: 'top',
theme_advanced_toolbar_align: 'left',
theme_advanced_statusbar_location: 'bottom',
theme_advanced_resizing: true,
theme_advanced_resize_horizontal: false,
convert_urls: false,
relative_urls: false,
content_css: this.config.content_css,
custom_popup_css: this.config.popup_css,
magentowidget_url: this.config.widget_window_url,
magentoPluginsOptions: magentoPluginsOptions,
doctype: '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">',
setup: function(ed){
ed.onInit.add(self.onEditorInit.bind(self));
ed.onSubmit.add(function(ed, e) {
varienGlobalEvents.fireEvent('tinymceSubmit', e);
});
ed.onPaste.add(function(ed, e, o) {
varienGlobalEvents.fireEvent('tinymcePaste', o);
});
ed.onBeforeSetContent.add(function(ed, o) {
varienGlobalEvents.fireEvent('tinymceBeforeSetContent', o);
});
ed.onSetContent.add(function(ed, o) {
varienGlobalEvents.fireEvent('tinymceSetContent', o);
});
ed.onSaveContent.add(function(ed, o) {
varienGlobalEvents.fireEvent('tinymceSaveContent', o);
});
var onChange = function(ed, l) {
varienGlobalEvents.fireEvent('tinymceChange', l);
};
ed.onChange.add(onChange);
ed.onKeyUp.add(onChange);
ed.onExecCommand.add(function(ed, cmd, ui, val) {
varienGlobalEvents.fireEvent('tinymceExecCommand', cmd);
});
}
};
// Set the document base URL
if (this.config.document_base_url) {
settings.document_base_url = this.config.document_base_url;
}
if (this.config.files_browser_window_url) {
settings.file_browser_callback = function(fieldName, url, objectType, w) {
varienGlobalEvents.fireEvent("open_browser_callback", {
win: w,
type: objectType,
field: fieldName
});
};
}
if (this.config.width) {
settings.width = this.config.width;
}
if (this.config.height) {
settings.height = this.config.height;
}
if (this.config.settings) {
Object.extend(settings, this.config.settings)
}
return settings;
},
applySchema: function (editor) {
var schema = editor.schema,
schemaData = this.schema,
makeMap = tinyMCE.makeMap;
jQuery.extend(true, {
nonEmpty: schema.getNonEmptyElements(),
boolAttrs: schema.getBoolAttrs(),
whiteSpace: schema.getWhiteSpaceElements(),
shortEnded: schema.getShortEndedElements(),
selfClosing: schema.getSelfClosingElements(),
blockElements: schema.getBlockElements()
}, {
nonEmpty: makeMap(schemaData.nonEmpty),
boolAttrs: makeMap(schemaData.boolAttrs),
whiteSpace: makeMap(schemaData.whiteSpace),
shortEnded: makeMap(schemaData.shortEnded),
selfClosing: makeMap(schemaData.selfClosing),
blockElements: makeMap(schemaData.blockElements)
});
},
openFileBrowser: function(o) {
//console.log(o.win.tinyMCE.activeEditor.editorId);
var typeTitle,
storeId = this.config.store_id !== null ? this.config.store_id : 0,
frameDialog = jQuery(o.win.frameElement).parents('[role="dialog"]'),
wUrl = this.config.files_browser_window_url +
'target_element_id/' + this.id + '/' +
'store/' + storeId + '/';
this.mediaBrowserOpener = o.win;
this.mediaBrowserTargetElementId = o.field;
if (typeof(o.type) != 'undefined' && o.type != "") {
typeTitle = 'image' == o.type ? this.translate('Insert Image...') : this.translate('Insert Media...');
wUrl = wUrl + "type/" + o.type + "/";
} else {
typeTitle = this.translate('Insert File...');
}
frameDialog = jQuery('[role="dialog"]');
frameDialog.hide();
jQuery('#mceModalBlocker').hide();
MediabrowserUtility.openDialog(wUrl, false, false, typeTitle, {
closed: function() {
jQuery(document).find('[role="dialog"]').show();
jQuery('#mceModalBlocker').show();
}
});
},
translate: function(string) {
return jQuery.mage.__ ? jQuery.mage.__(string) : string;
},
getMediaBrowserOpener: function() {
return this.mediaBrowserOpener;
},
getMediaBrowserTargetElementId: function() {
return this.mediaBrowserTargetElementId;
},
getToggleButton: function() {
return $('toggle' + this.id);
},
getPluginButtons: function() {
return $$('#buttons' + this.id + ' > button.plugin');
},
turnOn: function(mode) {
this.closePopups();
this.setup(mode);
tinyMCE.execCommand('mceAddControl', false, this.id);
this.getPluginButtons().each(function(e) {
e.hide();
});
return this;
},
turnOff: function() {
this.closePopups();
tinyMCE.execCommand('mceRemoveControl', false, this.id);
this.getPluginButtons().each(function(e) {
e.show();
});
return this;
},
closePopups: function() {
if (typeof closeEditorPopup == 'function') {
// close all popups to avoid problems with updating parent content area
closeEditorPopup('widget_window' + this.id);
closeEditorPopup('browser_window' + this.id);
}
},
toggle: function() {
if (!tinyMCE.get(this.id)) {
this.turnOn();
return true;
} else {
this.turnOff();
return false;
}
},
onEditorInit: function (editor) {
this.applySchema(editor);
},
onFormValidation: function() {
if (tinyMCE.get(this.id)) {
$(this.id).value = tinyMCE.get(this.id).getContent();
}
},
onChangeContent: function() {
// Add "changed" to tab class if it exists
if (tinyMCE.get(this.id)) {
jQuery('#' + this.id).val(tinyMCE.get(this.id).getContent()).trigger('change');
}
if (this.config.tab_id) {
var tab = $$('a[id$=' + this.config.tab_id + ']')[0];
if ($(tab) != undefined && $(tab).hasClassName('tab-item-link')) {
$(tab).addClassName('changed');
}
}
},
// retrieve directives URL with substituted directive value
makeDirectiveUrl: function(directive) {
return this.config.directives_url.replace('directive', 'directive/___directive/' + directive);
},
encodeDirectives: function(content) {
// collect all HTML tags with attributes that contain directives
return content.gsub(/<([a-z0-9\-\_]+.+?)([a-z0-9\-\_]+=".*?\{\{.+?\}\}.*?".+?)>/i, function(match) {
var attributesString = match[2];
// process tag attributes string
attributesString = attributesString.gsub(/([a-z0-9\-\_]+)="(.*?)(\{\{.+?\}\})(.*?)"/i, function(m) {
return m[1] + '="' + m[2] + this.makeDirectiveUrl(Base64.mageEncode(m[3])) + m[4] + '"';
}.bind(this));
return '<' + match[1] + attributesString + '>';
}.bind(this));
},
encodeWidgets: function(content) {
return content.gsub(/\{\{widget(.*?)\}\}/i, function(match) {
var attributes = this.parseAttributesString(match[1]);
if (attributes.type) {
attributes.type = attributes.type.replace(/\\\\/g, "\\");
var imageSrc = this.config.widget_placeholders[attributes.type];
var imageHtml = '<img';
imageHtml += ' id="' + Base64.idEncode(match[0]) + '"';
imageHtml += ' src="' + imageSrc + '"';
imageHtml += ' title="' + match[0].replace(/\{\{/g, '{').replace(/\}\}/g, '}').replace(/\"/g, '"') + '"';
imageHtml += '>';
return imageHtml;
}
}.bind(this));
},
decodeDirectives: function(content) {
// escape special chars in directives url to use it in regular expression
var url = this.makeDirectiveUrl('%directive%').replace(/([$^.?*!+:=()\[\]{}|\\])/g, '\\$1');
var reg = new RegExp(url.replace('%directive%', '([a-zA-Z0-9,_-]+)'));
return content.gsub(reg, function(match) {
return Base64.mageDecode(match[1]);
}.bind(this));
},
decodeWidgets: function(content) {
return content.gsub(/<img([^>]+id=\"[^>]+)>/i, function(match) {
var attributes = this.parseAttributesString(match[1]);
if (attributes.id) {
var widgetCode = Base64.idDecode(attributes.id);
if (widgetCode.indexOf('{{widget') != -1) {
return widgetCode;
}
return match[0];
}
return match[0];
}.bind(this));
},
parseAttributesString: function(attributes) {
var result = {};
attributes.gsub(/(\w+)(?:\s*=\s*(?:(?:"((?:\\.|[^"])*)")|(?:'((?:\\.|[^'])*)')|([^>\s]+)))?/, function(match) {
result[match[1]] = match[2];
});
return result;
},
updateTextArea: function () {
var editor = tinyMCE.get(this.id),
content;
if (!editor) {
return;
}
content = editor.getContent();
content = this.decodeContent(content);
jQuery('#' + this.id).val(content).trigger('change');
},
decodeContent: function (content) {
var result = content;
if (this.config.add_widgets) {
result = this.decodeWidgets(result);
result = this.decodeDirectives(result);
} else if (this.config.add_directives) {
result = this.decodeDirectives(result);
}
if(result!=''){
result = result.replace(/ /g, ' ');
}
return result;
},
encodeContent: function (content) {
var result = content;
if (this.config.add_widgets) {
result = this.encodeWidgets(result);
result = this.encodeDirectives(result);
} else if (this.config.add_directives) {
result = this.encodeDirectives(result);
}
return result;
},
beforeSetContent: function(o){
o.content = this.encodeContent(o.content);
},
saveContent: function(o) {
o.content = this.decodeContent(o.content);
}
};
});

Related

I want to use "el-upload" to upload images and documents, but I want to display the images

I want to use "el-upload" to upload images and documents, but I want to display the images. If "list-type='picture-card'" is used, the document will also be shown with an incorrect cover. So is there any way I can upload files that show images thumbnails, documents that show names?
enter image description here
<el-upload
action=""
ref="upload"
:auto-upload="false"
:on-change="onchange">
<el-button slot="trigger" size="small" type="primary">Click to Upload</el-button>
</el-upload>
<el-image
style="width: 100px; height: 100px"
:src="fileList[0]"
:preview-src-list="fileList">
</el-image>
data() {
return {
fileList: []
}
}, methods: {
onchange(file, fileList){
this.fileList.push(URL.createObjectURL(file.raw))
}
}
<template>
<div class="upload-file">
<el-upload
multiple
:action="uploadFileUrl"
:before-upload="handleBeforeUpload"
:file-list="fileList"
:limit="limit"
:on-error="handleUploadError"
:on-exceed="handleExceed"
:on-success="handleUploadSuccess"
:show-file-list="false"
:headers="headers"
class="upload-file-uploader"
ref="upload"
>
<!-- 上传按钮 -->
<el-button type="primary">选取文件</el-button>
</el-upload>
<!-- 上传提示 -->
<!-- <div class="el-upload__tip" v-if="showTip">
请上传
<template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b> </template>
<template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b> </template>
的文件
</div> -->
<!-- 文件列表 -->
<transition-group
class="upload-file-list el-upload-list el-upload-list--text"
name="el-fade-in-linear"
tag="ul"
>
<li
:key="file.uid"
class="el-upload-list__item ele-upload-list__item-content"
v-for="(file, index) in fileList">
<el-link
:href="`${baseUrl}${file.url}`"
:underline="false"
target="_blank"
>
<span class="el-icon-document"> {{ getFileName(file.name) }} </span>
</el-link>
<div class="ele-upload-list__item-content-action">
<el-link :underline="false" #click="handleDelete(index)" type="danger"
>删除</el-link
>
</div>
</li>
</transition-group>
</div>
</template>
<script setup>
import { getToken } from "#/utils/auth";
const props = defineProps({
modelValue: [String, Object, Array],
// 数量限制
limit: {
type: Number,
default: 1,
},
// 大小限制(MB)
fileSize: {
type: Number,
default: 2,
},
// 文件类型, 例如['png', 'jpg', 'jpeg']
fileType: {
type: Array,
default: () => ["png", "jpg", "gif"],
},
// 是否显示提示
isShowTip: {
type: Boolean,
default: true,
},
});
const { proxy } = getCurrentInstance();
const emit = defineEmits();
const number = ref(0);
const uploadList = ref([]);
const baseUrl = "URL HERE";
const uploadFileUrl = baseUrl + "Folder_URL"; //
const headers = ref({ Authorization: "Bearer " + getToken() });
const fileList = ref([]);
const showTip = computed(
() => props.isShowTip && (props.fileType || props.fileSize)
);
watch(
() => props.modelValue,
(val) => {
if (val) {
let temp = 1;
const list = Array.isArray(val) ? val : props.modelValue.split(",");
fileList.value = list.map((item) => {
if (typeof item === "string") {
item = { name: item, url: item };
}
item.uid = item.uid || new Date().getTime() + temp++;
return item;
});
} else {
fileList.value = [];
return [];
}
},
{ deep: true, immediate: true }
);
function handleBeforeUpload(file) {
if (props.fileType.length) {
let fileExtension = "";
if (file.name.lastIndexOf(".") > -1) {
fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
}
const isTypeOk = props.fileType.some((type) => {
if (file.type.indexOf(type) > -1) return true;
if (fileExtension && fileExtension.indexOf(type) > -1) return true;
return false;
});
if (!isTypeOk) {
proxy.$modal.msgError(
${props.fileType.join("/")}
);
return false;
}
}
if (props.fileSize) {
const isLt = file.size / 1024 / 1024 < props.fileSize;
if (!isLt) {
proxy.$modal.msgError(`上传文件大小不能超过 ${props.fileSize} MB!`);
return false;
}
}
proxy.$modal.loading("正在上传文件,请稍候...");
number.value++;
return true;
}
function handleExceed() {
proxy.$modal.msgError(`上传文件数量不能超过 ${props.limit} 个!`);
}
function handleUploadError(err) {
proxy.$modal.msgError("上传文件失败");
}
// 上传成功回调
function handleUploadSuccess(res, file) {
uploadList.value.push({ name: res.fileName, url: res.fileName });
if (uploadList.value.length === number.value) {
fileList.value = fileList.value
.filter((f) => f.url !== undefined)
.concat(uploadList.value);
uploadList.value = [];
number.value = 0;
emit("update:modelValue", listToString(fileList.value));
proxy.$modal.closeLoading();
console.log("url", file);
}
}
// 删除文件
function handleDelete(index) {
fileList.value.splice(index, 1);
emit("update:modelValue", listToString(fileList.value));
}
// 获取文件名称
function getFileName(name) {
if (name.lastIndexOf("/") > -1) {
return name.slice(name.lastIndexOf("/") + 1);
} else {
return "";
}
}
// 对象转成指定字符串分隔
function listToString(list, separator) {
let strs = "";
separator = separator || ",";
for (let i in list) {
if (undefined !== list[i].url) {
strs += list[i].url + separator;
}
}
return strs != "" ? strs.substr(0, strs.length - 1) : "";
}
</script>
//tu
<style scoped lang="scss">
.upload-file-uploader {
margin-bottom: 5px;
}
.upload-file-list .el-upload-list__item {
border: 1px solid #e4e7ed;
line-height: 2;
margin-bottom: 10px;
position: relative;
}
.upload-file-list .ele-upload-list__item-content {
display: flex;
justify-content: space-between;
align-items: center;
color: inherit;
}
.ele-upload-list__item-content-action .el-link {
margin-right: 10px;
}
</style>

My API is getting called 2 times In Ionic

I am working in my Ionic Project and my API is getting called 2 times. I am not able to get why my API is getting called 2 times.
This is my productdetails.html:
<ion-col *ngIf="hassizenot && product.out_of_stock == 0" style="padding: 0px;">
<button class="mybtn11" (click)="addtocartnew(product)" ion-button small>
Add to Cart
</button>
</ion-col>
This is my productdetails.ts:
addtocartnew(detailsp)
{
this.storage.get("ID").then((val) =>
{
if(val)
{
if(detailsp.SelectedSize)
{
let usercartnewdetails = {
user_id: val,
product_id: detailsp.id,
size: detailsp.SelectedSize,
};
this.restProvider.usercartproducts(usercartnewdetails, 'user_cart/'+detailsp.id+'/'+val+'/'+detailsp.SelectedSize).subscribe((data) => {
if (data) {
console.log("One");
this.responseEdit = data;
console.log(this.responseEdit.msg);
if (this.responseEdit.status === 'success') {
this.presentToast(detailsp.product_name);
}
else{
this.presentToasterror();
}
}
});
}
else
{
let usercartnewdetails = {
user_id: val,
product_id: detailsp.id,
};
this.restProvider.usercartproducts(usercartnewdetails, 'user_cart/'+detailsp.id+'/'+val).subscribe((data) => {
if (data) {
console.log("Two");
this.responseEdit = data;
console.log(this.responseEdit.msg);
if (this.responseEdit.status === 'success') {
this.presentToast(detailsp.product_name);
}
else{
this.presentToasterror();
}
}
});
}
}
});
}
This is my Service:
usercartproducts(credentials, type) {
var headers = new HttpHeaders();
headers.append('Access-Control-Allow-Origin' , '*');
headers.append('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT');
headers.append('Accept','application/json');
headers.append('Content-Type','application/json');
headers.append('Access-Control-Allow-Credentials','true');
headers.append('Access-Control-Allow-Headers','Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With');
return this.http.post(apiUrl + type, credentials, {headers: headers});
}
In my ts file, I am running the API for adding the products to the cart and it is showing only one response in the console but it is calling 2 times because it is adding the 2 times the product and in the network in the chrome, it is calling 2 times.
Any help is much appreciated.
Just Try This In Your Service:
usercartproducts(credentials, type) {
var headers = new HttpHeaders();
headers.append('Access-Control-Allow-Origin' , '*');
headers.append('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT');
headers.append('Accept','application/json');
headers.append('Content-Type','application/x-www-form-urlencoded');
headers.append('Access-Control-Allow-Credentials','true');
headers.append('Access-Control-Allow-Headers','Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With');
let v = new FormData();
for(var k in credentials)v.append(k,credentials[k]);
return this.http.post(apiUrl + type, v, {headers: headers});
}
This solved my problem.
because you implement yout API twice and your If condition must be wrong
change your ts like this.
addtocartnew(detailsp) {
if (detailsp.SelectedSize) {
this.storage.get("ID").then((val) => {
if (val) {
let usercartnewdetails = {
user_id: val,
product_id: detailsp.id,
size: detailsp.SelectedSize,
};
this.restProvider.usercartproducts(usercartnewdetails, 'user_cart/' +
detailsp.id + '/' + val + '/' + detailsp.SelectedSize).subscribe((data) => {
console.log("One");
this.responseEdit = data;
console.log(this.responseEdit.msg);
if (this.responseEdit.status === 'success') {
this.presentToast(detailsp.product_name);
}
else {
this.presentToasterror();
}
}
});
}
})
}
else {
this.storage.get("ID").then((val) => {
if (val) {
let usercartnewdetails = {
user_id: val,
product_id: detailsp.id,
};
this.restProvider.usercartproducts(usercartnewdetails, 'user_cart/' +
detailsp.id + '/' + val).subscribe((data) => {
if (data) {
console.log("Two");
this.responseEdit = data;
console.log(this.responseEdit.msg);
if (this.responseEdit.status === 'success') {
this.presentToast(detailsp.product_name);
}
else {
this.presentToasterror();
}
}
});
}
})
}
}
change as per your condition and it will work.

L.DomUtil.get() modifiers don't update HTML data

Creating a map with markers displayed on it. When clicking a marker, this one has to display a Popup. I extended the L.Popup like this
L.InfrastructurePopup = L.Popup.extend({
options: {
template : "<form id='popup-form'>\
<div>\
<label for='problem'>Problem</label>\
<textarea id='problem' rows='4' cols='46' placeholder='Type your text here'></textarea>\
</div>\
<div>\
<label for='solution'>Solution</label>\
<textarea id='solution' rows='4' cols='46' placeholder='Type your text here'></textarea>\
</div>\
<button id='button-submit' class='btn btn-primary' type='button'>Submit</button>\
</form>",
},
setContent: function () {
this._content = this.options.template;
this.update();
return this;
},
initializeForm(layer, callback)
{
var problem = L.DomUtil.get('problem');
problem.textContent = layer.options.problem ? layer.options.problem : "";
problem.addEventListener('change', (e) =>
{
layer.options.problem = problem.value;
});
var solution = L.DomUtil.get('solution');
solution.textContent = layer.options.solution ? layer.options.solution : "";
solution.addEventListener('change', (e) =>
{
layer.options.solution = solution.value;
});
var buttonSubmit = L.DomUtil.get('button-submit');
buttonSubmit.addEventListener('click', (e) =>
{
callback(layer);
});
}
});
L.infrastructurePopup = function (options, source)
{
return new L.InfrastructurePopup(options, source);
};
I linked it into a custom Marker called InfrastructureMarker that has one and only popup , a InfrastructurePopup. So when it calls the openPopup() function it loads the popup on the map [ map.addLayer(popup) ] and give me the correct datas thanks to method initializeForm() that I call after the addLayer(popup) method.
L.Map.include({
openInfrastructurePopup: function (layer, callback)
{
this.closePopup();
layer._popup._isOpen = true;
this.addLayer(layer._popup);
layer._popup.initializeForm(layer, callback);
}
});
L.InfrastructureMarker = L.Marker.extend({
openPopup: function (callback)
{
if (this._popup && this._map && !this._map.hasLayer(this._popup))
{
this._popup.setLatLng(this._latlng);
this._map.openInfrastructurePopup(this, callback);
}
return this;
},
togglePopup: function (callback)
{
if (this._popup)
{
if (this._popup._isOpen)
{
this._popup._isOpen = false;
this.closePopup();
}
else
{
this.openPopup(callback);
}
}
return this;
},
bindPopup: function (callback, options)
{
var anchor = L.point(this.options.icon.options.popupAnchor || [0, 0]);
anchor = anchor.add(L.Popup.prototype.options.offset);
if (options && options.offset)
{
anchor = anchor.add(options.offset);
}
options = L.extend({offset: anchor}, options);
if (!this._popupHandlersAdded)
{
this
.on('click', () => {this.togglePopup(callback)}, this)
.on('remove', this.closePopup, this)
.on('move', this._movePopup, this);
this._popupHandlersAdded = true;
}
this._popup = new L.infrastructurePopup(options, this).setContent();
return this;
},
});
L.infrastructureMarker = function (latlng, options)
{
return new L.InfrastructureMarker(latlng, options);
};
But if I decide to click on one marker, then on another one without closing the first one, it loads the template, but initializeForm(callback) doesn't change the datas. I checked all the datas to know if it was empty or something but everything worked, I absolutely don't know where the problem is. I suppose the popup is not yet set on the DOM before my L.DomUtils.get fire but I shouldn't see undefined elements in console.log when I'm getting them.
I actually found what was happening :
Actually, when the L.map calls its closePopup function , it destroys the layer.
So after that, it creates a new one to display. BUT the remaining HTML from the previous kind of still exists.
So I finally bound exact same Ids to two HTML tags. Heresy !
My solution became what's next :
L.InfrastructurePopup = L.Popup.extend({
setContent: function (layer)
{
var template = "<form id='popup-form'>\
<div>\
<label for='problem'>Problème Identifié</label>\
<textarea id='" + layer._leaflet_id + "-problem' rows='4' cols='46' placeholder='Type your text here'></textarea>\
</div>\
<div>\
<label for='solution'>Solution Proposée</label>\
<textarea id='" + layer._leaflet_id + "-solution' rows='4' cols='46' placeholder='Type your text here'></textarea>\
</div>\
<button id='" + layer._leaflet_id + "-button-submit' class='btn btn-primary' type='button'>Submit</button>\
</form>";
this._content = template;
this.update();
return this;
},
initializeForm: function(layer, callback)
{
console.log(L.DomUtil.get(layer._leaflet_id+'-problem'));
var problem = L.DomUtil.get(layer._leaflet_id + '-problem');
problem.textContent = layer.options.problem ? layer.options.problem : "";
problem.addEventListener('change', (e) =>
{
layer.options.problem = problem.value;
});
var solution = L.DomUtil.get(layer._leaflet_id + '-solution');
solution.textContent = layer.options.solution ? layer.options.solution : "";
solution.addEventListener('change', (e) =>
{
layer.options.solution = solution.value;
});
var buttonSubmit = L.DomUtil.get(layer._leaflet_id + '-button-submit');
buttonSubmit.addEventListener('click', (e) =>
{
callback(layer);
});
}
});
L.infrastructurePopup = function (options, source)
{
return new L.InfrastructurePopup(options, source);
};
Calling setContent when creating my InfrastructurePopup with the layer_id and set it into my template made it work.
I got : '97-problem' or '99-problem' and '97-solution' or '99-solution

How could I use tinyMCE when editing a SlickGrid column?

I would like to use tinyMCE with a custom Slick Editor outside of the table, or inside a dialog. It's just to enable rich text editing.
Can I use this external plugin for a custom Slick Editor? I have not seen any example of usages like this.
Is there any potential problems using this two plugins at the same time (injecting conflicting HTML for example or preventing some firing events)?
Use a jquery alias "jQuery_new" with a compatible version
Register the new editor "TinyMCEEditor" & Add it into slick.editors.js
Use it like this {id: "column2", name: "Year", field: "year", editor: Slick.Editors.TinyMCE}
jQuery_new.extend(true, window, {
"Slick": {
"Editors": {
(..)
"TinyMCE": TinyMCEEditor
}
}});
function TinyMCEEditor(args) {
var $input, $wrapper;
var defaultValue;
var scope = this;
this.guid = function () {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return s4();
},
this.init = function () {
var $container = jQuery_new(".container");
var textAreaIdString = 'rich-editor-'+guid();
$wrapper = jQuery_new("<DIV ID='rds-wrapper'/>").appendTo($container);
$input = jQuery_new("<TEXTAREA id=" + textAreaIdString + "/>");
$input.appendTo($wrapper);
jQuery_new("#" +textAreaIdString).val( args.item[args.column.field] );
var _this = this;
tinymce.init({
selector: "#"+textAreaIdString,
forced_root_block : "",
plugins : "save image imagetools",
toolbar: 'undo redo | styleselect | bold italic | link image | save',
save_onsavecallback: function() {
jQuery_new("#" +textAreaIdString).val( this.getContent() );
_this.save();
}
});
$input.bind("keydown", this.handleKeyDown);
scope.position(args.position);
$input.focus().select();
};
this.handleKeyDown = function (e) {
if (e.which == jQuery_new.ui.keyCode.ENTER && e.ctrlKey) {
scope.save();
} else if (e.which == jQuery_new.ui.keyCode.ESCAPE) {
e.preventDefault();
scope.cancel();
} else if (e.which == jQuery_new.ui.keyCode.TAB && e.shiftKey) {
e.preventDefault();
args.grid.navigatePrev();
} else if (e.which == jQuery_new.ui.keyCode.TAB) {
e.preventDefault();
args.grid.navigateNext();
}
};
this.save = function () {
args.commitChanges();
};
this.cancel = function () {
$input.val(defaultValue);
args.cancelChanges();
};
this.hide = function () {
$wrapper.hide();
};
this.show = function () {
$wrapper.show();
};
this.position = function (position) {
};
this.destroy = function () {
$wrapper.remove();
};
this.focus = function () {
$input.focus();
};
this.loadValue = function (item) {
$input.val(defaultValue = item[args.column.field]);
$input.select();
};
this.serializeValue = function () {
return $input.val();
};
this.applyValue = function (item, state) {
item[args.column.field] = state;
};
this.isValueChanged = function () {
return (!($input.val() == "" && defaultValue == null)) && ($input.val() != defaultValue);
};
this.validate = function () {
return {
valid: true,
msg: null
};
};
this.init();
}

alert() message isn't being called in my form

Firebug is giving me no error messages, but it's not working. The idea is regardless of whether the user picks an option from dropdown or if they type in something in search box, I want the alert() message defined below to alert what the value of the variable result is (e.g. {filter: Germany}). And it doesn't. I think the javascript breaks down right when a new Form instance is instantiated because I tried putting an alert in the Form variable and it was never triggered. Note that everything that pertains to this issue occurs when form.calculation() is called.
markup:
<fieldset>
<select name="filter" alter-data="dropFilter">
<option>Germany</option>
<option>Ukraine</option>
<option>Estonia</option>
</select>
<input type="text" alter-data="searchFilter" />
</fieldset>
javascript (below the body tag)
<script>
(function($){
var listview = $('#listview');
var lists = (function(){
var criteria = {
dropFilter: {
insert: function(value){
if(value)
return handleFilter("filter", value);
},
msg: "Filtering..."
},
searchFilter: {
insert: function(value){
if(value)
return handleFilter("search", value);
},
msg: "Searching..."
}
}
var handleFilter = function(key,value){
return {key: value};
}
return {
create: function(component){
var component = component.href.substring(component.href.lastIndexOf('#') + 1);
return component;
},
setDefaults: function(component){
var parameter = {};
switch(component){
case "sites":
parameter = {
'order': 'site_num',
'per_page': '20',
'url': 'sites'
}
}
return parameter;
},
getCriteria: function(criterion){
return criteria[criterion];
},
addCriteria: function(criterion, method){
criteria[criterion] = method;
}
}
})();
var Form = function(form){
var fields = [];
$(form[0].elements).each(function(){
var field = $(this);
if(typeof field.attr('alter-data') !== 'undefined') fields.push(new Field(field));
})
}
Form.prototype = {
initiate: function(){
for(field in this.fields){
this.fields[field].calculate();
}
},
isCalculable: function(){
for(field in this.fields){
if(!this.fields[field].alterData){
return false;
}
}
return true;
}
}
var Field = function(field){
this.field = field;
this.alterData = false;
this.attach("change");
this.attach("keyup");
}
Field.prototype = {
attach: function(event){
var obj = this;
if(event == "change"){
obj.field.bind("change", function(){
return obj.calculate();
})
}
if(event == "keyup"){
obj.field.bind("keyup", function(e){
return obj.calculate();
})
}
},
calculate: function(){
var obj = this,
field = obj.field,
msgClass = "msgClass",
msgList = $(document.createElement("ul")).addClass("msgClass"),
types = field.attr("alter-data").split(" "),
container = field.parent(),
messages = [];
field.next(".msgClass").remove();
for(var type in types){
var criterion = lists.getCriteria(types[type]);
if(field.val()){
var result = criterion.insert(field.val());
container.addClass("waitingMsg");
messages.push(criterion.msg);
obj.alterData = true;
alert(result);
initializeTable(result);
}
else {
return false;
obj.alterData = false;
}
}
if(messages.length){
for(msg in messages){
msgList.append("<li>" + messages[msg] + "</li");
}
}
else{
msgList.remove();
}
}
}
$('#dashboard a').click(function(){
var currentComponent = lists.create(this);
var custom = lists.setDefaults(currentComponent);
initializeTable(custom);
});
var initializeTable = function(custom){
var defaults = {};
var custom = custom || {};
var query_string = $.extend(defaults, custom);
var params = [];
$.each(query_string, function(key,value){
params += key + ': ' + value;
})
var url = custom['url'];
$.ajax({
type: 'GET',
url: '/' + url,
data: params,
dataType: 'html',
error: function(){},
beforeSend: function(){},
complete: function() {},
success: function(response) {
listview.html(response);
}
})
}
$.extend($.fn, {
calculation: function(){
var formReady = new Form($(this));
if(formReady.isCalculable) {
formReady.initiate();
}
}
})
var form = $('fieldset');
form.calculation();
})(jQuery)
Thank you for anyone who responds. I spent a lot of time trying to make this work.
The initial problem as to why the alert() was not being triggered when Form is instantiated is because, as you can see, the elements property belongs to the Form object, not fieldset object. And as you can see in the html, I place the fields as descendents of the fieldset object, not form.