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

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

Related

Tinymce multiple instances in same page

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);
}
};
});

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

Symfony collection form data is not in post params

Today our user reported that saving his CV does not work, that it does not save his Skills, languages, driving license level, schools and prev. employments.
That is the Collection forms that i use on 2 parts of website (CV and Offers)...
Funny is that we tested it before going live and running live from IE6 to any other newer browser.
Collections is added correctly using "add foobar record" button, when there is any record in DB it appears in edit correctly, when i edit these existing it will be saved, if i remove them than they will be removed.
But when i add new, these new records is not in Form post data. I cant understand if its part of form, html is rendered correctly, why it does not include it in post...
These collections works with Offer entity, saved updated added... no problem. i have checked the controller code, the javascript code, the entity code, the html code, the collection templates, the form types..
Here is DB structure:
here is how i add collection in botz CV and Offer
<div class="tbl">
<div class="row">
<div class="col" style="text-align: center; width: 100%;">Počítačové znalosti</div>
</div>
<div class="divider"></div>
<div class="skills" data="0" data-prototype="{% filter escape %}{% include 'TvarplastTopzamBundle:Collections:SkillCollection.html.twig' with {'form': form.skills.vars.prototype} %}{% endfilter %}">
{% for skill in form.skills %}
<div class="row">
{% include 'TvarplastTopzamBundle:Collections:SkillCollection.html.twig' with {'form': skill} %}
</div>
<script type="text/javascript">$(".skills").data("index", {{ loop.index }});</script>
{% endfor %}
</div>
<div class="row">
<div class="col">
Pridať počítačovú znalosť
</div>
</div>
</div>
Problem cannot be with entity, because if some relation exists in DB that is displayed as collection, and if its edited, it can be changed or removed, and its displayed in post parameters, then entity, form type, cannot be wrong.
but i handle form like this:
public function zivotopisAction(\Symfony\Component\HttpFoundation\Request $request, $showmsg = false) {
if (!$this->get("data")->hasPerm(Role::WORKER, $this->getUser())) {
$message["show"] = true;
$message["text"] = "Nemáte požadované oprávnenia. Stránka nemôže byť zobrazená.";
$message["type"] = "box-red";
return new \Symfony\Component\HttpFoundation\Response($this->renderView("TvarplastTopzamBundle::error.html.twig", array("message" => $message)));
}
$return = array();
$message = array("show" => $showmsg, "type" => "", "text" => "");
if ($message["show"]) {
$message["text"] = "Je nutné vyplniť nasledujúce informácie pre pokračovanie.";
$message["type"] = "box-red";
}
$em = $this->getDoctrine()->getManager();
if (!is_null($this->getUser()->getZivotopis())) {
$zivotopis = $em->getRepository("TvarplastTopzamBundle:Zivotopis")->find($this->getUser()->getZivotopis()->getId());
} else {
$zivotopis = new \Tvarplast\TopzamBundle\Entity\Zivotopis();
}
$originalSkills = new \Doctrine\Common\Collections\ArrayCollection();
if ($zivotopis->getSkills()) {
foreach ($zivotopis->getSkills() as $skill) {
$originalSkills->add($skill);
}
}
$originalLanguages = new \Doctrine\Common\Collections\ArrayCollection();
if ($zivotopis->getLanguages()) {
foreach ($zivotopis->getLanguages() as $language) {
$originalLanguages->add($language);
}
}
$originalDrivingskills = new \Doctrine\Common\Collections\ArrayCollection();
if ($zivotopis->getSkilldriving()) {
foreach ($zivotopis->getSkilldriving() as $skilldriving) {
$originalDrivingskills->add($skilldriving);
}
}
$originalEmployments = new \Doctrine\Common\Collections\ArrayCollection();
if ($zivotopis->getEmployments()) {
foreach ($zivotopis->getEmployments() as $employment) {
$originalEmployments->add($employment);
}
}
$originalSchools = new \Doctrine\Common\Collections\ArrayCollection();
if ($zivotopis->getSchools()) {
foreach ($zivotopis->getSchools() as $school) {
$originalSchools->add($school);
}
}
$form = $this->createForm(new \Tvarplast\TopzamBundle\Form\ZivotopisType(), $zivotopis, array(
'action' => $this->generateUrl('zivotopis'),
));
$form->handleRequest($request);
if ($form->isValid()) {
//var_dump($_POST); die();
foreach ($originalSkills as $skill) {
if (false === $zivotopis->getSkills()->contains($skill)) {
$skill->getZivotopis()->removeElement($zivotopis);
$em->persist($skill);
$em->remove($skill);
}
}
foreach ($originalLanguages as $language) {
if (false === $zivotopis->getLanguages()->contains($language)) {
$language->getZivotopis()->removeElement($zivotopis);
$em->persist($language);
$em->remove($language);
}
}
foreach ($originalDrivingskills as $drivingskill) {
if (false === $zivotopis->getSchools()->contains($drivingskill)) {
$drivingskill->getZivotopis()->removeElement($zivotopis);
$em->persist($drivingskill);
$em->remove($drivingskill);
}
}
foreach ($originalEmployments as $employment) {
if (false === $zivotopis->getEmployments()->contains($employment)) {
$employment->getZivotopis()->removeElement($zivotopis);
$em->persist($employment);
$em->remove($employment);
}
}
foreach ($originalSchools as $school) {
if (false === $zivotopis->getSchools()->contains($school)) {
$school->getZivotopis()->removeElement($zivotopis);
$em->persist($school);
$em->remove($school);
}
}
$zivotopis->upload();
$zivotopis->setBasicUser($this->getUser());
$zivotopis = $form->getData();
$em->persist($zivotopis);
$em->flush();
$message["text"] = ($this->container->get('security.context')->isGranted('ROLE_WORKER') ? "Životopis" : "Profil") . " bol úspešne uložený.";
$message["type"] = "box-yellow";
$message["show"] = true;
}
$return["form"] = $form->createView();
$return["message"] = $message;
return $return;
and my javascript looks like this:
$(document).ready(function() {
$.extend({getDeleteLinkCode: function(div) {
return '<div class="col" style="margin-top: 8px; margin-left: 3px;"><a href="#" style="margin-top: 5px;" >Odstrániť</a></div>';
}});
$.extend({addSubFormSelectChangeListener: function(collectionHolder, formRow, div) {
formRow.find('select' + (!div ? ':first' : '')).on("change", function() {
var org = $(this);
if (collectionHolder.find(!div ? "tr" : "div").size() > 1) {
collectionHolder.find(!div ? "tr" : "div").each(function() {
if (org.val() === $(this).find('select:first').val() && org.attr("id") !== $(this).find("select:first").attr("id")) {
org.parent().parent().remove();
}
});
}
});
}});
$.extend({addSubForm: function(collectionHolder, div) {
var prototype = collectionHolder.data('prototype');
var index = collectionHolder.data('index');
index = (index !== parseInt(index) ? 0 : index);
var form = prototype.replace(/__name__/g, index);
var formRow = $((div ? '<div class="row"></div>' : '<tr></tr>')).append(form);
var removeFormRow = $($.getDeleteLinkCode(div));
formRow.append(removeFormRow);
collectionHolder.data('index', index + 1);
collectionHolder.append(formRow);
removeFormRow.on('click', function(e) {
e.preventDefault();
formRow.remove();
});
$.addSubFormSelectChangeListener(collectionHolder, formRow, div);
}});
function addSubFormItemDeleteLink(collectionHolder, $tagFormLi, div, notag) {
var $removeFormA = $($.getDeleteLinkCode(div));
$tagFormLi.append($removeFormA);
$removeFormA.on('click', function(e) {
e.preventDefault();
$tagFormLi.remove();
});
$.addSubFormSelectChangeListener(collectionHolder, $tagFormLi, div);
}
jQuery.fn.toggleOption = function(show) {
$(this).toggle(show);
if (show) {
if ($(this).parent('span.toggleOption').length) {
$(this).unwrap();
}
} else {
if ($(this).parent('span.toggleOption').length === 0) {
$(this).wrap('<span class="toggleOption" style="display: none;" />');
}
}
};
$.extend({comboFilter: function(inputField, comboBox) {
$("#" + inputField).delayBind("input", function() {
var inputValue = $(this).val().toLowerCase();
var combobox = document.getElementById(comboBox);
$("#" + comboBox).children("span").children("optgroup").each(function() {
$(this).toggleOption(true);
});
optionToSelect = false;
$("#" + comboBox + " option").each(function() {
if ($(this).text().toLowerCase().replace(/<.+?>/g, "").replace(/\s+/g, " ").indexOf(inputValue.replace(/<.+?>/g, "").replace(/\s+/g, " ")) !== -1) {
optionToSelect = $(this);
$(this).toggleOption(true);
} else {
$(this).toggleOption(false);
}
if (optionToSelect !== false) {
$(optionToSelect).select();
}
});
$("#" + comboBox).children("optgroup").each(function() {
if ($(this).children("option").length <= 0) {
$(this).toggleOption(false);
} else {
$(this).toggleOption(true);
}
});
if ($("#" + comboBox).children("optgroup").length <= 0) {
$("#" + comboBox).children("span").children("optgroup").children("option").each(function() {
$(this).parent().toggleOption(true);
});
}
if (inputValue === '') {
combobox[0].selected = true;
$("#" + comboBox).children("span").children("optgroup").each(function() {
$(this).toggleOption(true);
});
}
}, 50);
}});
/* skills */
holderSkills = $('div.skills');
holderSkills.find('div.row').each(function() {
addSubFormItemDeleteLink(holderSkills, $(this), false, false);
});
$(".add_skill_link").on('click', function(e) {
e.preventDefault();
$.addSubForm(holderSkills, true);
});
/* driving */
holderDriving = $('div.skilldriving');
holderDriving.find('div.deletehere').each(function() {
addSubFormItemDeleteLink(holderDriving, $(this), true, true);
});
$(".add_driving_link").on('click', function(e) {
e.preventDefault();
$.addSubForm(holderDriving, true);
});
/* Lang */
holderLanguages = $('div.languages');
holderLanguages.find('div.row').each(function() {
addSubFormItemDeleteLink(holderLanguages, $(this), false, false);
});
$(".add_lang_link").on('click', function(e) {
e.preventDefault();
$.addSubForm(holderLanguages, true);
});
/* Emp */
holderEmployments = $('div.employments');
holderEmployments.find('div.deletehere').each(function() {
addSubFormItemDeleteLink(holderEmployments, $(this), false, false);
});
$(".add_zam_link").on('click', function(e) {
e.preventDefault();
$.addSubForm(holderEmployments);
});
/* Schools */
holderSchools = $('div.schools');
holderSchools.find('div.deletehere').each(function() {
addSubFormItemDeleteLink(holderSchools, $(this), false, false);
});
$(".add_Schools_link").on('click', function(e) {
e.preventDefault();
$.addSubForm(holderSchools);
});
});
Any idea where can the problem be?
Thank you very much
Thanks to Dynamically added form field not showing up in POSTed data
Solved by switching first 2 lines to be {form} first and div the second
i had something like
<div .....>
{form....}
some html
</div>
<div>
htmlhhtml
</div>
</div>
{endform}
That was the reason why browser was not able to read newly added items

bootstrap typeahead url/redirect

$(function(){
var orthoObjs = {};
var orthoNames = [];
var throttledRequest = _.debounce(function(query, process){
$.ajax({
url: 'json/ortho4.json'
,cache: false
,success: function(data){
orthoObjs = {};
orthoNames = [];
_.each( data, function(item, ix, list){
orthoNames.push( item.searchPhr );
orthoObjs[ item.searchPhr ] = item;
});
process( orthoNames );
}
});
}, 300);
$(".typeahead").typeahead({
source: function ( query, process ) {
throttledRequest( query, process );
}
,updater: function (item) {
var url = "orthoObjs[item.searchUrl]";
window.location = url;
Whats the best way to get the redirect to work? I have seen similar questions, but can't get this to work. Documentation on typeahead isn't great. I am using underscore.js for the each function. Just want a simple search query that redirects when the user selects.
I actually got this to work. I got a little help... but here it is. There is the JSON file..
[
{ "id":1, "searchUrl":"invisalign.html", "name":"invisalign" }
,{ "id":2, "searchUrl":"invisalign.html", "name":"invisalign teen" }
,{ "id":3, "searchUrl":"clearbraces.html", "name":"clear braces" }
]
And the HTML code....
Lots of good stuff here.. http://fusiongrokker.com/post/heavily-customizing-a-bootstrap-typeahead
And the search code..
<form method="post" id="myForm" class="navbar-search pull-left">
<input
type="text"
class="search-query typeahead"
placeholder="Search Our Website"
autocomplete="off"
data-provide="typeahead"
/>
<i class="fa-icon-search icon-black"></i>
</form> </li>
$(function(){
var bondObjs = {};
var bondNames = [];
$(".typeahead").typeahead({
source: function ( query, process ) {
//get the data to populate the typeahead (plus an id value)
$.ajax({
url: '/json/bonds.json'
,cache: false
,success: function(data){
bondObjs = {};
bondNames = [];
_.each( data, function(item, ix, list){
bondNames.push( item.name );
bondObjs[ item.name ] = item.searchUrl;
});
process( bondNames );
}
});
}
, updater: function ( selectedName ) {
window.location.href =bondObjs[ selectedName ];
}
});
});
</script>

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.