Vuetify data table - export to excel - vuetify.js

I want to export data from vuetify data table to excel. If user change sorting or filter data I want to export the data as I can see. Every operation is client-side, server only generates whole data source.
<v-data-table
:headers="headers"
:items="items"
:items-per-page="5"
></v-data-table>
...
created() {
this.items = await this.$axios.$get('/api/get-items')
}
My idea is take json data and use e.g. exceljs to generate excel file. But, there is only one prop (items), which is array before client-side operations (like sorting or filtering). Of cource, that I can take html code and parse data to json or edit api to accept sorting, filterig etc., but this is ugly way. Is there any other solution?

You can do it client-side with one major restriction: you will not be able to use pagination on this table.
If it's OK for you, a special #current-items event should to the trick:
<v-data-table
:headers="headers"
:items="desserts"
:items-per-page="-1"
#current-items="onCurrentItemsChanged"
></v-data-table>
...
data () {
return {
currentItems: [],
...
}
},
methods: {
onCurrentItemsChanged(val) {
this.currentItems = val;
}
}
This emits the items every time the internalCurrentItems is changed.
But when you apply pagination, this event will return only current page data. Not all table elements are displayed at once (to improve performance, I guess).
You won't be able to implement this via HTML code parse either, because v-data-table produce <tr>s only for the elements of the current page.
So if you are not satisfied with this restriction, it'd be better to do it server-side.
You can test this at CodePen.

Related

Export DataTables return [object Object] value

I want to export my datatable as CSV file. Unfortunately the Order History returns [object Object] value in CSV File. I have tried by looking this forum https://datatables.net/forums/discussion/50304/datatable-is-showing-object-object-in-columns#Comment_133450 but I'm not sure how should apply on my code.
Below the csv file, that give output [object Object] for Order History.
As for the datatables, it return the value that I wanted.
Here's my code: LIVE JS BIN DEMO
The Server_Processing.php JSON
{
"draw": 1,
"recordsTotal": 238633,
"recordsFiltered": 183514,
"data": [
[
"6789",
"North City"
],
[
"5325",
"South City"
]
]
}
Output console.log(result) for fetch_total.php ajax call
{"data":[[6]]}
{"data":[[1]]}
Basically I've pass the ID_No value to ajax call, and it will return the readable value to the cell.
I've tried by using JSON.stringify to the additionalData, it still return [object Object] value when I export as CSV file.
Any help would be greatly appreciated
Solution
The simplest way to fix this is to add an exportOptions section to your DataTable buttons option.
So, instead of this:
buttons: [ 'csv' ],
you can use this:
buttons: [
{
extend: 'csv',
exportOptions: {
format: {
body: function ( inner, rowidx, colidx, node ) {
return node.innerText;
}
}
}
}
],
And you can repeat the { extend: ... } section for additional buttons (e.g. Excel).
This logic ensures you take the value loaded into the DOM node (the HTML table cell) instead of the value stored in the DataTable (an object).
Explanation
In your logic, you are using this:
"createdCell": function(cell, cellData, rowData, rowIndex, colIndex) { ... }
This is documented here.
The key point is:
cell: The TD node that has been created.
In other words, this <td> element is what you see displayed in the web page - the HTML. It is not what is stored in the underlying DataTable (which is the createdCell function used to create the contents of that <td> element).
So, when you try to export your data, DataTables will use the data it has stored in its internal data structures. It does not use the data you added to the HTML table.
My exportOptions function solves that by telling DataTables to look at the data in the HTML table directly (node.innerText) instead of using its internal data.
This is a very basic solution. It looks in every <td> cell in the HTML table, not just the third column. In your case, this is probably fine. But you may need to refine this, if there are other cases where you do not want to use the cell contents.
Also, I agree with the comments made in the question by #mark_b:
You're making a separate Ajax call for each row of your data in order to populate the Order History column? Surely there is a more efficient way to get all the data you need in a single request?

CKEditor 5: How can I load to/save from model instead of view?

My application uses CKEditor 5 to allow users to edit rich text data. These texts support some application-specific custom elements (Web Components), and I want to extend CKEditor with custom plugins that support inserting such custom elements. I seem to be almost there, but I'm having some difficulties getting these custom elements into and out of the CKEditor instance properly.
Current plugin implementations
I mainly followed the Implementing an inline widget tutorial from the CKEditor 5 documentation. As an example, I would like to support a custom element like <product-info product-id="123"></product-info>, which in CKEditor should be rendered as a simple <span> with a specific class for some styling.
In my editing plugin, I first define the extension to the schema:
const schema = this.editor.model.schema;
schema.register('product-info', {
allowWhere: '$text',
isInline: true,
isObject: true,
allowAttributes: [ 'product-id' ]
});
I then define the upcast and downcast converters, closely sticking to the tutorial code:
const conversion = this.editor.conversion;
conversion.for('upcast').elementToElement({
view: {
name: 'span',
classes: [ 'product-info' ]
},
model: (viewElement, { writer: modelWriter }) => {
const id = viewElement.getChild(0).data.slice(1, -1);
return modelWriter.createElement('product-info', { 'product-id': id });
}
});
conversion.for('editingDowncast').elementToElement({
model: 'product-info',
view: (modelItem, { writer: viewWriter }) => {
const widgetElement = createProductInfoView(modelItem, viewWriter);
return toWidget(widgetElement, viewWriter);
}
});
conversion.for('dataDowncast').elementToElement({
model: 'product-info',
view: (modelItem, { writer: viewWriter }) => createProductInfoView(modelItem, viewWriter)
});
function createProductInfoView(modelItem, viewWriter) {
const id = modelItem.getAttribute('product-id');
const productInfoView = viewWriter.createContainerElement(
'span',
{ class: 'product-info' },
{ isAllowedInsideAttributeElement: true }
);
viewWriter.insert(
viewWriter.createPositionAt(productInfoView, 0),
viewWriter.createText(id)
);
return productInfoView;
}
Expected behavior
The idea behind all this is that I need to support the custom <product-info> elements stored in user data in the backend. CKEditor, which is used by users to edit that data, should load these custom elements and transform them into a styled <span> for display purposes while editing. These should be treated as inline widgets since they should only be able to be inserted, moved, copied, pasted, deleted as a whole unit. A CKEditor plugin should allow the user to create new such elements to be inserted into the text, which will then also be <span>s in the editing view, but <product-info>s in the model, which should also be written back to the backend database.
In other words, I expected this to ensure a direct mapping between element <product-info product-id="123"></product-info> in the model, and <span class="product-info">123</span> in the view, to support inserting and moving of <product-info> elements by the user.
Actual result
In short, I seem to be unable to get CKEditor to load data containing <product-info> elements, and unable to retrieve the model representation of these custom elements for backend storage. All operations to insert data to CKEditor from source, or to retrieve CKEditor data for sending to the backend, seem to operate on the view.
For example, if I preload CKEditor contents either by setting the inner content of the element that is replaced with the editor instance, or inserting it like this:
const viewFragment = editor.data.processor.toView(someHtml);
const modelFragment = editor.data.toModel(viewFragment);
editor.model.insertContent(modelFragment);
I see the following behavior (verified using CKEditor Inspector):
When inserting the custom element, i.e. <product-info product-id="123"></product-info>, the element is stripped. It's not present in either the model nor the view.
When inserting the view representation, i.e. <span class="product-info">123</span> I get the representation that I want, i.e. that same markup in CKEditor's view, and the <product-info product-id="123"></product-info> tag in the model.
This is exactly the opposite of what I want! In my backend, I don't want to store the view representation that I created for editing purposes, I want to store the actual custom element. Additionally:
My UI plugin to insert new product info elements, uses a command that does the following:
execute({ value }) {
this.editor.model.change( writer => {
const productInfo = writer.createElement('product-info', {
'product-id': value
});
this.editor.model.insertContent(productInfo);
writer.setSelection(productInfo, 'on');
});
}
which also works as I want it to, i.e. it generates the product-info tag for the model and the span for the view. But, of course, when loading an entire source text when initialising the editor with data from the backend, I can't use this createElement method.
Conversely, in order to retrieve the data from CKEditor for saving, my application uses this.editor.getData(). There, these proper pairs of <product-info> model elements and <span> view elements get read out in their view representation, instead of their model representation – not what I want for storing this data back!
The question
My question is: what do I need to change to be able to load the data into CKEditor, and get it back out of the CKEditor, using the custom element, rather than the transformed element I want to show only for editing purposes? Put differently: how can I make sure the content I insert into CKEditor is treated as the model representation, and how do I read out the model representation from my application?
I'm confused about this because if the model representation is something that is only supposed to be used internally by CKEditor, and not being able to be set or retrieved from outside – then what is the purpose of defining the schema and these transformations in the first place? It will only ever be visible to CKEditor, or someone loading up the CKEditor Inspector, but of no use to the application actually integrating the editor.
Sidenote: an alternative approach
For a different approach, I tried to forgo the transformation to <span>s entirely, and just use the custom element <product-info>, unchanged, in both the model and the view, by using the General HTML Support functionality. This worked fine, since this time no transformation was needed, all I had to do was to set the schema in order for CKEditor to accept and pass through the custom elements.
The reason I can't go with this approach is that in my application, these custom components are handled using Angular Elements, so they will actually be Angular components. The DOM manipulation seems to interfere with CKEditor, the elements are no longer treated as widgets, and there are all manner of bugs and side effects that come with it. Elements show up fine in CKEditor at first, but things start falling apart when trying to select or move them. Hence my realisation that I probably need to create a custom representation for them in the CKEditor view, so they're not handled by Angular and preventing these issues.

Children dynamic content with reactjs

I'm trying to experiment here. I want to build a component that auto populates some data from an ajax request after mounting. Something like this:
var AjaxComponent = React.createClass({
getInitialState: function() {
return {
data: {}
};
},
render: function() {
return (
<div>
{this.state.data.text}
</div>
);
},
componentDidMount: function() {
makeAjaxResquest(this.props.url).then(function(response){
this.setState({
data: response.body // or something
});
}.bind(this));
}
});
With that example component, I'd use <AjaxComponent url="/url/to/fetch" /> to display the content.
Now, what if I'd like to access different bits of data from children elements? Can I do something like this?
<AjaxComponent url="/url/to/fetch">
<div>
<header>{RESPONSE.title}</header>
<div>
{RESPONSE.text}
</div>
</div>
</AjaxComponent>
No problem if it doesn't render anything before the ajax request ends. The thing is how could I pass the data for children to render, not as props. Is it possible?
I had a similar scenario where I had similar Components that would query data from different APIs. Assuming you know the expected response from a given API, you could do it the same way perhaps.
Essentially make a generic Component where it props functions as an "API" of sorts, then define different types of sub components and their associated render function.
For example:
In widget, you then do something like this, where widgets is just a plain javascript file with a bunch of functions:
componentDidMount: widgets[type].componentDidMount(),
render: widgets[type].render().
In widgets, it would be like this:
var widgets = {
widget1: {
componentDidMount: function () {
//Ajax call..
},
render: function() {
//How should I draw?
}
},
widget2: //Same format, different functions
Then in some parent component you simply go
< Widget type="widget1" \>
or whatever.
There are a couple weird things about this that probably don't sit right with React. First off, you should take state all the way up to the top-level component, so I wouldn't do my ajax calls in componentDidMount...I'd more likely get the data I want for the widgets I want to render at a higher level, then pass that in as a prop too if it won't change until I make another API call (thinking Flux style flow here). Then, just pass in the data as a prop as well and just specify the render functions:
< Widget data={this.state.data[0]} type=widget1 />
The "gotcha" here is that you are making an assumption that whatever is in this data prop will match what you need in the widget type. I would pass in an object, and then validate it all in the render function etc.
That's one way. Not sure if it's valid, I'm sure someone who knows more could pick it apart but it suited my use case and I now have a library of similar components that I can selectively render by passing in data and a type, then looking up the appropriate render function and checking to make sure the data object contains everything I need to render.

Updating Django form based on input

I want to append more fields based on a users selection of Type of Event.
What is the best way to add additional fields based on the users selection without refreshing the page?
I was thinking ajax call when user clicks Add the details and return html?
Is there a way to do this using the template system with a series of if/else conditionals?
Two solutions come to mind here...
1)
Attach a jQuery change handler to the 'Type of Event' select element, and execute an ajax request to return the dynamic fields that will need to be displayed.
$('#TYPE_OF_EVENT_ID').change(function() {
$.get('/api/to/return/dynamic/fields/', {'type_of_event': $(this).val()}, function(data, textStatus, jqXHR) {
# Update DOM with dynamic content return by data (should probably be JSON)
});
});
2)
Hard code the logic straight into your javascript to handle the case statements to display the dynamic fields depending upon the value which is selected in the 'Type of Event' select element.
$('#TYPE_OF_EVENT_ID').change(function() {
switch($(this).val()) {
case 'Special Event':
# Show Special Event Fields
case 'Non Special Event':
# Show Non Special Event Fields
}
});
I'd recommend option 1 as it scales better keeping this logic on the server to be database driven.

implement chanied filters/seach options in a datagrid using ajax

Let´s say I have some sort of datagrid and I want to add a couple chained filters like in this site:
http://www.yelp.com/search?find_desc=bar&ns=1&find_loc=Minneapolis%2C+MN
(sort by,distance,price etc).
Each time a user clciked in a filter link it will update the content of datagrid accordingly. But I would also need to update the links in other filters to take account of the changes. Ex: if i change the order field I need to add/update ?order_field=x in all the other filters links.
What you think is the best way to implement such scenario?
Should i create a function that, when a filter link is clicked, it update the query string params of all the other filters? Or use hidden fields to record the selected option in each filter?
I would like a reusable solution if possible.
Since the data is loading via AJAX, there shouldn't be any links to update - at least not if you mean anchor tags <a>. You don't even need to store the filters in a hidden field.
I would store all the filters as a JSON object. Depending on how your API is set up, you may have to convert the JSON object to something usable by your API or you may even be able to pass on the JSON object directly in the $.ajax request.
This sample code assumes you have a textbox with id="price" in the markup. I intentionally left convert_filters_to_parameters blank because you didnt provide any details as to your API. jQuery will in turn serialize those parameters into a GET or POST request before it sends them out.
var filters = {
distance:null,
price:null,
sortBy:'distance'
}
//this assumes you have a textbox with id="price"
$('#price').changed(function()
{
filters.price = $(this).val();
refresh_data();
});
function refresh_data()
{
var parameters = convert_filters_to_parameters(filters);
$.ajax('/my_api',
{
//i left out a lot of properties here for brevity
data: parameters,
success: function(response) { alert(response); }
});
}

Resources