Customizing dropdown button for CKeditor 5 - javascript

Managed to add a custom dropdown button to the toolbar:
But I don't know how to add a label or an icon to it.
Here's my code:
import Plugin from '#ckeditor/ckeditor5-core/src/plugin';
import Model from '#ckeditor/ckeditor5-ui/src/model';
import { createDropdown, addListToDropdown } from '#ckeditor/ckeditor5-ui/src/dropdown/utils';
import Collection from '#ckeditor/ckeditor5-utils/src/collection';
import imageIcon from '#ckeditor/ckeditor5-core/theme/icons/image.svg';
export default class ImageDropdown extends Plugin {
static get pluginName() {
return 'ImageDropdown';
}
init() {
const editor = this.editor;
const t = editor.t;
const defaultTitle = t('Add image');
const dropdownTooltip = t('Image');
// Register UI component
editor.ui.componentFactory.add('imageDropdown', locale => {
const dropdownView = createDropdown( locale );
dropdownView.set({
label: 'Image',
tooltip: true
});
dropdownView.buttonView.set( {
isOn: false,
withText: true,
tooltip: dropdownTooltip
});
dropdownView.extendTemplate( {
attributes: {
class: [
'ck-image-dropdown'
]
}
});
// The collection of the list items.
const items = new Collection();
items.add( {
type: 'button',
model: new Model( {
label: 'Uppload image',
icon: imageIcon
})
});
items.add( {
type: 'button',
model: new Model( {
label: 'Image URL',
icon: imageIcon
})
});
// Create a dropdown with a list inside the panel.
addListToDropdown( dropdownView, items );
return dropdownView;
});
}
}

Setting labels, icons etc. for a dropdown button should take place on the dropdown's view instance:
dropdownView.buttonView.set({
label: 'some-label',
icon: 'path/to/some/icon'
tooltip: true
});
Note that these properties are observable and can be dynamically evaluated based on some state using the ObservableMixin#bind function.
See an example here: https://github.com/ckeditor/ckeditor5-alignment/blob/894745ecb1e8bd94286b4089eb16079034eb8a0b/src/alignmentui.js#L107-L124

Related

How can I add action menu in usermenu odoo15

In odoo 15, how can I add new action menu in user menu? In other odoo versions (13 and 14), it was possible by inheriting from UserMenu.Actions.
In odoo 15, I tried the following code but it is not working.
Thanks for any suggestion
/** #odoo-module **/
import { registry } from "#web/core/registry";
import { preferencesItem } from "#web/webclient/user_menu/user_menu_items";
export function UserLog(env) {
return Object.assign(
{},
preferencesItem(env),
{
type: "item",
id: "log",
description: env._t("UserRecent Log"),
callback: async function () {
const actionDescription = await env.services.orm.call("user.recent.log", "action_get");
actionDescription.res_id = env.services.user.userId;
env.services.action.doAction(actionDescription);
},
sequence: 70,
}
);
}
registry.category("user_menuitems").add('profile', UserLog, { force: true })
This is my model code.
class UserRecentLog(models.Model):
_name = 'user.recent.log'
_order = "last_visited_on desc"
#api.model
def action_get(self):
return self.env['ir.actions.act_window']._for_xml_id('user_recent_log.action_user_activity')
This is my xml view.
<!-- actions opening views on models -->
<record model="ir.actions.act_window" id="action_user_activity">
<field name="name">User Recent Log(s)</field>
<field name="res_model">user.recent.log</field>
<field name="view_mode">tree,form</field>
<field name="view_id" ref="user_activity_view_tree"/>
</record>
You don't need to change anything, your code should work. You can check the user preferences menu item in web module (similar to your menu item).
export function preferencesItem(env) {
return {
type: "item",
id: "settings",
description: env._t("Preferences"),
callback: async function () {
const actionDescription = await env.services.orm.call("res.users", "action_get");
actionDescription.res_id = env.services.user.userId;
env.services.action.doAction(actionDescription);
},
sequence: 50,
};
}
registry
.category("user_menuitems")
.add("profile", preferencesItem)
There is another implementation in hr module:
import { registry } from "#web/core/registry";
import { preferencesItem } from "#web/webclient/user_menu/user_menu_items";
export function hrPreferencesItem(env) {
return Object.assign(
{},
preferencesItem(env),
{
description: env._t('My Profile'),
}
);
}
registry.category("user_menuitems").add('profile', hrPreferencesItem, { force: true })
So you can rewrite your code above as following:
import { registry } from "#web/core/registry";
import { preferencesItem } from "#web/webclient/user_menu/user_menu_items";
export function UserLog(env) {
return Object.assign(
{},
preferencesItem(env),
{
type: "item",
id: "log",
description: env._t("Log"),
callback: async function () {
const actionDescription = await env.services.orm.call("res.users.log", "action_user_activity");
env.services.action.doAction(actionDescription);
},
sequence: 70,
}
);
}
registry.category("user_menuitems").add('profile', UserLog, { force: true })
Edit:
The tree view mode is ignored when executing the window action.
The _executeActWindowAction will check for the tree view type in the views registry to construct the views object and unfortunately, the tree view mode was not added to that registry.
To show the tree view, you can add [false, 'list'] to the views list and specify the view type (list) in the doAction options:
actionDescription.views.push([actionDescription.view_id[0], 'list'])
env.services.action.doAction(actionDescription, {viewType: 'list'});
Or update the views list and change tree to list:
actionDescription.views[0][1] = 'list';
Of course , you can do the same in the action_get method:
action = self.env['ir.actions.act_window']._for_xml_id('user_recent_log.action_user_activity')
action['views'][0] = action['view_id'][0], 'list'
return action

how to solve Trying to get property 'bids' of non-object error

I want to display data from bid table in a form of datatable. But I get this error
"Trying to get property 'bids' of non-object" if it doesn't have bids.The bids model is connected to auction model and the auction model is connected to media site model. How to make it display blank record if it doesn't have data.
Here is my controller:
<?php
namespace App\Http\Controllers;
use App\Auction;
use App\Bid;
use App\User;
use App\Media;
use App\MediaSite;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class MediaSiteController extends Controller
{
public function show(MediaSite $mediaSite)
{
$auction = $mediaSite->auction;
$bids = $auction->bids;
return view('admin.media-site.show', ['mediaSite' => $mediaSite,'auction' => $auction], compact('auction'));
}
My view:
<body>
<div id="datatable-bid"></div>
</body>
<script>
$(document).ready(function () {
var datatableBid = $('#datatable-bid').mDatatable({
// datasource definition
data: {
type: 'local',
source: {!! json_encode($auction->bids) !!},
pageSize: 10
},
// layout definition
layout: {
theme: 'default', // datatable theme
class: '', // custom wrapper class
scroll: false,
footer: false // display/hide footer
},
// column sorting
sortable: true,
pagination: true,
search: {
input: $('#panel-search')
},
// columns definition
columns: [
{
field: "price",
title: "Price",
}, {
field: "month",
title: "Month",
},{
field: "user_id",
title: "User Id",
}
]
});
</script>
Here is my error:
Trying to get property 'bids' of non-object
place following after $auction = $mediaSite->auction;
if($auction){
$bids = $auction->bids;
}else{
//put following line or whatever you need to do if there is no data comes
$auction = [];
}
In the show() function make these changes
$auction = $mediaSite->auction;
if($auction) {
$bids = $auction->bids;
} else {
$bids = [];
}
// now send $bids to view along with $auction
// may be like this
// return view(..., compact($auction, $bids));
Then, in your view make this change
// datasource definition
data: {
type: 'local',
source: {!! json_encode($bids) !!},
pageSize: 10
},
See if this helps.

How to split up code for better readability?

I want to clean up my code for better readability and put some code in extra js-files but nothing I've tried has worked.
It's a SubApp and part of a larger Project (Shopware) that is still using ExtJs 4.1.
I have a "main/window.js" that extends 'Ext.window.Window'.
initComponent looks like this:
initComponent: function () {
//...
me.dockedItems = [
me.createTopToolbar(),
];
//...
}
createTopToolbar is a Method inside "main/window.js" that return a Ext.toolbar.Toolbar with some elements.
My goal is to put this method in an extra file.
I tried to create a new static/singleton class like this
Ext.define('myapp.myplugin.view.main.Toptoolbar', {
singleton: true,
createTopToolbar: function(){
// ...
return toolbar;
}
But inside "main/window.js" i cannot call it using myapp.myplugin.view.main.Toptoolbar.createTopToolbar(), or main.Toptoolbar.createTopToolbar()
In app.js i tried to include it like this
views: [
'main.Window',
'main.Toptoolbar',
],
but it doesnt work.
I have no experience with ExtJs and search for hours...hope someone can help me.
Thank you
Edit
To answer the question why i'm building the toolbar within a function.
The whole functions looks like this:
createTopToolbar: function () {
var me = this;
var shopStore = Ext.create('Shopware.apps.Base.store.Shop');
shopStore.filters.clear();
shopStore.load({
callback: function(records) {
shopCombo.setValue(records[0].get('id'));
}
});
var shopCombo = Ext.create('Ext.form.field.ComboBox', {
name: 'shop-combo',
fieldLabel: 'Shop',
store: shopStore,
labelAlign: 'right',
labelStyle: 'margin-top: 2px',
queryMode: 'local',
valueField: 'id',
editable: false,
displayField: 'name',
listeners: {
'select': function() {
if (this.store.getAt('0')) {
me.fireEvent('changeShop');
}
}
}
});
var toolbar = Ext.create('Ext.toolbar.Toolbar', {
dock: 'top',
ui: 'shopware-ui',
items: [
'->',
shopCombo
]
});
return toolbar;
}
And i dont want the whole code inside my "main/window.js".
I'm not sure using the xtype solution provided by Jaimee in this context because i dont realy extend 'Ext.toolbar.Toolbar'. I just need a "wrapper" for my "shopCombo" code and return 'Ext.toolbar.Toolbar' with shopCombo as an item.
Create the toolbar as you would any other view, and create an 'xtype' to add it to your window.
Ext.define('myapp.myplugin.view.main.Toptoolbar', {
extends: 'Ext.toolbar.Toolbar',
xtype: 'mytoptoolbar',
dock: 'top',
ui: 'shopware-ui',
items :[
'->',
{
xtype: 'combobox',
name: 'shop-combo',
fieldLabel: 'Shop',
store: 'shopStore',
labelAlign: 'right',
labelStyle: 'margin-top: 2px',
queryMode: 'local',
valueField: 'id',
editable: false,
displayField: 'name',
listeners: {
'select': function() {
if (this.store.getAt('0')) {
me.fireEvent('changeShop');
}
}
}
}]
});
And then simply add it to your window's docked items like you would any other component:
initComponent: function () {
//...
me.dockedItems = [
{
xtype: 'mytoptoolbar'
}
];
//...
}
And the load listener can be added to the store.
Ext.define('Shopware.apps.Base.store.Shop', {
// ....
listeners:
{
load: function() {
Ext.ComponentQuery.query("combobox[name='shop-combo']")[0].setValue(...)
}
}
However, I'd suggest just setting a starting value for the combobox if it's a predictable value. You'll need to add the store to your controller's stores config if you haven't already.
You could use a factory pattern like so:
Ext.define('ToolbarFactory', {
alias : 'main.ToolbarFactory',
statics : {
/**
* create the toolbar factory
*/
factory : function() {
console.log('create the toolbar');
var toolbar = ....;
return toolbar;
}
}
});
Then you can create the Toolbar this way:
initComponent: function () {
//...
me.dockedItems = [
ToolbarFactory.factory();
];
//...
}
Depending on your build process you may need to add a requires statement.

Unable to create a delete button in Meteor using reactive-table

I building a sortable table in Meteor with Reactive-Table and having trouble getting my delete button to work for removing entries from the table.
Please see my javascript code below:
Movies = new Meteor.Collection("movies");
if (Meteor.isClient) {
Template.body.events({
"submit .new-movie": function (event) {
var title = event.target.title.value;
var year = event.target.year.value;
var genre = event.target.genre.value;
Movies.insert({
title: title,
year: year,
genre: genre
});
event.target.title.value = "";
event.target.year.value = "";
event.target.genre.value = "0";
return false;
}
});
Template.moviestable.events({
"click .deletebtn": function (event) {
Movies.remove(this._id);
}
});
Template.moviestable.helpers({
movies : function () {
return Movies.find();
},
tableSettings : function () {
return {
showFilter: false,
fields: [
{ key: 'title', label: 'Movie Title' },
{ key: 'year', label: 'Release Year' },
{ key: 'genre', label: 'Genre' },
{ key: 'edit', label: 'Edit', fn: function () { return new Spacebars.SafeString('<button type="button" class="editbtn">Edit</button>') } },
{ key: 'delete', label: 'Delete', fn: function () { return new Spacebars.SafeString('<button type="button" class="deletebtn">Delete</button>') } }
]
}
}
});
}
Can anyone tell me what I'm doing wrong?
In the reactive tables docs, there's an example of how to delete rows from the table. Adapting the example in the docs for your needs, your event should look like this:
Template.moviestable.events({
'click .reactive-table tbody tr': function (event) {
event.preventDefault();
var objToDelete = this;
// checks if the actual clicked element has the class `deletebtn `
if (event.target.className == "deletebtn") {
Movies.remove(objToDelete._id)
}
}
});
The problem you are having is that you are trying to find the _id property on the button click instead of the row click.
If you do console.log(this) on your button click event (as you have it in your question above) you will get something like this Object {key: "delete", label: "", fieldId: "2", sortOrder: ReactiveVar, sortDirection: ReactiveVar} which does not contain the property _id
It is easier to register the row click, where the row object is the actual document you are trying to delete, and then check if the event's target has the delete class you added.

How to disable the delete button using if condition in Extjs

How to disable the delete button using if condition in Extjs for ex;i want to disable the button if it satifies the given if condition else remain enabled.
if(validAction(entityHash.get('entity.xyz'),actionHash.get('action.delete')))
This is the grid Delete button code.
Ext.reg("gridheaderbar-inActive", Ad.GridInActiveButton,{
xtype: 'tbspacer', width: 5
});
Ad.GridCampDeleteButton = Ext.extend(Ext.Toolbar.Button, {
//text: 'Delete',
cls: 'ad-img-button',
width:61,
height:40,
iconCls: 'ad-btn-icon',
icon: '/webapp/resources/images/btn_del.png',
handler:function(){
statusChange(this.parentBar.parentGrid, 'Delete')
}
});
create actioncolumn and make custom renderer:
{
xtype: 'actioncolumn',
width: 38,
renderer: function (val, metadata, record) {
this.items[0].icon = '${CONTEXT_PATH}/images/' + record.get('fileType') + '.png';
this.items[0].disabled = !record.get('isDownloadActionEnable');
this.items[1].disabled = !record.get('isDeleteActionEnable');
metadata.style = 'cursor: pointer;';
return val;
},
items: [
{
icon: '${CONTEXT_PATH}/images/pdf.png', // Use a URL in the icon config
tooltip: 'Download',
handler: function (grid, rowIndex, colIndex) {
//handle
}
},
{
icon: '${CONTEXT_PATH}/images/delete.png', // Use a URL in the icon config
tooltip: 'Delete',
handler: function (grid, rowIndex, colIndex) {
handle
}
}
]
}
in this example You see additionally how to change dynamically icon.
One way to solve it is to attach a unique ID to your delete button and bind a listener to the selectionchange event of your SelectionModel, whenever the selection changes you can check whatever you want and enable/disable the button as you see fit.
ie.
Ad.GridCampDeleteButton = Ext.extend(Ext.Toolbar.Button, {
id: 'btnDelete',
cls: 'ad-img-button',
...
});
and in your selectionmodel do something like this :
var sm = new Ext.grid.CheckboxSelectionModel({
...
,listeners: {
'selectionchange' : {
fn: function(sm) {
if (sm.hasSelection()) {
var selected = sm.getSelected();
if (selected.get('field') == value) {
Ext.getCmp('btnDelete').disable();
}
else {
Ext.getCmp('btnDelete').enable();
}
}
}
,scope: this
}
}
});

Categories

Resources