Custom number of buttons tinymce - javascript

How can I create custom buttons tinymce buttons using JQuery? I would need n "Menu item" buttons. "n" would be defined depending on the selected data before opening the tinymce editor.
My buttons:
editor.addButton('addButtons', {
type: 'menubutton',
text: 'My button',
icon: false,
menu: [
{
text: 'Menu item 1',
onclick: function() {
editor.insertContent(' <strong>item1</strong> ');
}
}, {
text: 'Menu item 2',
onclick: function() {
editor.insertContent(' <strong>item2</strong> ');
}
}, {
text: 'Menu item 3',
onclick: function() {
editor.insertContent(' <strong>item3</strong> ');
}
}
]
});
I can get "n" value from a input type hidden using JQuery $("#totalButtons").val(). If totalButtons is 4, I would need 4 item buttons. Does it make sense? Is it possible to do?
Thanks
Updated Code:
var n = $('#total').val();
var menuItems = [];
tinymce.init({
selector: '#mytextareaTenant',
content_css: 'https://fonts.googleapis.com/css?family=Aguafina+Script|Alex+Brush|Bilbo|Condiment|Great+Vibes|Herr+Von+Muellerhoff|Kristi|Meddon|Monsieur+La+Doulaise|Norican|Nothing+You+Could+Do|Parisienne|Permanent+Marker|Sacramento|Yellowtail',
theme: 'modern',
menubar: false,
plugins: [
"print"
],
setup: function (editor) {
editor.on('init', function (e) {
renderEditorTenant();
for (var i=1; i<=n; i++){
var msg = ' <strong>#item' + i + '#</strong> ';
var obj = {
text: 'Menu item ' + i,
onclick: function() {
editor.insertContent(msg);
}
}
menuItems.push(obj);
}
});

Supposing you have a hidden input like this:
<input type="hidden" id="foo" name="zyx" value="3" />
You can get the value of the input and generate an array with n elements:
var n = $('#foo').val();
var menuItems = [];
for (var i=0; i<n; i++){
var msg = ' <strong>item' + i + '</strong> ';
var obj = {
text: 'Menu item ' + i,
onclick: function() {
editor.insertContent(msg);
}
}
menuItems.push(obj);
}
Now, just pass this array to the function you're using to generate the editor:
editor.addButton('addButtons', {
type: 'menubutton',
text: 'My button',
icon: false,
menu: menuItems
});

Related

Server-side ajax search, wait till finish entering - Multi tables

I have the following code:
$('.gerais').each(function(){
var daotable = $(this).data('dao');
x = $(this).DataTable({
serverSide: true,
ajax: {
url: $('body').data('url')+'gerais/ajax_list/'+daotable,
type: "POST"
},
buttons: {
dom: {
button: {
className: 'btn btn-default'
}
},
buttons: [
{
extend: 'copyHtml5',
text: "<i class=' icon-copy3'></i> Copiar"
},
{
extend: 'excelHtml5',
text: "<i class=' icon-file-excel'></i> Excel"
},
{
extend: 'pdfHtml5',
text: "<i class=' icon-file-pdf'></i> PDF"
},
{
extend: 'print',
text: '<i class="icon-printer"></i> Imprimir'
}
],
}
});
});
$('.dataTables_filter input[type=search]').attr('placeholder','Pesquisar...')
.unbind()
.bind('input', function(e){
var item = $(this);
searchWait = 0;
if(!searchWaitInterval) searchWaitInterval = setInterval(function(){
if(searchWait >= 3){
clearInterval(searchWaitInterval);
searchWaitInterval = '';
searchTerm = $(item).val();
x[z].search(searchTerm).draw(); // change to new api
searchWait = 0;
}
searchWait++;
},200);
});
This part of the code is responsible for the loop that create data tables on my page, that have the class ".gerais":
$('.gerais').each(function(){
var daotable = $(this).data('dao');
x = $(this).DataTable({
serverSide: true,
ajax: {
url: $('body').data('url')+'gerais/ajax_list/'+daotable,
type: "POST"
},
buttons: {
dom: {
button: {
className: 'btn btn-default'
}
},
buttons: [
{
extend: 'copyHtml5',
text: "<i class=' icon-copy3'></i> Copiar"
},
{
extend: 'excelHtml5',
text: "<i class=' icon-file-excel'></i> Excel"
},
{
extend: 'pdfHtml5',
text: "<i class=' icon-file-pdf'></i> PDF"
},
{
extend: 'print',
text: '<i class="icon-printer"></i> Imprimir'
}
],
}
});
});
And this one is responsible by the delay on the search
$('.dataTables_filter input[type=search]').attr('placeholder','Pesquisar...')
.unbind()
.bind('input', function(e){
var item = $(this);
searchWait = 0;
if(!searchWaitInterval) searchWaitInterval = setInterval(function(){
if(searchWait >= 3){
clearInterval(searchWaitInterval);
searchWaitInterval = '';
searchTerm = $(item).val();
x[z].search(searchTerm).draw(); // change to new api
searchWait = 0;
}
searchWait++;
},200);
});
This works well for just one table, but I have 3 tables and it only works on the last one.
I already tried to transform "x" on a array and it didn't work.
I made some minor changes and tested it on two client side (serverSide:false) tables.
$(function () {
$("#tabs").tabs();
$('#tblTab1').DataTable();
$('#tblTab2').DataTable();
// definded global variable.
var searchWaitInterval = null;
$('.dataTables_filter input[type=search]').attr('placeholder', 'Pesquisar...')
.off()
.on('input', function (e) {
var item = $(this);
var searchWait = 0;
if (!searchWaitInterval) searchWaitInterval = setInterval(function () {
if (searchWait >= 3) {
clearInterval(searchWaitInterval);
searchWaitInterval = null;
searchTerm = $(item).val();
// aria-controls is an attribute added by DataTables so it makes it easy to target the right
// tables without resorting to global variables.
$("#" + item.attr("aria-controls")).DataTable().search(searchTerm).draw(); // change to new api
searchWait = 0;
}
searchWait++;
}, 200);
});
});

How to create custom dropdownlist in kendo grid header column?

Actually my requirement is want to create custom dropdownlist in the column header of kendo grid. I don't down like nrwant to use filtler column. I just want to add normal dropdown in header. Please provide any example like that so that i can move forward on my task.
Thanks in advance...
In your column definition add a property like this:
headerTemplate: '<input id="dropdown" />'
Then after your grid initialization do:
$("#dropdown").kendoDropDownList({...init parameters...});
UPDATE: go to dojo.telerik.com and paste in the following code:
<div id="grid"></div>
<script>
$("#grid").kendoGrid({
columns: [
{
field: "ProductName",
title: "Product Name",
headerTemplate: '<input id="dropdown" />'
},
{ field: "UnitPrice", title: "Price", template: 'Price: #: kendo.format("{0:c}", UnitPrice)#' }
],
pageable: true,
dataSource: {
transport: {
read: {
url: "http://demos.telerik.com/kendo-ui/service/products",
dataType: "jsonp"
}
},
pageSize: 10
},
excelExport: function(e) {
var sheet = e.workbook.sheets[0];
var template = kendo.template(this.columns[1].template);
for (var i = 1; i < sheet.rows.length; i++) {
var row = sheet.rows[i];
var dataItem = {
UnitPrice: row.cells[1].value
};
row.cells[1].value = template(dataItem);
}
}
});
$("#dropdown").kendoDropDownList({
optionLabel: 'Choose a value...',
dataTextField: 'description',
dataValueField: 'id',
dataSource:{
data: [{id: 1, description: 'One'},{id: 2, description: 'Two'}]
},
change: function(e){
//do whatever you need here, for example:
var theGrid = $("#grid").getKendoGrid();
var theData = theGrid.dataSource.data();
$(theData).each(function(index,item){
item.ProductName = e.sender.text();
});
theGrid.dataSource.data(theData);
}
});

Kendo TreeView Search with Highlight

I have a KendoTreeview with spriteclass. I want to highlight the nodes (root as well as child nodes) with my search term. I have implemented the search functionality. But the issue when i search it is highlighting the term in the nodes but missing the SpriteClass in the nodes after first search. Any idea ?
jsFiddle code
$('#search-term').on('keyup', function () {
$('span.k-in > span.highlight').each(function () {
$(this).parent().text($(this).parent().text());
});
// ignore if no search term
if ($.trim($(this).val()) == '') {
return;
}
var term = this.value.toUpperCase();
var tlen = term.length;
$('#treeview-sprites span.k-in').each(function (index) {
var text = $(this).text();
var html = '';
var q = 0;
while ((p = text.toUpperCase().indexOf(term, q)) >= 0) {
html += text.substring(q, p) + '<span class="highlight">' + text.substr(p, tlen) + '</span>';
q = p + tlen;
}
if (q > 0) {
html += text.substring(q);
$(this).html(html);
$(this).parentsUntil('.k-treeview').filter('.k-item').each(
function (index, element) {
$('#treeview-sprites').data('kendoTreeView').expand($(this));
$(this).data('search-term', term);
});
}
});
$("#treeview-sprites").kendoTreeView({
dataSource: [{
text: "My Documents",
expanded: true,
spriteCssClass: "rootfolder",
items: [{
text: "Kendo UI Project",
expanded: true,
spriteCssClass: "folder",
items: [{
text: "about.html",
spriteCssClass: "html"
}, {
text: "index.html",
spriteCssClass: "html"
}, {
text: "logo.png",
spriteCssClass: "image"
}]
}, {
text: "New Web Site",
expanded: true,
spriteCssClass: "folder",
items: [{
text: "mockup.jpg",
spriteCssClass: "image"
}, {
text: "Research.pdf",
spriteCssClass: "pdf"
}, ]
}, {
text: "Reports",
expanded: true,
spriteCssClass: "folder",
items: [{
text: "February.pdf",
spriteCssClass: "pdf"
}, {
text: "March.pdf",
spriteCssClass: "pdf"
}, {
text: "April.pdf",
spriteCssClass: "pdf"
}]
}]
}]
})
;
Kendo's tree view widget doesn't like it if you muck around in its HTML, so I suggest modifying the data source instead (this will require the encoded option for all items in the DS).
In the keyup handler, you reset the DS whenever you search to clear highlighting, then instead of replacing the element's HTML directly, you set the model's text property:
$('#search-term').on('keyup', function () {
var treeView = $("#treeview-sprites").getKendoTreeView();
treeView.dataSource.data(pristine);
// ignore if no search term
if ($.trim($(this).val()) == '') {
return;
}
var term = this.value.toUpperCase();
var tlen = term.length;
$('#treeview-sprites span.k-in').each(function (index) {
var text = $(this).text();
var html = '';
var q = 0;
while ((p = text.toUpperCase().indexOf(term, q)) >= 0) {
html += text.substring(q, p) + '<span class="highlight">' + text.substr(p, tlen) + '</span>';
q = p + tlen;
}
if (q > 0) {
html += text.substring(q);
var dataItem = treeView.dataItem($(this));
dataItem.set("text", html);
$(this).parentsUntil('.k-treeview').filter('.k-item').each(
function (index, element) {
$('#treeview-sprites').data('kendoTreeView').expand($(this));
$(this).data('search-term', term);
});
}
});
$('#treeview-sprites .k-item').each(function () {
if ($(this).data('search-term') != term) {
$('#treeview-sprites').data('kendoTreeView').collapse($(this));
}
});
});
The tree definition needs the encoded option for this to work:
var pristine = [{
encoded: false,
text: "Kendo UI Project",
expanded: true,
spriteCssClass: "folder",
items: [{
encoded: false,
text: "about.html",
spriteCssClass: "html"
}, {
encoded: false,
text: "index.html",
spriteCssClass: "html"
}, {
encoded: false,
text: "logo.png",
spriteCssClass: "image"
}]
}, {
encoded: false,
text: "New Web Site",
expanded: true,
spriteCssClass: "folder",
items: [{
encoded: false,
text: "mockup.jpg",
spriteCssClass: "image"
}, {
encoded: false,
text: "Research.pdf",
spriteCssClass: "pdf"
}, ]
}, {
encoded: false,
text: "Reports",
expanded: true,
spriteCssClass: "folder",
items: [{
encoded: false,
text: "February.pdf",
spriteCssClass: "pdf"
}, {
encoded: false,
text: "March.pdf",
spriteCssClass: "pdf"
}, {
encoded: false,
text: "April.pdf",
spriteCssClass: "pdf"
}]
}];
$("#treeview-sprites").kendoTreeView({
dataSource: [{
text: "My Documents",
expanded: true,
spriteCssClass: "rootfolder",
items: pristine
}]
});
(demo)
Good job guys, just what I neeeded!
Using your code I did a small tweak (actually added just two lines of jquery filtering), so that now when searching for a keyword, the treeview shows only the branches that contain highlighted texts. Easy peasy! :)
Other branches are hidden if they do not contain the higlighted text. Simple as that.
This means we now have a VisualStudio-like treeview search (see the Visual Studio Solution Explorer Search and Filter: http://goo.gl/qr7yVb).
Here's my code and demo on jsfiddle: http://jsfiddle.net/ComboFusion/d0qespaz/2/
HTML:
<input id="treeViewSearchInput"></input>
<ul id="treeview">
<li data-expanded="true">My Web Site
<ul>
<li data-expanded="true">images
<ul>
<li>logo.png</li>
<li>body-back.png</li>
<li>my-photo.jpg</li>
</ul>
</li>
<li data-expanded="true">resources
<ul>
<li data-expanded="true">pdf
<ul>
<li>brochure.pdf</li>
<li>prices.pdf</li>
</ul>
</li>
<li>zip</li>
</ul>
</li>
<li>about.html</li>
<li>contacts.html</li>
<li>index.html</li>
<li>portfolio.html</li>
</ul>
</li>
<li>Another Root</li>
</ul>
CSS
span.k-in > span.highlight {
background: #7EA700;
color: #ffffff;
border: 1px solid green;
padding: 1px;
}
JAVASCRIPT
function InitSearch(treeViewId, searchInputId) {
var tv = $(treeViewId).data('kendoTreeView');
$(searchInputId).on('keyup', function () {
$(treeViewId + ' li.k-item').show();
$('span.k-in > span.highlight').each(function () {
$(this).parent().text($(this).parent().text());
});
// ignore if no search term
if ($.trim($(this).val()) === '') {
return;
}
var term = this.value.toUpperCase();
var tlen = term.length;
$(treeViewId + ' span.k-in').each(function (index) {
var text = $(this).text();
var html = '';
var q = 0;
var p;
while ((p = text.toUpperCase().indexOf(term, q)) >= 0) {
html += text.substring(q, p) + '<span class="highlight">' + text.substr(p, tlen) + '</span>';
q = p + tlen;
}
if (q > 0) {
html += text.substring(q);
$(this).html(html);
$(this).parentsUntil('.k-treeview').filter('.k-item').each(function (index, element) {
tv.expand($(this));
$(this).data('SearchTerm', term);
});
}
});
$(treeViewId + ' li.k-item:not(:has(".highlight"))').hide();
$(treeViewId + ' li.k-item').expand(".k-item");
});
}
var $tv = $("#treeview").kendoTreeView();
InitSearch("#treeview", "#treeViewSearchInput");
Another tweak from me :)
What I did was change the highlight code in order to preserve anything else that might exist in the node html (such as sprite span for example).
I also implemented it as a TypeScript class wrapper around the TreeView.
If you don't want TypeScript stuff just copy the code out and it should work fine :)
export class SearchableTreeView {
TreeView: kendo.ui.TreeView;
emphasisClass: string;
constructor(treeView: kendo.ui.TreeView) {
this.TreeView = treeView;
this.emphasisClass = "bg-warning";
}
search(term: string): void {
var treeElement: JQuery = this.TreeView.element;
var tv: kendo.ui.TreeView = this.TreeView;
var emphClass = this.emphasisClass;
this.resetHighlights();
// ignore if no search term
if ($.trim(term) === '') { return; }
var term = term.toUpperCase();
var tlen = term.length;
$('span.k-in', treeElement).each(function (index) {
// find all corresponding nodes
var node = $(this);
var htmlContent = node.html();
var text = node.text();
var searchPosition = text.toUpperCase().indexOf(term);
if (searchPosition === -1) {
// continue
return true;
}
var generatedHtml = '<span class="highlight-container">' + text.substr(0, searchPosition) + '<span class="' + emphClass + '">' + text.substr(searchPosition, tlen) + '</span>' + text.substr(searchPosition + tlen) + '</span>';
htmlContent = htmlContent.replace(text, generatedHtml);
node.html(htmlContent);
node.parentsUntil('.k-treeview').filter('.k-item').each(
function (index, element) {
tv.expand($(this));
$(this).data('search-term', term);
}
);
});
$('.k-item', treeElement).each(function () {
if ($(this).data('search-term') != term) {
tv.collapse($(this));
}
});
}
resetHighlights(): void {
this.TreeView.element.find("span.k-in:has('." + this.emphasisClass + "')")
.each(function () {
var node = $(this);
var text = node.text();
$(".highlight-container", node).remove();
node.append(text);
});
}
}
$("#textBox").on("input", function () {
var query = this.value.toLowerCase();
var dataSource = $("#Treeview").data("kendoTreeView").dataSource;
filter(dataSource, query);
});
function filter(dataSource, query) {
var uidData = [];
var data = dataSource instanceof kendo.data.DataSource && dataSource.data();
for (var i = 0; i < data.length; i++) {
var item = data[i];
var text = item.text.toLowerCase();
var isChecked = item.checked;
var itemVisible =
query === true
|| query === ""
|| text.indexOf(query) >= 0;
uidData.push({ UID: item.uid, Visible: itemVisible });
}
if (query != "") {
$.each(uidData, function (index, datavalue) {
if (datavalue.Visible) {
$("li[data-uid='" + datavalue.UID + "']").addClass("highlight");
}
else {
$("li[data-uid='" + datavalue.UID + "']").removeClass("highlight");
}
});
}
else {
$.each(uidData, function (index, datavalue) {
$("li[data-uid='" + datavalue.UID + "']").removeClass("highlight");
});
}
}
CSS :
.highlight {
background:#0fa1ba;
color:white;
}
For Angular 2+ you need to create a pipe for this feature.
import { Pipe, PipeTransform } from '#angular/core';
import { DomSanitizer } from '#angular/platform-browser';
import { NGXLogger } from 'ngx-logger';
#Pipe({
name: 'highlight'
})
export class TypeaheadHighlight implements PipeTransform {
constructor(private readonly _sanitizer: DomSanitizer, private readonly logger: NGXLogger) { }
transform(matchItem: any, query: any): string {
let matchedItem: any;
if (matchItem) {
matchedItem = matchItem.toString();
}
if (this.containsHtml(matchedItem)) {
this.logger.warn('Unsafe use of typeahead please use ngSanitize');
}
matchedItem = query ? ('' + matchedItem).replace(new RegExp(this.escapeRegexp(query), 'gi'), '<strong>$&</strong>') : matchedItem; // Replaces the capture string with a the same string inside of a "strong" tag
if (!this._sanitizer) {
matchedItem = this._sanitizer.bypassSecurityTrustHtml(matchedItem);
}
return matchedItem;
}
escapeRegexp = (queryToEscape) => queryToEscape.replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1');
containsHtml = (matchItem) => /<.*>/g.test(matchItem);
}
Use of this pipe in html template....
<input name="searchTerm" type="text" [(ngModel)]="searchTerm" (keyup)='onkeyup(searchTerm)'
/>
</div>
<div style="height: 70vh;overflow: auto">
<kendo-treeview style="margin-top: 50px" id="availableColumns" [nodes]="availableColumns"
textField="displayName" kendoTreeViewExpandable kendoTreeViewFlatDataBinding idField="id"
parentIdField="parentId">
<ng-template kendoTreeViewNodeTemplate let-dataItem>
<span [tooltip]="dataItem.columnDescription"
[innerHtml]="dataItem.displayName | highlight:searchTerm "></span>
</ng-template>
</kendo-treeview>
</div>

Creating Toolbar In Extjs 4.2 which should like Stack Overflow Toolbar

Am Creating Toolbar Which Is like Stack Overflow having Like This Am Creating Please Go Down you will see Pagination.Now Am stack in between how processed futhure .
i have created 4 buttons which are current page, its next page, and second and last page.
now i want to create next button on click of 2 page same. when i click on 2 page(ie 2nd button
then i want to create 3,4, button.. same way if i click on 6 than i wan to create next two button and prev button will seen which seen in above link.
my code is here:
Ext.define('Ext.bug.Newtoolbar', {
extend: 'Ext.toolbar.Toolbar',
alternateClassName: 'NewToolbar',
requires: ['Ext.toolbar.TextItem', 'Ext.button'],
mixins: {
bindable: 'Ext.util.Bindable'
},
autoDestroy: false,
displayInfo: false,
displayMsg: 'Displaying {0} - {1} of {2}',
emptyMsg: 'No data to display',
initComponent: function () {
var me = this,
pagingItems = me.addBtn(),
userItems = me.items || me.buttons || [];
if (me.prependButtons) {
me.items = userItems.concat(pagingItems);
} else {
me.items = pagingItems.concat(userItems);
}
//delete me.buttons;
if (me.displayInfo) {
me.items.push('->');
me.items.push({ xtype: 'tbtext', itemId: 'displayItem' });
}
me.callParent();
me.addEvents('change', 'beforechange');
me.on('beforerender', me.onLoad, me, { single: true });
me.bind(me.store || 'ext-empty-store', true);
},
// update here info...
updateInfo: function () {
var me = this,
displayItem = me.child('#displayItem'),
store = me.store,
pageData = me.getPageData(),
count, msg;
if (displayItem) {
count = store.getCount();
if (count === 0) {
msg = me.emptyMsg;
} else {
msg = Ext.String.format(
me.displayMsg,
pageData.fromRecord,
pageData.toRecord,
pageData.total
);
}
displayItem.setText(msg);
}
},
onLoad: function () {
var me = this,
pageData,
currPage,
pageCount,
afterText,
count,
isEmpty,
item;
count = me.store.getCount();
isEmpty = count === 0;
if (!isEmpty) {
pageData = me.getPageData();
currPage = pageData.currentPage;
pageCount = pageData.pageCount;
} else {
currPage = 0;
pageCount = 0;
}
Ext.suspendLayouts();
me.updateInfo();
me.updateLayout();
Ext.resumeLayouts(true);
if (me.rendered) {
me.fireEvent('change', me, pageData);
console.log('asd');
};
},
addBtn: function () {
var OnloadArray = [];
var me = this,
PageData,
currntPage,
PageCount;
PageData = me.getPageData();
currntPage = PageData.currentPage;
PageCount = PageData.pageCount;
for (var temp = 0; temp <= currntPage + 1; temp++) {
if (temp != 0) {
OnloadArray.push({
xtype: 'button',
itemId: temp,
scope: me,
text: temp,
enableToggle: true,
toggleGroup: me,
handler: me.btnHandler
});
}
};
OnloadArray.push({
xtype: 'tbtext',
scope: me,
text: '..........',
itemId: currntPage + 2
});
OnloadArray.push({
xtype: 'button',
itemId: PageCount - 1,
scope: me,
text: PageCount - 1,
enableToggle: true,
toggleGroup: me,
handler: me.btnHandler
});
OnloadArray.push({
xtype: 'button',
itemId: PageCount,
scope: me,
text: PageCount,
enableToggle: true,
toggleGroup: me,
handler: me.btnHandler
});
return OnloadArray;
},
getPageData: function () {
var store = this.store,
totalCount = store.getTotalCount();
return {
total: totalCount,
currentPage: store.currentPage,
pageCount: Math.ceil(totalCount / store.pageSize),
fromRecord: ((store.currentPage - 1) * store.pageSize) + 1,
toRecord: Math.min(store.currentPage * store.pageSize, totalCount)
};
}
});
please Help me Please
Thank You
Instead of coding it yourself, why not leverage off Ext JS's existing functionality?

Sencha Touch: filter dataview store with nested JSON data based on button click

I have a dataview list that fetches data from the server, puts it in a store, and renders into a template. Standard stuff.
Above the dataview list in the UI is a button bar containing some Ext.Buttons. I want to be able tap a button and filter the list based on the name of the button. For example: click on 'English 9A' button and show items in the list with the 'title' of 'English 9A'.
As of now when I click the button, the list disappears and I get a console error of: "Uncaught TypeError: Cannot read property 'position' of undefined " and a loading spinner where the list was.
I know there are similar questions out there but I've tried all the solutions but no luck at all.
Sample json data:
{
"ftype":"Announcement",
"value":{
"created":"7/18/2013 05:40:06 PM",
"content":"Hello class, it is July 29th. This is quiz",
"announcementtypename":"HW",
"announcementtypeid":2,
"expiresdate":"2013-07-19",
"isowner":false,
"gradable":false,
"starred":false,
"id":172459,
"order":1,
"state":1,
"statetyped":1,
"qnacount":0,
"attachmentscount":0,
"ownerattachmentscount":0,
"title":"Spanish 9A",
}
},
{
"ftype":"Announcement",
"value":{
"created":"7/18/2013 12:04:45 PM",
"content":"Hello class, it is July 18th. Here is an essay",
"announcementtypename":"HW",
"announcementtypeid":2,
"expiresdate":"2013-07-19",
"isowner":false,
"gradable":false,
"starred":false,
"id":172009,
"order":61,
"state":1,
"statetyped":1,
"qnacount":0,
"attachmentscount":0,
"ownerattachmentscount":0,
"title":"English 9A",
}
}
Model:
Ext.define('app.model.FeedModel', {
extend: 'Ext.data.Model',
config: {
sorters: 'title',
fields: [
{name: 'content', type: "string"},
{name: 'created', type: "string"},
{name: 'announcementtypename', type: "string"},
{name: 'announcementtypeid', type: "integer"},
{name: 'attachmentscount', type: "integer"},
{name: 'applicationscount', type: "integer"},
{name: 'ftype', type: "string"},
{name: 'title', type: "string"},
{name: 'expiresdate', type: "string"},
{name: 'starred', type: "boolean"}
]
}
});
Store:
Ext.define('app.store.FeedStore',{
extend: 'Ext.data.Store',
config:{
storeId:'FeedStore',
model:'app.model.FeedModel',
filterRoot: 'title', // * --does nothing
filters: [
{
property: 'title' // * --does nothing
}
],
}
});
Controller: (Needs the help)
//the button name matches the "title" node in the json
filterFeedFunc: function(button){
var name = button.config.name;
var sto = Ext.getStore('FeedStore');
var all = "allname";
if (name == all){
sto.clearFilter(); // when they click "all" it should show all items - doesn't work
}
//sto.clearFilter(); // * --doesn't work
//sto.filter('title', name); // * --doesn't work
sto.filter({
property: 'title', // * --doesn't work, need something new here
value: name,
exactMatch: true
});
sto.load(); // no
},
UPDATE / EDIT
the View:
Ext.define('app.view.feed.Feed', {
extend: 'Ext.dataview.List',
xtype: 'Feed',
alias: 'widget.feedlist',
config: {
cls: 'feedlist',
store : 'FeedStore',
model: 'FeedModel',
title:'',
emptyText:'no items',
style: 'background-color:#ffffff',
itemTpl: new Ext.XTemplate(
'<tpl for=".">'+
'<div class="feed-item-box">'+
'<tpl if="values.starred == true"> <img src="img/Important.png"> </tpl>'+
'<tpl if="!values.starred"> <img src="img/not-starred.png"> </tpl>'+
'<div class="anntype"><h1>{announcementtypename} </h1></div>' +
'<div class="classname"><h2>{title:ellipsis(30)} </h2></div>' +
'<div class="content"><h4>{content:ellipsis(50)} {summary}</h4></div>' +
'<tpl if="values.attachmentscount || values.applicationscount"><div class="attachment-clip"></div> </tpl>' +
'<div class="due"> ' +
'<h4>{[this.dueInfo(values.expiresdate)]} </h4>' +
'</div>' +
'</div>'+
'</tpl>',{
getUrl: function(){
var store = Ext.getStore('UrlStore');
var url = store.last();
return url.data.url;
},
dueInfo: function(date){
var origDate = moment(date).format("MMMM Do");
var today = moment().format("MMMM Do");
if (today.match(origDate)){
return "Today"
} else{
return origDate
}
}
}),
listeners:{
refresh: function(records) {
var me = this;
var classes = Ext.getStore('ClassListStore')._data.items;
me.setItems([{
cls : 'classbar',
docked : 'top',
xtype : 'dataview',
inline: {
wrap: false
},
scrollable: {
direction: 'horizontal',
directionLock: true
},
height : 101,
html : '<div class="select-all" style= "float: left"></div>',
itemTpl: ''.concat (
'<tpl for=".">',
'<div class="select-{id}"></div>',
'</tpl>'
),
store : Ext.getStore('ClassListStore'),
model : 'app.model.ClassListModel',
listeners:{
refresh: function(){
var bar = jQuery('.classbar');
function getUserRole(){
var store = Ext.getStore('UserStore');
store.load();
var userRole = store.last();
return userRole.data.roledescription;
}
if (getUserRole() != app.UserRoles.ADMIN){
for(var i = 0; i < classes.length; i++){
var data = classes[i].data;
var render = Ext.DomQuery.select('.classbar .select-' + data.id)[0];
var allbutren = Ext.DomQuery.select('.classbar .select-all')[0];
var button = new Ext.Button({
ui: 'chalk-light',
text: data.name,
renderTo: render,
name: data.name,
clazzId: data.id,
cls: 'class-button',
action: 'filterFeed',
html: '<img width="45" style="margin-top: -45px;" src="https://www.app.com/Course/GetIcon?courseInfoId=' + data.courseinfoid + '"/>' +
'<div class="classnamer">' + data.name + '</div>'
});
var allbutton = new Ext.Button({
ui: 'chalk-light',
text: 'All',
renderTo: allbutren,
name: 'allname',
clazzId: 'someId',
cls: 'class-button x-button-pressing',
action: 'filterFeed',
html: '<img width="45" style="margin-top: -45px;" src="https://www.app.com/Content/images/common/course-icons/all.png"/>' +
'<div class="classnamer">All</div>'
});
}
} else{
bar.hide();
}
}
}
}
,
{
cls : 'feedbar',
itemId : 'something',
docked : 'top',
xtype : 'panel',
items:[
{
xtype: 'panel',
html:'Feed',
cls: 'feedTitle'
},
{
xtype: 'button',
action: 'feedAll',
text: 'All',
cls: 'allBtn',
ui: 'chalk-light'
//see feedController.all()
},
{
xtype: 'button',
action: 'starred',
cls: 'impBtn',
ui: 'chalk-light',
html: '<img src="img/not-starred.png"> Important'
}
]
}]
);
}
}
}
});
You don't need to set filterRoot and filters property in store, Try this and let me know what happened.
filterFeedFunc: function(button){
var name = button.config.name;
var sto = Ext.getStore('FeedStore');
sto.load(function(records, operation, success) {
if(sto.getCount()){
if (name == "allname")
sto.clearFilter();
else
sto.filter("title", name);
}
});
}

Categories