I am currently working on a custom Wordpress plugin which requires the user to create a list in a form, and so to help them populate their list, I have implemented the Wordpress Thickbox. I have made the Thickbox display, with the content I would like, however what I am struggling to do is pass the data back to the original form.
The Original Form is like this:
<input name="input_that_wants_data" id="input_for_data" type="text" />
Click Here for Modal
Just like you would expect any form to be. Basically I want the information from the modal to pass my string back to the input_for_data
The code inside the modal has multiple table rows like this:
<td><input type="checkbox" class="modal_checkbox_class" value="'.$data->value.'"></td>
Basically what I would like to do is build an array of the values of each clicked checkbox, and then use the split function of Javascript to turn it into a string which I would return to the input field outside of the modal.
Any and all help is greatly appreciated. I would prefer a Javascript/JQuery solution to this
I used this tutorial to do something that you want:
https://code.tutsplus.com/tutorials/getting-started-with-the-wordpress-media-uploader--cms-22011
My code looks like this:
function renderMediaUploader() {
'use strict';
var file_frame, image_data;
/**
* If an instance of file_frame already exists, then we can open it
* rather than creating a new instance.
*/
if ( undefined !== file_frame ) {
file_frame.open();
return;
}
/**
* If we're this far, then an instance does not exist, so we need to
* create our own.
*
* Here, use the wp.media library to define the settings of the Media
* Uploader. We're opting to use the 'post' frame which is a template
* defined in WordPress core and are initializing the file frame
* with the 'insert' state.
*
* We're also not allowing the user to select more than one image.
*/
file_frame = wp.media.frames.file_frame = wp.media({
title: 'Select or Upload Media Of Your Chosen Persuasion',
button: {
text: 'Use this media'
},
multiple: true
});
//add items from thickbox to table
file_frame.on( 'select', function() {
var attachment = file_frame.state().get('selection').toJSON();
jQuery.each(attachment, function(i, val){
jQuery('table').show();
jQuery('table tbody').append('<tr class="table_row"><td class="col-sm-2"><img class="img-responsive" src="'+val.url+'"></td><td class="col-sm-8"><input style=" display: block;" type="text" name="entry[url][]" value="'+ val.url +'"></td></tr>');
});
});
// Now display the actual file_frame
file_frame.open();
}
(function( $ ) {
'use strict';
$(function() {
$( '#set-footer-thumbnail' ).on( 'click', function( evt ) {
// Stop the anchor's default behavior
evt.preventDefault();
// Display the media uploader
renderMediaUploader();
});
});
})( jQuery );
Related
I have implemented a custom math plugin and integrated it into ck5. this plugin will convert math latex to image equation and I'm able to render the converted math equation image into a ck5 editor using the below code.
editor.model.change(writer => {
const imageElement = writer.createElement('image', {
src: data.detail.imgURL
});
editor.model.insertContent(imageElement, selection);
});
Still here everything is working fine. when i'm trying to store original latex equation value in image tag as custom attribute (attribute name is data-mathml ). It strips out custom attributes.
So I have gone through the documentation and tried but was not able to add the custom attribute.
Below is my code :
class InsertImage extends Plugin {
init() {
const editor = this.editor;
const view = editor.editing.view;
const viewDocument = view.document;
// Somewhere in your plugin's init() callback:
view.addObserver( ClickObserver );
editor.ui.componentFactory.add('insertImage', locale => {
const view = new ButtonView(locale);
view.set({
label: 'Add Equations',
withText: true,
tooltip: true
});
// Callback executed once the image is clicked.
this.listenTo(view, 'execute', () => {
openModel();
});
return view;
});
window.addEventListener('setDatatoCK', function(data){
const selection = editor.model.document.selection;
editor.model.change( writer => {
const imageElement = writer.createElement( 'image', {
src: data.detail.imgURL,
'data-mthml': data.detail.latexFrmla,
} );
editor.model.insertContent( imageElement, selection );
} );
})
this.listenTo( editor.editing.view.document, 'click', ( evt, data ) => {
if ( data.domEvent.detail == 2 ) {
editorToPopupdoubleClickHandler( data.domTarget, data.domEvent );
evt.stop();
}
}, { priority: 'highest' } );
}
};
I want to add multiple attributes to the image tag. What should I do to add multiple attributes?
(Note: I'm able to create a new custom tag (tag named "math") with multiple attributes but not for image tag)
Please help me with this. this blocker for me.
Methods tried:
In order to achieve this, I have created one custom tag with multiple attributes and append image tags under this custom tag. It's working fine as expected but I want to add multiple attributes to image tag not with the custom tag.
✔️ Expected result
❌ Actual result
📃 Other details
Browser: Google Chrome Version 78.0.3904.108 (Official Build) (64-bit)
OS: macOS Mojave 10.14.6
CKEditor version: CKEditor 5
Installed CKEditor plugins: ckeditor5-editor-classic,ckeditor5-image,ckeditor5-essentials,ckeditor5-basic-styles,ckeditor5-core,ckeditor5-ui
Hope you've already found a solution to this answer. After spending several hours on searching a solution to a similar problem, I've made it working. See below:
// you have to import the insertImage fn to be able to override default imageinsert fn
import { insertImage } from '#ckeditor/ckeditor5-image/src/image/utils.js'
// this method HAVE to be automatically called when ckeditor is onready.
// You can add custom eventlistener or on the html tag just define listener:
// in Vue2 we used to do like this: <ckeditor #ready="someFnOnCkEditorReadyState()" />
someFnOnCkEditorReadyState() {
// as for img tag the options supported by ckeditor is very limited, we must define our properties to extend the used schema
editor.model.schema.extend('image', { allowAttributes: ['data-mathml'] })
// add conversion for downcast
editor.conversion.for('downcast').add(modelToViewAttributeConverter('data-mathml'))
// add conversion for upcast
editor.conversion.for('upcast').attributeToAttribute({
view: {
name: 'image',
key: 'data-mathml',
},
model: 'data-mathml',
})
}
// then you have to implement your custom image insert method
// from now on this will be your default insertImage fn
// this modification might require other modifications for example to add a custom image browser button to the toolbar
otherFnToInsertImg() {
insertImage(editor.model, {
src: image.url,
'data-mathml': 'here comes the magic',
})
}
Hope it helps someone to save some hours. ;)
I am developing one custom plugin for the CKEditor 4.7 which do a simple think take in case user select some stuff it will put it in a div with specific class, else it will put a div with same class just with text like 'Add content here'
I try to use some functions according to CKEditor docs but have something really wrong.
here is the code for the plugin folder name=> customdiv, file=> plugin.js
CKEDITOR.plugins.add('customdiv', {
icons: 'smile',
init: function (editor) {
editor.addCommand( 'customdiv',{
exec : function( editor ){
var selection = editor.getSelection();
if(selection.length>0){
selection='<div class="desktop">'+selection+'</div>';
}else{
selection='<div class="desktop">Add your text here </div>';
}
return {
selection
};
}
});
editor.ui.addButton( 'Customdiv',
{
label : 'Custom div',
command : 'customdiv',
toolbar: 'customdiv',
icon : this.path + 'smile.png'
});
if (editor.contextMenu) {
editor.addMenuGroup('divGroup');
editor.addMenuItem('customdiv', {
label: 'Customdiv',
icon: this.path + 'icons/smile.png',
command: 'customdiv',
group: 'divGroup'
});
editor.contextMenu.addListener(function (element) {
if (element.getAscendant('customdiv', true)) {
}
});
}
}
});
According to some docs it have to return the result good.
Also this is how I call them in my config.js file
CKEDITOR.editorConfig = function (config) {
config.extraPlugins = 'templates,customdiv';
config.allowedContent = true;
config.toolbar = 'Custom';
config.toolbar_Custom = [
{ name: 'divGroup', items: [ 'Customdiv' ] },
{name: 'document', items: ['Source', '-', 'Save', 'Preview', '-', 'Newplugin']},
/* MOre plugins options here */
];
};
Note: the official forum was close and moved here :(
UPDATE
I have change the function like this
exec : function( editor ){
var selection = editor.getSelection();
if(selection.length>0){
selection='<div class="desktop">'+selection+'</div>';
CKEDITOR.instances.editor1.insertHtml( selection );
}else{
selection='<div class="desktop">Add your text here </div>';
CKEDITOR.instances.editor1.insertHtml( selection );
}
}
This makes it work for the else part, but still can't get the selected one.
UPDATE 2
After change of the if I can get data if is selected, but when I do insert selected between <div> I face a problem.
var selection = editor.getSelection();
give like result an object, and I funded out a more complex function and I get collected data like this
var selection = editor.getSelection().getNative();
alert(selection);
from this in alert I see the proper selection and not just object,but when I insert it like
CKEDITOR.instances.editor1.insertHtml('<div class="desktop">' + selection + '</div>');
it just put all selected in one line and not adding the div, new div for else case working with this syntax.
UPDATE 3
The problem now is this function
CKEDITOR.instances.editor1.insertHtml('<div>' + selection + '<div>');
it delete all existing HTML tags even if I add just selection without <div> I am not sure if this is because of the way I insert data or way I collect data, just in alert when I collect data I see correct space like in the editor.
user select some stuff it will put it in a div with specific class
If you want to check if selection is not empty, please instead of selection.length>0 try using !selection().getRanges()[0].collapsed.
If you need something more advanced you could also try using
!!CKEDITOR.instances.editor1.getSelection().getSelectedText() to see if any text was selected and !!CKEDITOR.instances.editor1.getSelection().getSelectedElement() to see if any element like e.g. image, tabl,e widget or anchor was selected.
EDIT:
If you need selected HTML please use CKEDITOR.instances.editor1.getSelectedHtml().getHtml();
Please also have a look at CKEditor documentation:
https://docs.ckeditor.com/#!/api/CKEDITOR.editor-method-getSelectedHtml
https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_dom_documentFragment.html#method-getHtml
https://docs.ckeditor.com/#!/api/CKEDITOR.dom.selection-method-getSelectedText
https://docs.ckeditor.com/#!/api/CKEDITOR.dom.selection-method-getSelectedElement
I have looked through all of the similar questions available at the time of this question, and none of the solutions presented worked in the below code. Google was also not helpful except that I did find a few issues with dynamic code where the entire menu was not wrapped, but those issues should be fixed with either the trigger or enhanceWithin methods - which have been tried here.
I am a fairly new with javascript and the jquery library and this is my first app with jquery mobile.
The raw html as generated from the php file:
<div class="cell_container force_org_select">
<label for"force_org[new_555]" class="ui-hidden-accessible">Troop Type</label>
<select name="force_org[new_555]" id="force_org[new_555]" class="roster_cell" data-mini="true">
<option value="hq">HQ</option>
<option value="elite">Elite</option>
<option value="solo">Solitaire</option>
<option value="formation">Std Formation</option>
</select>
The Javascript function that handles the dynamic injection:
$(document).on('click','.add_item', function(event) {
event.preventDefault();
var the_link = $(this).attr('href')
var area = getParameterByName(the_link, 'area');
var type = getParameterByName(the_link, 'type');
var squad_id = getParameterByName(the_link, 'squad_id');
var vehicle = getParameterByName(the_link, 'vehicle');
var divider = getParameterByName(the_link, 'divider');
var preset = $('#preset').val();
$.post(cmd_ajax.ajaxurl,{action: 'cmd_add_item_mobile', type: type, preset: preset, squad_id: squad_id, vehicle: vehicle, divider: divider}, function(data) {
if(type == 'squad' || type == 'divider') {
$('#list').append(data).enhanceWithin();
//$('#list').append(data).trigger("refresh");
//$('#list').append(data).trigger("create");
$('.squad_help_button').tooltipster({
contentCloning: true,
trigger: 'custom',
triggerOpen: {
click: true,
tap: true
},
triggerClose: {
click: true,
tap: true
}
});
}
else {
$('#' + area).append(data).enhanceWithin();
}
//console.log("squad_id:"+this_id);
set_unit_sortable();
});
return false;
});
I also tried adding the .selectmenu("refresh",true) within the function and that seems to do nothing. The custom selects that are not dynamically generated work fine.
If I use the data-native-menu="false" attribute on the generated select menus, the popup does not function and you cannot select anything, if I remove the attribute, the native select works as it should.
I thought about using a selectmenu() refresh at the very end of the function, but I can't seem to catch the element id of the select menu either. My only guess is that it isn't created yet in the DOM when I try to retrieve it.
i'm struggeling with one challenge to do in my custom theme for Wordpress. I want to have content specific controls in my Theme Customizer. I know there is option "active_callback", but this is not sufficient for my purpose and i read 2 documentation articles about customizer and this https://make.wordpress.org/core/2014/07/08/customizer-improvements-in-4-0/ article, but still have no clue, here is what i want to achieve:
For example, i want to have "show sidebar" checkbox, but this checkbox should be more contextual specifix. For example, when i will be on homepage, there will be just one checkbox as "Show sidebar default" but when i will go into some post, i want there 3 checkboxes:
"Show sidebar default" - id="show_sidebar"
"Show sidebar in Post archive page" - id="show_sidebar_archive_{post_type}"
"Show sidebar for this post" - id="show_sidebar_singular_{post_id}"
So when i want to have this kind of specific IDs for control, just active_callback is not enought, becauce it can just show/hide controls, i can't create new when URL in iframe changes.
There could be 2 sollutions:
1. Better - when i could somehow create/remove controls by context, it would be best solution. If it's somehow possible with customizer API, give me som hint please
2. Not good, but sufficient - is at least possible somehow reload whole /wp-admin/customize.php?url= with new clicked url? this could be enought for a while
thx for any advices!
Ok, i figured out that second solution, here is code. It's enought for me for now.
'use strict';
(function ($) {
/**
* This is important fix for Theme Customizer
* It will change whole customizer url, because we need to load
* all controls ahan for new url, because of hierarchical options
*/
if ( /\/customize\.php$/.test( window.location.pathname ) ) {
wp.customize.bind( 'preview-ready', function() {
var body = $( 'body' );
body.off( 'click.preview' );
body.on( 'click.preview', 'a[href]', function( event ) {
var link, isInternalJumpLink;
link = $( this );
isInternalJumpLink = ( '#' === link.attr( 'href' ).substr( 0, 1 ) );
event.preventDefault();
if ( isInternalJumpLink && '#' !== link.attr( 'href' ) ) {
$( link.attr( 'href' ) ).each( function() {
this.scrollIntoView();
} );
}
/*
* Note the shift key is checked so shift+click on widgets or
* nav menu items can just result on focusing on the corresponding
* control instead of also navigating to the URL linked to.
*/
if ( event.shiftKey || isInternalJumpLink ) {
return;
}
//self.send( 'scroll', 0 );
//self.send( 'url', link.prop( 'href' ) );
var newUrl = link.prop( 'href' );
var currentUrl = window.location.href;
var customizeUrl = currentUrl.substring(0, currentUrl.indexOf("?url=") + 5) + newUrl;
// Reload whole customizer for new url
window.parent.location.replace(customizeUrl);
});
} );
}
})(jQuery);
//# sourceMappingURL=customizer.js.map
I wanted to hide some issue link outward & inwards strings of Link type from the Link Issues Popup Window using java script.
I have tried using java script but I am not getting the popup screen from the java script.
Please see the screenshot below :
Can anyone tell me how can I get this popup screen in the java script?
Is there any other method to hide this?
Thanks & Regards,
Renuka.
To hide the clone issue link every page:
edit the file system-webresources-plugin.xml (should be at /atlassian-jira/WEB-INF/classes/), and add to <web-resource key="jira-fields"> this code:
<resource type="download" name="myScript.js" location="/includes/jira/field/script.js">
<param name="source" value="webContextStatic"/>
</resource>
than, on /includes/jira/field/myScript.js write this:
AJS.$(document).ready(function() {
if (AJS.$("#link-type option[value*='clon']").size() > 0) {
// will work even when right clicking on More
// Actions->Link & open it into a new window
AJS.$("#link-type option[value*='clon']").remove()
} else if (AJS.$("#link-issue").size() > 0) {
// will work in case the link menu showing via popup
AJS.$("#link-issue").click(function(){
// wait for the popup to show, and remove the clone options
setTimeout(function (){
AJS.$("#link-type option[value*='clon']").remove();
}, 300);
});
}
});
restart Jira and it that it!
The script attaches a function to the link-menu opening, than gives the menu 0.3 seconds to load, and removes the unwanted items. If it doesn't work well for you, try to raise the timeout from 300 to 500-1000.
On jira 4, run instead:
AJS.$("#issue-link-link-type option[value*='clon']").remove();
The previous solution has an issue:
It will only work when clicking the "Link Issue"-Menu-Item.
When I use the Point (.)-Shortcut-Menu, it won't remove the issue types.
I have established the following solution:
JS-Binding-Part:
AJS.$(document).ready(function() {
JIRA.bind(JIRA.Events.NEW_CONTENT_ADDED, function(e, context, reason) {
hideIssueLinkTypes();
});
});
JS-Backing-Function:
function hideIssueLinkTypes() {
var apiURL = "/rest/scriptrunner/latest/custom/getHiddenLinkTypes"
$.getJSON( apiURL, {
}).done(function( objectData ) {
$.each( objectData, function( i, item ) {
var issueLinkType = item.issueLinkType[0];
AJS.$("#link-type option[value='"+issueLinkType.inwardDescription+"']").remove();
AJS.$("#link-type option[value='"+issueLinkType.outwardDescription+"']").remove();
});
});
}
Scriptrunner-REST-Endpoint:
import com.onresolve.scriptrunner.runner.rest.common.CustomEndpointDelegate
import groovy.json.JsonBuilder
import groovy.transform.BaseScript
import com.atlassian.jira.issue.link.DefaultIssueLinkTypeManager
import com.atlassian.jira.issue.link.IssueLinkTypeManager
import com.atlassian.jira.issue.link.IssueLinkType
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.config.properties.ApplicationProperties
import javax.ws.rs.core.MultivaluedMap
import javax.ws.rs.core.Response
#BaseScript CustomEndpointDelegate delegate
String HIDDEN_IDENT="[hidden]"
getHiddenLinkTypes(httpMethod: "GET") { MultivaluedMap queryParams, String body ->
def appProperties = ((ApplicationProperties) ComponentAccessor.getComponentOfType(ApplicationProperties.class));
def appClonersLinkTypeName = appProperties.getDefaultBackedText("jira.clone.linktype.name");
def jsBuilder=new JsonBuilder();
def issueLinkTypes = ((IssueLinkTypeManager) ComponentAccessor.getComponentOfType(IssueLinkTypeManager.class)).getIssueLinkTypes();
jsBuilder issueLinkTypes.findAll({it.getName().contains(HIDDEN_IDENT) || it.getName()==appClonersLinkTypeName }),
{ IssueLinkType linkType ->
issueLinkType linkType.getId(),
name: linkType.getName(),
inwardDescription: linkType.getInward(),
outwardDescription: linkType.getOutward()
}
return Response.ok(jsBuilder.toString()).build();
}
What you can do then ist just annotate and Link-Type with putting [hidden] in the link name and it will disappear for all users (It can still be programmatically added though or created by cloning).
If you don't have Scriptrunner or don't need the dynamic nature of the implementation, you can still hard-code the values as Kuf described in the answer above in hideIssueTypes() like this:
AJS.$("#issue-link-link-type option[value*='clon']").remove();