Quantcast
Channel: DHTMLX Blog
Viewing all 392 articles
Browse latest View live

dhtmlxSuite 6.1 Minor Update: Multiselection, Enhanced Drag-n-Drop and Editing Features

$
0
0

It’s been a month and a half since the large-scale update of the whole JavaScript UI library DHTMLX Suite v6.0. We’ve been gathering your feedback, prioritizing features for future releases, and working hard to deliver the next update 6.1. And now our minor release brings out editing for dhtmlxGrid and dhtmlxTree, multiselection and drag-n-drop of multiple items and inline editing in dhtmlxList and dhtmlxDataView as well as a range of other essential features for building top-notch user interfaces.

dhtmlxGrid New Features and Updates
Data Editing

V6.1 provides new editing capabilities for our JavaScript Data Grid. Now end users can easily edit any cells they need on the fly. When they double click a cell, an appropriate editor appears: a simple input field, selection box or datepicker:
DHTMLX Grid editingCheck the sample >

As you can also see from the recording above, there appeared a new column type – date, which enables end users to choose a date on a calendar in the column “Start date”.

In order to achieve that and make an entire Grid editable, developers need to specify the editing:true property in the Grid configuration:

var grid = new dhx.Grid("grid_container", {
    columns: [// columns config],
    data: data,
   editing: true
});

However, you can limit a choice of columns that can be edited by end users if you set the editing:true property in the configuration of specific columns. For instance, here is how we can make only the first column editable:

var grid = new dhx.Grid("grid", {
    columns: [
        {
           width:150,id:"project",

          editing:true,
          header: [
            {text:"Project"}, {content:"selectFilter"}
           ]
        },
        { width:150, id:"owner", header: [{text:"Owner"},{content:"inputFilter"}]},
        { width:150, id: "hours", header: [{text:"Hours"}, {content:"inputFilter"}]},
        // more columns
    ],
    data: data
});

Check the documentation >

By default, columns have an input type of the editor for working with plain text. If a column has a type “date”, then a datepicker editor will be used. Developers can also set a specific date format for editing:

{
    // if the type:"date" config is set in the column config,
    // there's no need to specify the type of the editor
    width: 150, id: "start_date",
    header: [{ text: "Calendar", colspan: 2 }, { text: "Start date" }],
   type: "date", dateFormat: "%d/%m/%Y"
}

In order to equip a cell with a selection box with options to choose from, you’ll need to specify the select editor type and and add the desired options for selection:

{
    width: 150, id: "status", header: [{text: "Status"}, {content: "selectFilter"}],
   editorType: "select", options: ["Done", "In Progress", "Not Started"]
}

Check the documentation >

Additionally, now developers have a straightforward way to edit any Grid cell using the edit method. Here is how we can edit the first cell of the “project” column with just one line of code:

grid.edit(grid.data.getId(0),"project");

Check the documentation >

Vertical Spans in Header

Besides, now our Grid allows creating not only horizontal but also vertical spans in the header:
Vertical Header Spans in DHTMLX GridCheck the sample >

Empty Grid

On top of all, v6.1 makes it possible to initialize an empty Grid, without any data loaded into it. It also introduces the ability to automatically add an empty row into the end of the Grid when the last empty row is filled out with the help of the autoEmptyRow property:

var grid = new dhx.Grid("grid_container", {
    columns: [// columns config],
   autoEmptyRow:true,  
   data: dataset
});

Check the documentation >
Empty row at the end of DHTMLX GridCheck the sample >

Complex Selection

V6.1 delivers the ability to highlight a selected cell together with a row it belongs to. Check the documentation >

dhtmlxDataView and dhtmlxList New Features
Inline Editing

Besides dhtmlxGrid, our data processing components – DataView and List – also become easily editable starting from v6.1. There are two ways of setting up the editing functionality. The first one is via the API with the help of the edit method. It allows developers to define which item should be edited. For example, the following line of code instructs DataView to enable editing of the item with the id “1”:

dataview.edit("1");

However, there is a more convenient way, which gives end users an opportunity to edit all items at once. It can be enabled using the editing configuration option before the initialization of the component:

var dataview = new dhx.DataView("dataview_container", {editing:true});

Inline editing in DHTMLX DataViewCheck the sample >

The same edit method and editing configuration option can be applied in dhtmlxList. Read more in the documentation >

As for dhtmlxTree, previously developers were able to use the edit method for changing particular items. Now they can turn on inline editing of all Tree items with the help of the editing configuration property as well:

var tree = new dhx.Tree("tree", {editing: true});
Multiple Selection and Drag-n-Drop

V6.1 introduces a multiple selection of List and DataView items and multiple drag-n-drop.

By default, it’s possible to select just one item in a DataView or List at a time. However, with the multiselection configuration option developers can enable the selection of multiple items at once:

var dataview = new dhx.DataView("dataview", {multiselection:true});
var list = new dhx.List("list", {multiselection:true});

Multiselection has two modes of work. The default one makes use of “Ctrl + click” combination for selecting several items. But developers may switch on a simple click mode, which allows selecting multiple items by means of clicks only:

var dataview = new dhx.DataView("dataview", {
    multiselection:true,
    multiselectionMode:"click"  
});

Drag-n-drop of multiple items can be easily enabled by specifying the multiselection:true configuration property in addition to the dragMode. For example, let’s set up the drag-n-drop of multiple items in the DataView:

var dataview = new dhx.DataView("dataview_container", {
    dragMode:"source",
    multiselection:true
});

Drag-n-drop of multiple items in DHTMLX DataViewCheck the sample >

Other Updates

In addition to the main features presented above, we’ve updated a range of other UI components included in dhtmlxSuite: ComboBox, Form, Popup, Window – as well as Data and Tree Collection. For instance, dhtmlxCombo received the ability to hide and show a popup via the Popup API. dhtmlxWindow got a special method for checking the window’s visibility – isVisible. Learn about all the updates of JavaScript UI components in the documentation.

We invite you to try out dhtmlxSuite 6.1 during a 30-day evaluation period and benefit from the assistance of our technical support team.

Current clients are welcome to download the latest version in their Client’s Area.

We’ll be looking forward to your feedback! Stay tuned for future updates!

Related Materials:

The post dhtmlxSuite 6.1 Minor Update: Multiselection, Enhanced Drag-n-Drop and Editing Features appeared first on DHTMLX Blog.


dhtmlxPivot 1.4 Minor Update: Flat Mode, Export to CSV, and Dropdown Field Selectors

$
0
0

A long-awaited v1.4 of our JavaScript pivot table, a smart component for data analysis, is finally out!

The highlight of the release is the ability to display data in a flattened pivot table with repeated row labels. Besides, now dhtmlxPivot is able to export data not only to Excel but also to the CSV format, which is lightweight and simple to use with any programming language. We also supplied the component with a wide range of events firing on various user actions in the grid and updated the UX of field selectors.

So, let’s make a long story short…and invite you to download the latest v1.4 for 30-day evaluation!

Tree vs Flat Mode of the Grid

The update introduces different modes for visualizing pivot data. You can set up the desired mode according to the preferences of your end users. The tree-like structure of the grid has been used in dhtmlxPivot by default so far. V1.4 brings out the gridMode attribute of the layout object, which helps to redefine the mode of displaying data and present it as a flattened table as shown in the picture below:
Flat mode of the pivot gridCheck the sample >

Apart from that, it’s possible to avoid duplicating row headers in the cells of the first column by specifying the repeatRowsHeaders:false property in the layout configuration:

var pivot = new dhx.Pivot(document.body, {
    data: dataset,
    fields: {
        rows: ["form", "name"],
        columns: ["year"],
        values: [{ id: "oil", method: "max" }, { id: "oil", method: "sum" }],
    },
    fieldList: [
        { id: "name", label: "name" },
        // the full list of fields
    ],

   layout: {                      
           gridMode:"flat",          
           repeatRowsHeaders: false    
   }                              
 }
);

Flat mode with repeated labelsCheck the sample >
The new flat mode is a convenient and easy-to-read way of visualizing pivot data. It may be familiar to end users due to a similar tabular form with repeated item labels of the Excel layout.

Export to CSV

The newly introduced pivot.export.csv() method of the Export module enables you to export pivot data to the CSV format. The export settings are quite flexible and allow for the necessary adjustments. By default, you’ll get a CSV file as a result of export. However, you can choose to export data only as a CSV string by specifying the asFile:false configuration property. Other settings permit converting pivot into a flat table and defining custom separators between rows and columns.

In the example below we’ll get a CSV file named “pivot_data” with a flat structure, tabs as row separators and semicolons as column separators:

pivot.export.csv({
    name:"pivot_data",
    asFile:true,
    flat:true,
    rowDelimiter: "\t",
    columnDelimiter: ";"
});

Check the sample >

Please note that since v1.4 we recommend using the pivot.export.xlsx() method of the Export module instead of the pivot.export() method. Read the migration article for more details.

New Dropdown Field Selectors

In v1.4 we added a new type of field selectors. Now with the help of the fieldSelectorType attribute you can define the look and feel of selectors and configure them either as loop selectors or dropdown lists:

var pivot = new dhx.Pivot(document.body, {
    data: dataset,
    fields: {
        // fields structure
    },
    fieldList: [
        // full list of fields
    ],
    layout: {
   fieldSelectorType:"dropdown"          
   }
  }
);

JS Pivot dropdown selectorsCheck the sample >

TreeGrid Events in the Pivot API

On top of all, starting with v1.4 dhtmlxPivot is able to listen to the grid events triggered by user actions such as clicks on cells, moving the mouse pointer, typing text in an input field, etc. The entire list of the newly added events is available in the documentation.

We hope the update will come in useful in your projects! We’re looking forward to hearing your feedback and comments. Feel free to evaluate the latest version with the help of our technical support team for free for 30 days.

We invite our current clients to download v1.4 of dhtmlxPivot in their Client’s Area.

Stay tuned!

Related Materials:

The post dhtmlxPivot 1.4 Minor Update: Flat Mode, Export to CSV, and Dropdown Field Selectors appeared first on DHTMLX Blog.

How to Make Hotel Booking Calendar with dhtmlxScheduler

$
0
0

dhtmlxScheduler is one of the most flexible components available, but yet when you check the basic examples of dhtmlxScheduler, they can look pretty far from a final result and feel that you need to implement. And a usual challenge for developers that are new to dhtmlxScheduler is how do I get from this:

timeline scheduler

to this:

hotel calendar

At this point familiarizing with the API and figuring the appropriate approach can take an unnecessarily long time.

In this tutorial, we want to show you some frequently used settings in order to speed up this process. We’ll start from a plain timeline config and will show how to make it into something more complex, like our hotel reservation demo.

When you understand how our Scheduler component works, it’ll be much simpler for you to develop any functionality you want. As a result of this tutorial, you will learn how to work with the Scheduler’s timeline and be able to configure it based on your needs.

Now, let’s define which features we will implement during the tutorial:

features

  1. Filtering allows visualizing the rooms according to particular criteria
  2. Timescale should be changed to show a full month
  3. Lefthand labels, step one. We’ll add a header above the lefthand column
  4. Lefthand labels, step two. We’ll add the possibility to display multiple columns with a custom HTML content and colors
  5. The default appearance of the event boxes will be changed
  6. We’ll add custom tooltips
  7. We’ll add the highlight for the days off

As we successfully defined what should be done, we can proceed with the code writing.

Step 0 – Prerequisites

We’re starting with the plain timeline view, like the one you can find in our package:

Before proceeding with the coding, we’re doing some preparations.

Firstly we add test data – we need lists of bookings, rooms, room types, booking statuses (confirmed, arrived, etc.) and room statuses (ready, clean up, dirty). In this tutorial we’ll load all of this in a single json document formatted like this.

All arrays from the “collections” part of json can be accessed using scheduler.serverList method by their respective name.

If the list objects have the expected structure (`key` and `value` properties), they can be connected to the timeline/units views or to the lightbox select controls directly. Moreover, if you reload data or update these collections from code, the views and controls connected to the appropriate collections will be repainted automatically in order to reflect the changes.

Thus, the data models may look as following:

booking:

{
   "id":"1",
   "start_date":"2017-03-02",
   "end_date":"2017-03-23",
   "text":"A-12",
   "room":"1",
   "status":"1",
   "is_paid":"1"
}

room:

{
   "value":"1",
   "label":"101",
   "type":"1",
   "status":"1"
}

booking status:

{
  "value":"3",
  "label":"Arrived"
}

room status:

{
  "value":"1",
  "label":"Ready"
}

room type:

{
  "value":"2",
  "label":"2 beds"
}

And here is how a complete JSON will look like. After we connect list of rooms to the timeline view, we’ll be able to see the following calendar and drag bookings between rooms:

Another small thing we can do is to set the default values, such as booking status, paid status or a default text. It is usually done via onEventCreated event:

scheduler.attachEvent('onEventCreated', function (event_id) {
    var ev = scheduler.getEvent(event_id);
    ev.status = 1;
    ev.is_paid = false;
    ev.text = 'new booking';
});

Check the code.

And now let’s go through the list of features we made.

Step 1 – Filtering timeline rows (rooms)

As we’ve found out at the previous step, we have a list of rooms which are displayed as rows of the timeline, and room types which are associated with the rooms:

values

What we want here is to filter timeline rows by the room type, e.g. ‘show two bed rooms only’.

How it’s usually done – scheduler allows dynamically replacing timeline rows with a new collection using
scheduler.serverList/updateCollection.

Knowing this, the task is pretty simple.

1) We connect the timeline to the empty serverList:

scheduler.createTimelineView({
    ...
    y_unit:    scheduler.serverList("visibleRooms"),
    ...
});

2) Then we define a function that filters a complete list of rooms, select ones that pass the filter and put them into “visibleRooms” list, updating the timeline:

window.showRooms = function showRooms(type) {
    var allRooms = scheduler.serverList("rooms");
    var visibleRooms ;
    if (type == 'all') {
        visibleRooms = allRooms.slice();
    }else{
        visibleRooms = allRooms
          .filter(function(room){
             return room.type == type;
        });
    }

  scheduler.updateCollection("visibleRooms", visibleRooms);
};

3) Once data is parsed, we can run the filters in order to populate the timeline initially:

scheduler.attachEvent("onParse", function(){
  showRooms("all");
});

When you will replace data loading from a client-side resource by scheduler.parse() method with data loading from a server-side resource by scheduler.load(), you must also replace onParse with onLoadEnd.
Here is how everything looks at this point.

Finally, let’s add a dropdown for a user to change the filter.
We can put it on the place of .dhx_cal_tab elements in the scheduler header:

<div id="scheduler_here" class="dhx_cal_container" style="width:100%; height:100%;">
    <div class="dhx_cal_navline">
        <div class="dhx_cal_prev_button">&nbsp;</div>
        <div class="dhx_cal_next_button">&nbsp;</div>
        <div class="dhx_cal_today_button"></div>
        <div class="dhx_cal_date"></div>
        <select id="room_filter" onchange='showRooms(this.value)'></select>
    </div>
    <div class="dhx_cal_header">
    </div>
    <div class="dhx_cal_data">
    </div>
</div>
scheduler.attachEvent("onParse", function(){
  showRooms("all");

  var roomSelect = document.querySelector("#room_filter");
  var types = scheduler.serverList("roomTypes");
  var typeElements = ["<option value='all'>All</option>"];
  types.forEach(function(type){
     typeElements.push("<option value='"+type.key+"'>" + type.label +"</option>");
  });
  roomSelect.innerHTML = typeElements.join("")
});

And that’s how we implement the filtering:

Step 2 – Displaying a full month in the time scale

As per requirements, we need a two line time scale – one day per cell of the time scale, and the month line on top of days. Also, the timeline should show a complete month.

The time unit and number of columns of the timeline view are defined by x_size/x_step/x_date properties of configuration object. It also allows adding a second row to the time scale.

So, intuitively we can get a config like this:

scheduler.createTimelineView({
    name:    "timeline",
    x_unit: "day",
    x_date: "%j",
    x_step: 1,
    x_size: 31,
    section_autoheight: false,
    y_unit:    scheduler.serverList("visibleRooms"),
    y_property:    "room",
    render:"bar",
    round_position:true,
    dy:60,
    second_scale:{
     x_unit: "month",
     x_date: "%F, %Y"
    }
});

And get a timeline looking like this:

You may see a problem here – the timeline must always start from the first day of the month, and a number of columns should match a number of days per month, which may vary.

How do we solve this? We can access the instance of the timeline view from code and modify the number of days per view according to the displayed month. We can do it each time the displayed date is changed using onBeforeViewChange event.

scheduler.attachEvent("onBeforeViewChange", function(old_mode,old_date,mode,date){
    var year = date.getFullYear();
    var month= (date.getMonth() + 1);
    var d = new Date(year, month, 0);
    var daysInMonth = d.getDate();
    var timeline = scheduler.getView('timeline');
    timeline.x_size = daysInMonth;

    return true;
});

Then we need to make sure that timeline starts from the first day of the month, this can be done using scheduler.date[timelineName + “_start”] method. This method is defined by the timeline instance and controls the starting point of the time scale:

scheduler.date.timeline_start = scheduler.date.month_start;

We use a ‘month_start’ method of scheduler date helper, which does exactly what we need.

Finally, we need to make sure that the timeline is scrolled for exactly one month when user clicks forward/backward navigation in the scheduler head. We do it by redefining scheduler.date.add_timeline method. This is also a generic scheduler.date[“add_” + viewName] method that is defined for the each view:

scheduler.date.add_timeline = function(date, step){
    if(step > 0){
        step = 1;
    }else if(step < 0){
        step = -1;
    }
    return scheduler.date.add(date, step, "month")
};

Note that the scheduler.date methods of the timeline should be declared after scheduler.createTimelineView call, otherwise the timeline will overwrite them.

And now you should have a correct month scale:

Step 3 – Adding a header to the lefthand column of the timeline

Now we need to add a header here:

header scheduler

There is timeline_scale_label template to set required markup into the header of Y-Axis in the Timeline view.
So, we’ll put HTML elements that we need to create 3 header’s columns into the variable and then will set this variable as the value of the template.

The code may look as following:

 var headerHTML = "<div class='timeline_item_separator'></div>" +
      "<div class='timeline_item_cell'>Number</div>" +
      "<div class='timeline_item_separator'></div>" +
      "<div class='timeline_item_cell'>Type</div>" +
      "<div class='timeline_item_separator'></div>" +
      "<div class='timeline_item_cell room_status'>Status</div>";
      scheduler.locale.labels.timeline_scale_header = headerHTML;

And css:

  .timeline_item_cell {
    width: 32%;
    font-size: 14px;
    text-align: center;
  }
  .timeline_item_separator {
    background-color: #CECECE;
    width: 1px;
    height: 100% !important;
  }
  .timeline_item_separator,
  .timeline_item_cell {
    vertical-align:top;
    height: 100%;
    display:inline-block;
    line-height: 60px;
    vertical-align:top;
  }

Step 4 – Adding multiple columns to the left part of the timeline

Scheduler always creates a single column before the time scale of the timeline, and as of the current version, there is no way to tell it otherwise.

The good news are, we have a complete control over the contents of that column via template function. Thus, we can put any html into that column, including extra cells.

In short, the code may look like following:

scheduler.attachEvent("onTemplatesReady", function(){
 
     function findInArray(array, key) {
        for (var i = 0; i < array.length; i++) {
            if (key == array[i].key)
                return array[i];
        }
        return null;
    }

    function getRoomType(key) {
        return findInArray(scheduler.serverList("roomTypes"), key).label;
    }

    function getRoomStatus(key) {
        return findInArray(scheduler.serverList("roomStatuses"), key);
    }

    function getRoom(key) {
        return findInArray(scheduler.serverList("rooms"), key);
    }

    scheduler.templates.timeline_scale_label = function (key, label, section) {
        var roomStatus = getRoomStatus(section.status);
        return ["<div class='timeline_item_separator'></div>",
            "<div class='timeline_item_cell'>" + label + "</div>",
            "<div class='timeline_item_separator'></div>",
            "<div class='timeline_item_cell'>" + getRoomType(section.type) + "</div>",
            "<div class='timeline_item_separator'></div>",
            "<div class='timeline_item_cell room_status'>",
            "<span class='room_status_indicator room_status_indicator_"+section.status+"'></span>",
            "<span class='status-label'>" + roomStatus.label + "</span>",
            "</div>"].join("");
    };
 
});

And css:

.collection_label {
  z-index: 2;
}

.room_status {
    position: relative;
}


.room_status_indicator {
    position: absolute;
    background-color: red;
    left: 0;
    top: 0;
    right: 95%;
    bottom: 0;
}

.room_status_indicator_1 {
    background-color: #4CAF50;
}

.room_status_indicator_2 {
    background-color: red;
}

.room_status_indicator_3 {
    background-color: #FFA000;
}

Step 5 – Changing the color and the inner contents of the event boxes

There are three settings that define the look of an event in the timeline view:

1) the height of the event box is defined by event_dy property of the Timeline config.

2) css class applied to the event box

3) and the inner html of the event box

We’ll need all of them.

Firstly, let’s make events occupy the whole height of the timeline row:

scheduler.createTimelineView({
...
  event_dy: "full",
...
});

Now let’s color events based on their status.

For that we’ll need css rules for each status, for this tutorial we’ll simply hardcode them:

.event_1 {
    background-color: #FFB74D !important;
}

.event_2 {
    background-color: #9CCC65 !important;
}

.event_3 {
    background-color: #40C4FF !important;
}

.event_4 {
    background-color: #BDBDBD !important;
}

And assign these classes to the appropriate events:

scheduler.templates.event_class = function (start, end, event) {
    return "event_" + (event.status || "");
};

And the coloring should be done:

The template is called each time the event is repainted. So, if a user changes event status from the UI, a new color will be immediately applied.

And now we move to the inner content of events. As you remember, our aim is something like this:

labels

Here is how it can be implemented:

function getBookingStatus(key) {
    var bookingStatus = findInArray(scheduler.serverList("bookingStatuses"), key);
    return !bookingStatus ? '' : bookingStatus.label;
}

function getPaidStatus(isPaid) {
    return isPaid ? "paid" : "not paid";
}

var eventDateFormat = scheduler.date.date_to_str("%d %M %Y");
scheduler.templates.event_bar_text = function (start, end, event) {
    var paidStatus = getPaidStatus(event.is_paid);
    var startDate = eventDateFormat(event.start_date);
    var endDate = eventDateFormat(event.end_date);
    return [event.text + "<br />",
        startDate + " - " + endDate,
        "<div class='booking_status booking-option'>" + getBookingStatus(event.status) + "</div>",
        "<div class='booking_paid booking-option'>" + paidStatus + "</div>"].join("");
};

And css:

.booking_status, .booking_paid {
    position: absolute;
    right: 5px;
}

.booking_status {
    top: 2px;
}

.booking_paid {
    bottom: 2px;
}

.dhx_cal_event_line:hover .booking-option {
    background: none !important;
}

Step 6 – Tooltips

Tooltips are defined in the extension file which has to be added to the page after dhtmlxscheduler.js.

<script src="./scheduler/ext/dhtmlxscheduler_tooltip.js"></script>

After that we can define a tooltip content using tooltip_text template.

scheduler.templates.tooltip_text = function (start, end, event) {
     var room = getRoom(event.room) || {label: ""};

     var html = [];
     html.push("Booking: <b>" + event.text + "</b>");
     html.push("Room: <b>" + room.label + "</b>");
     html.push("Check-in: <b>" + eventDateFormat(start) + "</b>");
     html.push("Check-out: <b>" + eventDateFormat(end) + "</b>");
     html.push(getBookingStatus(event.status) + ", " + getPaidStatus(event.is_paid));
     return html.join("<br>")
};

Note that we reused helper functions we’ve declared for event text and header templates, all these templates are supposed to be declared in the same scope.

And here is how the result looks like:

There are a couple of things to consider regarding tooltips.

Tooltip template can be called very frequently. It’s preferable not to make the tooltip_text function too heavy. If the tooltip should show a result of some relatively complex calculations, it’s better to precalculate values and save them into some property of the event object, rather than calculating them each time from the tooltip template.

Find out the related docs here and here.

The template function does not support async/promise result and you can’t use synchronous requests there (technically one could, but that would hit client-side performance and usability hard).

Thus, if you need to load tooltip content from the backend, simply requesting the data from a tooltip wouldn’t be enough.

This is usually solved by loading the tooltip content into some property of an event via ajax and returning this property value from the tooltip template. If the property value is not loaded from the server yet, you can display some kind of placeholder. Here is a jsfiddle where we emulate ajax loading with timeouts, but the idea is the same.

Step 7 – Highlight weekends

It’s also done with the help of the extension which allows coloring time ranges from code.

One important thing – if you use the dhtmlxsheduler_limit.js extension together with the timeline, it should be added before the dhtmlxscheduler_timeline.js:

<script src="./scheduler/dhtmlxscheduler.js"></script>
<script src="./scheduler/ext/dhtmlxscheduler_limit.js"></script>
<script src="./scheduler/ext/dhtmlxscheduler_timeline.js"></script>

After you add the extension you can color days like this:

scheduler.addMarkedTimespan({
  days: [0, 6],
  zones: "fullday",
  css: "timeline_weekend"
});

CSS:

.timeline_weekend {
    background-color: #FFF9C4;
}

Here is the result:

A more complex use-case would involve loading areas you want to highlight from the backend.

Usually it’s done from onBeforeViewChange event. You can detect when the displayed date is changed and start loading markers for the displayed range.

Once they loaded – you can add them using scheduler.addMarkedTimespan and repaint scheduler to display them:

Step 8 – Configuring the lightbox

What we need from the details form:

For this we’ll need to add extensions where these controls are defined:

<script src="./scheduler/dhtmlxscheduler.js"></script>
<script src="./scheduler/ext/dhtmlxscheduler_minical.js"></script>
<script src="./scheduler/ext/dhtmlxscheduler_editors.js"></script>

And update the settings of the lightbox:

scheduler.config.lightbox.sections=[
  {map_to: "text", name: "text", type: "textarea", height: 24},
  {map_to: "room", name: "room", type: "select", options: scheduler.serverList("visibleRooms")},
  {map_to: "status", name: "status", type: "radio", options: scheduler.serverList("bookingStatuses")},
  {map_to: "is_paid", name: "is_paid", type: "checkbox", checked_value: true, unchecked_value: false},
  {map_to: "time", name: "time", type: "calendar_time"}
];

Note that no lightbox controls have a config for the default value – that’s intentional. Lightbox controls are configured to read the value from specific properties of the event object.

That means that instead of setting a default value for the lightbox control, you should set default property values of the scheduler event object itself. It’s done like we did in the step 0, the lightbox will reflect them once opened.

Also, add a following config for labels of lightbox controls:

scheduler.locale.labels.section_text = 'Name';
scheduler.locale.labels.section_room = 'Room';
scheduler.locale.labels.section_status = 'Status';
scheduler.locale.labels.section_is_paid = 'Paid';
scheduler.locale.labels.section_time = 'Time';

After that you’ll get the lightbox looking like this:

As you can notice, the description at the top-left container of the lightbox is now not quite useful for us:

time lightbox

We can redefine this content. Check the docs.

scheduler.templates.lightbox_header = function (start, end, ev) {
    var formatFunc = scheduler.date.date_to_str('%d.%m.%Y');
    return formatFunc(start) + " - " + formatFunc(end);
};

Step 9 – Preventing double bookings for the same time

To avoid double bookings, we’ll use this extension.

<script src="./scheduler/ext/dhtmlxscheduler_collision.js"></script>

Once you add it to the page, it will revert actions that put several events to the same time.
You can also control this behavior by capturing the onEventCollision event either to conditinally allow double bookings, or simply show a user some warning

scheduler.attachEvent("onEventCollision", function (ev, evs) {
  for (var i = 0; i < evs.length; i++) {
    if (ev.room != evs[i].room) continue;
    dhtmlx.message({
      type: "error",
      text: "This room is already booked for this date."
    });
  }
  return true;
});

Conclusions

Overcoming the learning curve of dhtmlxScheduler, you’ll see that it’s possible to build on new features and change the look and behavior of the component pretty simply. We hope that this tutorial gave you a clear understanding how the Timeline of dhtmlxScheduler behaves and helped you in achieving your own goals when building your applications.

If you’re already familiar with our tutorials, you may notice that this time we used jsfiddle to provide you with a more detailed and informative description of each step. Do you find it useful?

Also, if you have any thoughts and ideas what the next topics/tutorials you would like to discover, don’t hesitate to share them in comments. We are open for suggestions.

Originally published on Dec 21, 2017, 14:00

The post How to Make Hotel Booking Calendar with dhtmlxScheduler appeared first on DHTMLX Blog.

JavaScript Bar Chart: Exploring Data Visualization Techniques

$
0
0

DHTMLX Chart, a part of the modern Suite UI library, consists of different types of graphs. One of the most widely used is a javascript bar chart, which allows comparing data categories and seeing their changes over time. Try out dhtmlxChart by downloading a 30-day free trial.

Where to Use JavaScript Bar Charts?

A bar graph is a visual tool that allows comparing data among categories. The chart displays categorical data as rectangular bars with heights equivalent to the values that they represent. Usually, the categories appear along the horizontal axis, and a vertical one represents a measured value of the categories being compared.

HTML Bar Chart by DHTMLX

Simply put, bar charts are a must-have in the data visualization arsenal. They are quick to create, show comparison clearly, and are easy for the audience to understand.

A bar chart in JavaScript has the following fields of use:

  • Providing an intuitive view to the values of each category.
  • Comparing sets of data between different groups at a glance. Thus, for example, users can analyze data by a quarter or annually and see how results are distributed throughout each year.
  • Tracking big changes in data over time (for example, months or years).
What Are the Ways to Visualize Data With a Bar Graph?

If you have to show the frequency and ratio of each category, a single bar chart would be the best solution. Thus you will see the values of items clearly with the length of each bar.

Simple bar chart by DHTMLX

Moreover, a simple JavaScript bar chart allows arranging bars in any order. Bar graphs organized from highest to lowest incidence are called Pareto charts. In this way, the graph visually depicts which situations are more significant.

A single HTML bar chart is intuitive to view the values. However, there is one noticeable limitation: as soon as you have more than about 10 categories being displayed next to each other, labels can become hard to read. Indeed Y-bar graphs don’t leave much space for the text below.

A horizontal bar chart in HTML/JavaScript solves this issue. X-Bar graphs allow for much longer label text because the labels are above each other and not beside.
JS horizontal bar chartCheck the sample >

Some bar graphs present columns sorted in groups, showing the values of more than one measured variable. These are clustered bar charts used to compare multiple series inside the same category.

In clustered bar charts, each categorical group consists of two or more bars. Let us suppose that a business owner decided to compare the revenue of his 3 companies. Thus he can build a grouped graph.

Below you can see a clustered HTML bar chart example with different colored bars to represent each company. The horizontal axis shows the months of the year and the vertical one illustrates the profit.

Сlustered bar chart by DHTMLXCheck the sample >

As a clustered bar chart makes it complex to show the differences between the totals of each group, JavaScript stacked bar graph comes in to fix it. It is composed of multiple bar series placed vertically one after the other. If there are any negative values, they are stacked in reverse order below the chart’s axis baseline.

HTML stacked bar chart is a good choice if you have to:

  • Demonstrate the total size of the groups.
  • Track the variation in the individual values along with their total value.
  • Visualize data that is naturally divided into components, like sales by district, time span or product type.

Stacked bar chart by DHTMLXCheck the sample >

With a vertical diverging bar chart in JavaScript, end-users can view the spread of negative and positive values. The key point is comparing data with a middle point and categorizing chart bars above and below a common baseline.
Base line in JS bar chart by DHTMLXCheck the sample >

Why Build JavaScript Bar Chart with DHTMLX?

Building a bar chart using JavaScript is simple and convenient with our dhtmlxChart component, which also provides 10 other types of graphs: X-Bar, Line and Spline, Area and Spline Area, Pie and Donut (that have 2D and 3D variations), Radar and Scatter charts.

Material Styling

Back in 2014, Google announced guidelines designed to support a common look and feel across applications that run on Google platforms. This effort, called Material Design, uses more grid-based layouts, improved color palette, clearer label formatting, and depth effects such as lighting and shadows.

We at DHTMLX respect common practices and have designed our Chart component in Material style.

Suitable Configuration

Our bar chart is highly flexible. Users can easily modify scales, series, and legend and even toggle off a series in a legend by using our API.

Here you can see how to create a bar chart in HTML using JavaScript and configure series:

var chart = new dhx.Chart("chart_container",{
    type:"bar",
    scales: {
        "bottom" : {
            text: "month"
        },
        "left" : {}
    },
    series: [
        {
            id: "A",
            value: "company A",
            fill: "#394E79",
            stacked: stacked,
            color: "none"
        },
        {
            id: "B",
            value:"company B",
            fill: "#5E83BA",
            stacked: stacked,
            color: "none"
        }
    ]
});

You are also able to choose the proper type of scales and tailor it depending on your needs:

var chart = new dhx.Chart("chart_container",{
    type:"area",
    scales: {
        "bottom" : {
            text: 'month'
        },
        "left" : {
            padding: 10,
            max: 90
        }
    },
    series: [
        {
           value: 'company A',
           strokeWidth: 2
           // more options  
        }
    ]
});

The configuration of a chart legend includes a number of options, for instance, enabling you to add a legend and define its position:

var chart = new dhx.Chart("chart_container",{
    scales: {
        // scales config
    },
    series: [
        // list of series
    ],
    legend: {
        series: ["A", "B", "C"],
        valign: "top",
        halign: "right"
    }    
});
Flexible Customization

Style manipulations are achieved via CSS. dhtmlxChart component lets you control several aspects of bar appearance, tailor paddings, margins, and sizes of all graph’s elements. Our users can specify colors and transparency, apply a color gradient to bars as you can see in the screenshot below.

Js bar chart with gradient by DHTMLXCheck the sample >

However, despite the endless opportunities for customizing our JavaScript bar chart library, we highly recommend to choose a proper style and focus on it. Do not mix various styles too freely inside the single chart.

DHTMLX Chart is a part of the Suite UI library. Thus, you can test and order dhtmlxChart as a separate component or choose a complete Suite library with 20+ full-featured widgets. Our cutting-edge JavaScript library allows building modern and rich web interfaces, makes them compatible with all modern browsers and provides integrations with React, Vue.js, and Angular.

Conclusion

Data visualization gets easier and more exciting when you understand what tools and under what conditions are the best. A simple bar chart, for example, allows comparing values in a single data series. Users are able to analyze data sets between different groups and capture data changes over time.

DHTMLX fully-featured JavaScript chart library offers different graph types to illustrate whatever you need and build a rich user experience. Get deeper insight into the features of our charts by accessing our documentation.

You can download a 30-day trial version for free in case you decided to try dhtmlxChart library possibilities.

Do not hesitate to contact us if you have any issues or leave your comments below.

The post JavaScript Bar Chart: Exploring Data Visualization Techniques appeared first on DHTMLX Blog.

How to Manage Columns Visibility in the Grid of dhtmlxGantt – Video Tutorial

$
0
0

Let’s keep on learning all the valuable possibilities of our JavaScript Gantt library with the help of our video tutorials.


In the fourth video from our series, we’ll dive into managing the columns visibility in the grid of dhtmlxGantt. The challenge you can face is that users may want to show all the possible info in the grid, to the point that the grid may take up all the available space:
JS Gantt ColumnsThere are two possible solutions for that. We can either add a horizontal scrollbar into the grid and make it thinner, or allow a user to select which columns are going to be visible.

Horizontal Scroll

Let’s start with the first approach. We can make our grid scrollable using the scrollable property of the layout configuration option:

gantt.config.layout = {
    css: "gantt_container",
    cols: [
        {
        width:400,
        min_width: 300,
        rows:[
            {view: "grid", scrollX: "gridScroll", scrollable: true, scrollY: "scrollVer"},
            {view: "scrollbar", id: "gridScroll", group:"horizontal"}
        ]
        },
        {resizer: true, width: 1},
        {
        rows:[
            {view: "timeline", scrollX: "scrollHor", scrollY: "scrollVer"},
            {view: "scrollbar", id: "scrollHor", group:"horizontal"}
        ]
        },
        {view: "scrollbar", id: "scrollVer"}
    ]
};

Check the source code >

We split the Gantt layout into several columns:

  • The grid
  • The timeline
  • The resizer element between the grid and the timeline
  • And the vertical scrollbar

In order to add an inner scrollbar into the grid element, add the scrollable property to the grid object and connect it to the horizontal scrollbar located in the same column. After that we can scroll the grid using the scrollbar element.

We also need a horizontal scrollbar for the timeline element, which is added in the same way.

Lastly, we connect both the grid and the timeline to the same vertical scrollbar element in order to synchronize their vertical position.
Horizontal Scrollbar in GanttCheck the documentation >

Hiding Columns in the Grid

Another approach to our original challenge is to provide a user with an ability to select which columns should be visible:
Visible columns of the Grid in Gantt

To do so, add a UI element where a user will be able to specify the visible columns and change the configuration of the grid after the user’s selection. You can hide any column either by removing it from the columns config or by setting the hide:true property.

Given that we already know how to add a UI control where a user can select columns as well as add a dropdown menu to the Gantt header – all we need is to add inputs for each defined column. When the selection changes, we prepare an array of selected columns:

function createColumnsConfig(selectedColumns){
    var newColumns = [];

    allColumns.forEach(function(column){
        if(selectedColumns[column.name]){
            newColumns.push(column);
        }
    });

    newColumns.push(controlsColumn);
    return newColumns;
}

Assign it to the columns config and repaint the Gantt:

dropDown.onchange = function(){
    var selection = getColumnsSelection(dropDown);
    gantt.config.columns = createColumnsConfig(selection);
    gantt.render();
}

Check the source code >

Ready to try it out on your own Gantt? Download our free 30-day trial version and get down to experimenting with the visibility of columns in the grid of dhtmlxGantt.

We also invite you to subscribe to our YouTube channel and keep an eye on the latest video tutorials!

Related Materials:

The post How to Manage Columns Visibility in the Grid of dhtmlxGantt – Video Tutorial appeared first on DHTMLX Blog.

dhtmlxScheduler 5.3 Minor Update: RTL Support and Improved Responsiveness

$
0
0

Good news for the users of RTL languages and mobile device addicts! A brand new v5.3 of our JavaScript event calendar comes out with the support for right-to-left locales and greatly enhanced UI/UX for mobile screens. Besides, in v.5.3 we’ve polished Scheduler’s compatibility with our state-of-the-art Suite UI library.
Download dhtmlx Scheduler - JavaScript event calendar

Feel free to download and evaluate Scheduler’s update 5.3 and share your feedback with us!

RTL Mode

RTL mode is a highly-demanded feature of many users in the Eastern world. In v5.3 our dev team equipped dhtmlxScheduler with a new configuration option ensuring RTL support:

scheduler.config.rtl = true;

By default, the rtl property is set to false. In order to switch on the RTL mode, developers should specify the rtl=true configuration option before the component’s initialization. It will make dhtmlxScheduler automatically display all the events from right to left as shown in the picture below:

RTL mode of DHTMLX SchedulerCheck the sample >
After that, you may also reorder the elements of the header via CSS if needed.

The RTL mode changes the appearance of all Scheduler views as well as the lightbox:
DHTMLX Scheduler RTL viewsCheck the sample >

Meanwhile, dhtmlxScheduler can be easily customized in the RTL mode according to your requirements. We prepared a list of additional CSS classes, to which you may apply any styles you need and thus fine-tune the look and feel of your event calendar:

  • dhx_cal_container_rtl – sets styles for the container
  • dhx_tooltip_rtl – sets styles for tooltips
  • dhx_quick_info_rtl – sets styles for the ‘quick info’ popup
  • dhx_cal_light_rtl – sets styles for the lightbox
Improved Responsiveness

Another challenge that our users face is making Scheduler responsive on small screens. Starting with v5.3, things should become much easier for developers. We tried to address two main issues that were receiving quite a lot of complaints regarding mobile support – the navigation (or header) panel on top of Scheduler and the lightbox.

Now you can easily define headers that would look good on mobile screens using the header configuration property. The lightbox has a mobile friendly mode, which can be enabled via the responsive_lightbox configuration option.

That’s how dhtmlxScheduler looks like on mobile devices now:
DHTMLX Mobile SchedulerCheck the sample >

While a responsive lightbox is disabled by default, you can enable it via the responsive_lightbox configuration option:

scheduler.config.responsive_lightbox = true;

We also introduced a new CSS class dhx_cal_light_responsive for the responsive lightbox, which allows you to customize it to meet your needs.

Integration with dhtmlxSuite 6

On top of all, the latest v5.3 of our event calendar implements smooth integration with DHTMLX UI components library – dhtmlxSuite 6. Read more in the documentation >

We are eager to invite our users to evaluate a brand new v5.3 during a 30-day trial period. Our clients are welcome to get the latest update in their Client’s Area.

We’re looking forward to your feedback!

Related Materials:

The post dhtmlxScheduler 5.3 Minor Update: RTL Support and Improved Responsiveness appeared first on DHTMLX Blog.

JavaScript Pie Chart and How to Use It Properly

$
0
0

We continue learning about the DHTMLX Chart library. In this article, we explain the basic principles of a JavaScript pie chart and characterize the ways to use circle graphs effectively. You are free to try dhtmlxChart by downloading a 30-day trial version.

Effective Tips to Create a Pie Chart Using JavaScript

Widely used in presentations and infographics, an HTML/JavaScript pie chart is a common way to illustrate quantity proportions between categories. By cutting a pie into slices, you highlight the size of each data point and thus compare parts to the whole graph, equal to 100%.

Pie Chart Demo

Pie charts are perfect for giving the reader a quick understanding of the proportional data distribution. However, there are many ways to get them wrong.

The following are the rules of thumb for building an effective JavaScript pie chart:

  • You have only one data series.
  • None of the data values are less than or equal to zero.
  • The values have to differ. Small differences in slices are hard to understand, so users won’t be able to see which parts are larger or smaller without a hint. Moreover, having similar-sized categories makes a pie chart look cluttered.
  • There’s an adequate small number of slices, e.g. from 6 to 10 categories maximum. As the number of values shown increases, the size of each segment becomes smaller. It makes a chart difficult for the eye to distinguish between the relative sizes of the different sectors.
  • You can sort slices by value in clockwise decreasing order starting at 12 o’clock.
  • A slice that contains a total amount of some values (commonly named as “other” or “other types”) is usually placed in the end even if it is not the smallest category. This method is to not distract from the individual categories of interest.
JavaScript Pie Chart Types and Ways to Use Them Efficiently

Let’s say you have to compare the workload of your development team for the first 5 months of the year. Then you can build a simple pie chart in HTML to see how much (i.e., how many tasks) the team has contributed to the development process as a whole.

Take a look at the pie graph presented below, used to showcase the workload for five months:

Simple Pie Chart
Check the sample >

This HTML pie chart example gives a quick comparison between the number of completed tasks per month and the activity during the first part of the year. We are able to deduce the following points at a glance: March was the most productive month while the lowest activity level took place in February and May.

A 3D pie chart adds a pinch of aesthetics to the flat 2D graph by making it deeper:

Pie3D Chart
Check the sample >

You can separate one or more segments from the circle and create an exploded pie chart. The separated slices look as if they were cut from the pie and moved from its center. This effect is applied to either draw special attention to the slice or to highlight smaller chart categories with minimum values.

Another variation of a JavaScript pie chart is a donut graph with a hole in the center. This type of circular graph offers a better data intensity ratio to standard pie charts. Donut charts are more space-efficient because the blank space inside can be used to display additional information.

Donut Chart
Check the sample >

Summing up, wherever you can use a pie chart, you might as well create 3 other types described above.

Reasons to Create a Pie Chart in JavaScript with DHTMLX

DHTMLX Chart library is an effective and time-saving solution to assemble a pie chart using JavaScript. Apart from Pie and Donut charts, including 2D and 3D variations, the component also provides 8 types of commonly used graphs: Bar and X-Bar, Line and Spline, Area and Spline Area, Radar and Scatter.

Material Design Styling

Our JavaScript pie chart library follows the rules of a Material-based design. We cover best practices to help you build modern web interfaces that are scalable across all major platforms and devices.

Multiple Configuration Options

dhtmlxChart API properties allow configuring all chart types while the config options are individual for particular types. For instance, look how to create a pie chart in HTML using JavaScript:

var chart = new dhx.Chart("chart", {
    type:"pie"
});

Since pie graphs are primarily for showing data proportions, the percentage represented by each category should come next to the corresponding slice of a chart. You can build a JavaScript pie chart with labels, enable the legend and define its position:

var chart = new dhx.Chart("chart_container",{
    scales: {
        // scales config
    },
    series: [
        // list of series
    ],
    legend: {
        series: ["A", "B", "C"],
        valign: "top",
        halign: "right"
    }    
});
Advanced Customization Opportunities

dhtmlxChart comes with a broad set of config options that offer complete control over Pie, Pie3D and Donut graphs appearance. The component allows building a chart with monochrome fill or defining a color for each sector, which can be divided by lines with custom colors.

You can connect chart slices with labels by adding lines. Besides, pie and donut charts can display the percentage and values of data items as well as come naked without labels.

As far as a legend is a part of a JavaScript pie chart, its look may be turned according to your project specifications. Thus, you can choose square or circle marker shapes, apply custom paddings and margins between legend items and the scale.

Take a look at the screenshot below. We built an interactive dashboard that can be embedded in real-life web applications, for example, CRM systems. Here you can find a customized pie chart in monochrome blue colors with a one-column legend on the right. We also added an area chart, both are in the same style.

UI Dashboard Demo
Check the full UI Dashboard demo >

Moreover, you are able to tailor all chart elements (including those omitted in config options) to suit your needs by adding new CSS classes.

Conclusion

Pie and donut charts are commonly used to visualize data as a circle sliced into sectors that each represent a percentage of the whole. Despite their benefits, circle graphs are increasingly criticized and overlooked by the web community. We at DHTMLX are aware of how important and sometimes difficult it is to build a clear and intuitive pie chart. So in this article, we tried to bring useful tricks in pie charting.

Being a part of the dhtmlxSuite UI library, Chart component helps to build rich web interfaces and applications that are compatible with all modern browsers and popular frameworks including Angular, React, and Vue.js.

You can download a 30-day trial version of dhtmlxChart or test a full Suite kit with 20+ UI components included. Access our documentation to receive thorough information about DHTMLX JavaScript charts features.

Do you have any questions for our team? Feel free to contact us and share your concerns.

The post JavaScript Pie Chart and How to Use It Properly appeared first on DHTMLX Blog.

DHTMLX Suite 6.2: Grid with New Editors, Drag-n-Drop, and Flexible Columns, Calendar Range Mode, and More

$
0
0

Our JavaScript UI components are empowered with new abilities, boosted performance, and a more developer-friendly API in v6.2.

Now DHTMLX Grid is equipped with new filter and editor types, drag-n-drop of rows, hiding and resizing of columns, and export to CSV. DHTMLX Calendar receives a new range selection mode. Form and Layout components become much more convenient and flexible to work with due to newly introduced API methods and events. Besides, v6.2 brings out helper guides on how to use DHTMLX default icons and CSS classes to accelerate web development.

Download evaluation version 6.2 and try it out in your projects free of charge for 30 days!

Grid with Surpassing Performance and Enriched Functionality

First and foremost, v6.2 has made our Grid blazing fast accelerating its speed to 2.5x:

New Editor and Filter Types

Secondly, the update introduces two new types of editors for cells of Grid columns: combobox and checkbox.

DHTMLX Grid editorsCheck the sample >

A combobox editor represents a dropdown list of options, which can be filtered by typing in text in the editor cell. This type of editor is enabled by setting the editorType: “combobox” property for a particular column and specifying options to choose from:

{
   width: 160, id: "test", header: [{ text: "Test" }], type: "string",

   editorType: "combobox", options: ["1 time", "1-2 times", "more than 5 times"]
}

A checkbox editor can be applied for columns with a binary choice. In order to implement this type of editor, you only need to specify the type: “boolean” property for a column. In case the editing option is enabled in the whole Grid, then the checkbox editor will be switched on for the respective columns by default.

{
    // if the type:"boolean" config is set in the column config,
    // there's no need to specify the type of the editor
    width: 160, id: "test",
    header: [{ text: "Test" }],

    type: "boolean"
}

Apart from the editing functionality, a combo box control can be used as a filter in the Grid header or footer for quickly searching for the necessary data:

{
    width: 160, id: "renewals",

    header: [{ text: "Number of renewals" }, { content: "comboFilter" }],
    type: "string", editorType: "combobox",
    options: ["1 time", "1-2 times", "more than 5 times"]
}

Check the sample >

Various additional configuration properties allow developers to refine this filter type depending on their needs – for example, load data dynamically while scrolling the list of options. Read more in the documentation >

Drag-n-Drop of Rows

Starting with v6.2, end users are able to easily rearrange Grid rows by dragging and dropping them with the mouse. Drag-n-drop operations can be enabled within one Grid or several Grids according to the specified mode. For instance, here you can see how to drag-n-drop rows within one Grid by setting the dragMode:both property in the configuration object of Grid:

var grid = new dhx.Grid("grid_container", {
   columns: [
        { id: "country", header: [{ text: "Country" }] },
        { id: "population", header: [{ text: "Population" }] }
    ],
    data: dataset,

    dragMode: "both"
});

Row drag-n-drop in GridCheck the sample >

Manipulating Columns

Another enhancement in v6.2 concerns the flexibility of working with Grid columns. The update delivers a wide range of new configuration properties for controlling the maximum and minimum column width, making columns hidden, and resizing them from the UI.

For example, the hidden:true property specified in the config of a column hides it in Grid:

{
    width: 150, id: "population", header: [{ text: "Population" }]
},
{

    hidden: true, width: 150, id: "yearlyChange", header: [{ text: "Yearly Change" }]
}

Check the sample >

The resizable:true option specified in the configuration of the whole Grid or a particular column enables manipulating the columns’ size by end users with the help of the mouse:

var grid = new dhx.Grid("grid_container", {
    columns: [// columns config],
    data: dataset,

    resizable: true
}

Resizing columns in DHTMLX GridCheck the sample >
Meanwhile, developers can disable the resizing of specific columns by setting the resizable:false property in their config:

var grid = new dhx.Grid("grid_container", {
    columns: [
        { width: 150, id: "test1", header: [{ text: "Test1" }] },

        { width: 150, id: "test2", header: [{ text: "Test2" }], resizable: false }
    ],
    data: dataset,

    resizable: true
}

On top of all, you can predefine the limits, within which columns can be resized from the UI, by defining their minimum and maximum width.

Export to CSV

In addition to Excel, now Grid supports exporting of its data into the CSV format. You can choose to export data to a CSV file or just as a string. Read more in the documentation >

In v6.2 DHTMLX TreeGrid also receives all the new features and improvements described above. For all the details, study the documentation.

New Range Mode in DHTMLX Calendar

Besides the ability to link two calendars for showing a date range on them, v6.2 allows displaying a range of dates on one calendar only. This mode is easily enabled via the range:true option in the calendar configuration object, where you should also define the start and end dates of your range:

var calendar = new dhx.Calendar("calendar", {
    css: "dhx_widget--bordered",
    range: true,
    value: ["03/06/19", "15/06/19"]
});

DHTMLX Calendar Range Mode
Check the sample >

Enlarged API in Form and Layout

Now working with Form and Layout components is much more straightforward and intuitive, as v6.2 supplies them with a wide range of methods and events.

From now on, developers are able to manipulate separate Form controls: DatePicker, Checkbox, ColorPicker, Combo, Input, RadioGroup, Select, SimpleVault, Slider, Text, Textarea, TimePicker – and update their configuration on the fly. Check Form API >

Moreover, new Layout events provide more control over the components’ behavior in order to assemble complex user interfaces, especially with custom content in them.

DHTMLX Guides for CSS Classes and Icons

Apart from the new functionality, our dev team designed special guides, which would assist you in the development of web apps using our UI library:

We’re eager to receive your feedback about the release and continue our work on the Suite UI library. Don’t hesitate to contact us and share your ideas!

Try out the latest v6.2 during a 30-day evaluation period >

Current clients are welcome to get their updated version in Client’s Area.

Related Materials:

The post DHTMLX Suite 6.2: Grid with New Editors, Drag-n-Drop, and Flexible Columns, Calendar Range Mode, and More appeared first on DHTMLX Blog.


Maintenance Release: DHTMLX Gantt 6.2.7, Diagram 2.1.1, Scheduler 5.3.3, and Suite 6.2.2

$
0
0

This year, October has been a fruitful month for maintenance releases. Apart from two big updates of our JavaScript event calendar and Suite UI components library, all our principal products received new patch versions.

What’s New in DHTMLX Gantt 6.2.7:

October 11, 2019

  • (Fixed) The issue with vertical resizing of grids with horizontal scroll in complex layouts
  • (Fixed) The incorrect work of the resource histogram when the scale step is greater than one
  • (Fixed) The reopened bug with collapsed branches after calling gantt.parse from v6.2.4 bugfix

Learn more in the documentation >

What’s New in DHTMLX Diagram 2.1.1:

October 11, 2019

  • (Fixed) Issues with img-card in IE

Learn more in the documentation >

What’s New in DHTMLX Suite 6.2.1 and 6.2.2:

October 25 and November 5, 2019

  • (Fixed) Issue with the setValue() method in Calendar
  • (Fixed) Issue with the combo filters in Grid
  • (Fixed) Issues with selection in Grid
  • (Fixed) Issue with the height of a cell in Layout

Learn more in the documentation >

What’s New in DHTMLX Scheduler 5.3.1-5.3.3:

October 30, 2019

  • responsive_lightbox is disabled by default
  • (Fixed) Incorrect work of the click handler in the Mini Calendar when a custom calendar_date template is defined
  • (Fixed) Rounding of the end date of an event when it is resized in Day/Week views
  • More informative error messages for common misconfigurations are added
  • HTML markup of some public samples is cleaned up

Learn more in the documentation >

If you haven’t tried the latest evaluation versions of our JavaScript libraries yet, you may download them here (free for 30 days):

Current clients are invited to download the updated components in their Client’s Area.

The post Maintenance Release: DHTMLX Gantt 6.2.7, Diagram 2.1.1, Scheduler 5.3.3, and Suite 6.2.2 appeared first on DHTMLX Blog.

DHTMLX Gantt Chart 6.3 with Decimal Durations, Link Formatting, Drag-n-Drop of Multiple Tasks, and Even Smarter Rendering

$
0
0

We’re eager to deliver the next important update of our HTML5 Gantt chart library. This time, our development team has put a lot of effort into making DHTMLX Gantt even smarter and more flexible in v6.3.

From now on, Gantt users may benefit from a new intelligent module for converting duration units from days to hours or minutes and back and specifying task duration in decimal format. Additionally, now our Gantt has an MS Project-like way of showing dependency links in the grid. We have also polished up scrolling the timescale, drag-n-drop of multiple tasks, and fullscreen mode. And that’s not all the new features and improvements in v6.3 – just keep on reading!

Download a free 30-day evaluation version of DHTMLX Gantt 6.3 now >

Intelligent Duration Formatting [PRO]

In the previous versions of DHTMLX Gantt users could set task durations in whole numbers only. Starting with v6.3, they can specify the duration in fractional numbers as well. Now there’s no difficulty in assigning tasks that are 2.5 hours or 0.5 days long. Moreover, now Gantt is capable of converting minutes into hours, hours into days, days into months, etc. and vice versa.

Decimal Duration - DHTMLX GanttCheck the sample >

All that is possible due to a brand new Duration Formatter module, which is easy to set up.

Firstly, if you’d like to specify task duration in fractions of an hour precision (for example, set the duration to 0.5 hours), you’ll need to store the duration of tasks in minutes:

gantt.config.duration_unit = "minute";

Storing duration in hours will do as well and may be even better for the overall performance of the Gantt chart:

gantt.config.duration_unit = "hour";

When you are done with that, just create the formatter object as described below and add it to the Duration column of the grid, lightbox, and inline editors if necessary:

// formatting the duration
var formatter = gantt.ext.formatters.durationFormatter({
    enter: "day",
    store: "minute", // duration_unit
    format: "day",
    hoursPerDay: 8,
    hoursPerWeek: 40,
    daysPerMonth: 30
});
gantt.config.columns = [
    {name: "text", tree: true, width: 170, resize: true, editor: textEditor},
    {name: "start_date", align: "center", resize: true, editor: dateEditor},
    {name: "duration", label:"Duration", resize: true, align: "center",
        template: function(task) {
            return formatter.format(task.duration);
        }, width: 100},
    {name: "add", width: 44}
];
MS Project-Like Link Formatting [PRO]

In v6.3 DHTMLX Gantt provides an alternative way of linking tasks with each other via inline editors in the grid. It is based on MS Project formats of task dependencies:

  • finish_to_finish: “FF”
  • finish_to_start: “FS”
  • start_to_start: “SS”
  • start_to_finish: “SF”

Now end users can fill in cells of the grid with inline editors responsible for linking tasks by typing in abbreviations common for MS Project. For example, “2FF+1 day” abbreviation means that one of the tasks should be finished not later than one day after the end of the second task. Such link formatting can be enabled via the Link Formatter module. Read more in the documentation >
MS Project Task Dependencies in DHTMLX GanttCheck the sample >

Scrolling the Timeline with the Mouse

Working with huge Gantt charts is more convenient now, as end users can quickly scroll the timeline using mouse click and drag:
Scrolling the timeline - DHTMLX GanttCheck the sample >

This ability can be implemented with the help of the dhtmlxgantt_drag_timeline extension:

<script src="../codebase/ext/dhtmlxgantt_drag_timeline.js"></script>

The properties of the drag_timeline object allow you to control the behavior of Gantt elements while scrolling the timeline. The useKey property enables scrolling only when you press the specified key like Ctrl, Shift, Alt, etc. Besides, you can define which Gantt elements shouldn’t be affected in the process of scrolling by adding their CSS classes to the ignore property:

gantt.config.drag_timeline = {
      ignore:".gantt_task_line, .gantt_task_link",
      useKey: false
};

Additionally, we enlarged the API of horizontal scrolling in the timeline. Now developers can change the default Shift key to Alt or Meta keys in the horizontal_scroll_key property or even disable the horizontal scroll.

Displaying Tasks Outside of the Specified Time Range

Previously, users faced a problem of not being able to see the tasks that were assigned on dates outside of the limited time range of the Gantt chart. V6.3 copes with this issue by showing such tasks in the grid, even if they start and end before or after the specified time period. For instance, in the project below tasks 1 and 3 take place in January and March respectively. These tasks are listed in the grid, while the chart displays only the tasks scheduled for February 2020. Learn more in the documentation >
Tasks Outside the Timescale - DHTMLX GanttCheck the sample >

Drag-n-Drop of Multiple Tasks

Due to the ext/dhtmlxgantt_multiselect.js extension, it’s possible to select multiple tasks and manage them all together. In v6.3 the newly introduced drag_multiple method allows selecting several tasks by Shift or Ctrl-clicking and moving them simultaneously while saving their position in relation to each other:

gantt.config.drag_multiple = true;

The same approach can be applied to projects by using the drag_project method:

gantt.config.drag_project = true;

Drag-n-Drop of Multiple Tasks - DHTMLX GanttCheck the sample >

Other Important Updates
Smart Rendering Update

The release revamped the smart rendering techniques in order to further improve Gantt performance with large data sets. Now our updated Gantt chart is able to understand the exact position of custom elements such as baselines, deadlines, milestones, etc. and render them only when they are visible. It became possible due to the renderer configuration object, which keeps track of the visible area of the chart as well as the position of custom elements and decides whether to display them or not. Learn more in the documentation >

Full-Screen Mode

V6.3 brings out the ability to display not only the Gantt chart itself but also its header and other additional elements in the fullscreen mode.

How to Undo Custom Actions

Another essential update is the possibility to undo and redo changes you make to your Gantt from the code. Read more in the documentation >

Compatibility with RequireJS

V6.3 introduces some changes to the usage of RequireJS with DHTMLX Gantt. For more details, consult the migration article.

Inclusive End Dates in the Timeline

In the previous versions, the grid column with the end date of tasks comprised exclusive dates. For example, the end date of the task starting on November 10 and lasting for 3 days would fall on November 14 in the grid. Whereas, the timeline displayed the duration of the task taking into account only inclusive dates (November 10-13). In order to avoid confusion and show inclusive dates everywhere, v6.3 offers a special template for redefining the format of end dates in the grid and lightbox.

We hope all the new features and updates will come in useful in your projects. We’re eager to get your feedback and continue further enriching the abilities of DHTMLX Gantt!

Please note that the features marked with PRO label are available under the Professional edition of paid licenses only.

We invite you to try out the latest version during a free 30-day evaluation.

Current clients may download dhtmlxGantt 6.3 in their Client’s Area.

The post DHTMLX Gantt Chart 6.3 with Decimal Durations, Link Formatting, Drag-n-Drop of Multiple Tasks, and Even Smarter Rendering appeared first on DHTMLX Blog.

Customer Spotlight: dhtmlxSuite and dhtmlxScheduler for Pixel Nation

$
0
0

Headquartered in Richmond Hill, Ontario, Pixel Nation Inc. is a vendor-independent software development company. Their Core Framework platform was built with the help of the DHTMLX Suite and Scheduler libraries. Why the company chose our solutions and whether they met the expectations? Let’s find out!

Pixel Core is a development framework that provides common basic functionality out of the box. The product was designed to save developers from management tasks so they could focus on implementing specific business requirements.

Core Framework includes client management, robust roles and permissions, authorization, and authentication. Customers are equipped with reporting, scheduling, and scripting functionalities. Having outlined components at hand reduces time to market for new products.

pixel-core-login

The main requirements for choosing a UI framework were the richness and flexibility of its components. Out of many options available, the Pixel Nation team went for dhtmlxSuite controls library and dhtmlxScheduler event calendar.

The ability to initialize DHTMLX components without a learning curve was one of the key criteria. Moreover, our libraries have very extensive documentation and robust samples. The team thought API was consistent and admitted it was pretty easy to integrate different components into layouts.

pixel-core-registration

Pixel Nation extended DHTMLX and added some wrappers around components. Finally, the team received a powerful UI framework. It’s easy to build standard cases and extensible enough to develop complex single-page interfaces.

One of the Suite components, dhtmlxGrid, provides powerful support for infinite scrolling. Thanks to this functionality they can effectively display data in searchable and scrollable lists with an unlimited number of rows.

pixel-core-grid

DHTMLX Form maintains an intuitive view. Thus, end-users are able to clearly see what is missing or has invalid data.

Pixel Core also provides scheduled tasks support. Thanks to our Scheduler component, applications based on Core Framework allow monitoring and completing tasks at specific times.

pixel-core-schedule-timeline

Users can view task history displayed in a grid layout. They are able to analyze and configure long-running assignments. For instance, users can change timelines and limit the impact of heavy tasks to focus on other system’s functionality.

pixel-core-form

We at DHTMLX are grateful to Pixel Nation for sharing their case of using our libraries!

Do you want to tell us your own story? Fill in a form and receive a special bonus from our team.

The post Customer Spotlight: dhtmlxSuite and dhtmlxScheduler for Pixel Nation appeared first on DHTMLX Blog.

DHTMLX Diagram 2.2: Build Any Type of JavaScript Diagrams and Org Charts with Custom Shapes

$
0
0

Great news for DHTMLX Diagram users!

A brand new version of our JS diagram library 2.2 is out. Hurry up to get acquainted with new powerful abilities – adding any custom shapes you wish and building mixed org charts and diagrams.

Download a free 30-day evaluation version of DHTMLX Diagram >

Custom Shapes via SVG and HTML Templates

The release rolls out the most awaited ability to equip DHTMLX Diagrams with any types of shapes you desire. Now your opportunities are not restricted to a range of predefined shapes and you are free to build UML class diagrams, network diagrams, life cycle charts, Venn diagrams, and whatnot.

Venn diagramVenn diagrams are designed for finding patterns and defining logical relations among groups of objects, which are usually split into 3 sets. Overlapping areas stand for common characteristics of objects in question. Check the sample >

Network diagramNetwork diagrams usually depict the structure of telecommunication systems. Besides, they can be applied in project management for showing the process flow. Check the sample >

Life cycle diagram with sticky notesLife cycle diagrams make it easy to illustrate the stages of a product’s or project’s life cycle. In our example, the stages of the development process are designed with the help of yellow sticky notes. Check the sample >

UML class diagramUML Class Diagram for software engineering. Check the samples with HTML template and SVG template >

Embedding custom-made shapes into DHTMLX Diagram became possible due to newly introduced SVG and HTML templates. Now building a custom diagram takes just two steps:

  • Create a new SVG or HTML template for shapes:
  • // creating SVG template
    diagram.flowShapes.customShape = function(config) {
        var svg = '<svg width="'+ config.width +'" height="'+ config.height +
                                '" viewBox="0 0 '+ config.width +' '+ config.height +
                                '" fill="none" xmlns="http://www.w3.org/2000/svg">';
            svg += '<rect width="'+ config.width +'" height="'+ config.height +
                                '" fill="'+ config.fill +'"/>';
            svg += '</svg>';
        return svg;
    };

    or

    // creating HTML template
    diagram.flowShapes.customShape = function(config) {
        return `
            <section style="width:${config.width}px;
                height:${config.height}px; background: ${config.fill}"
    >
            <span style="font-size:${config.fontSize}px;
                color:${config.fontColor}"
    >${config.text}</span>
            </section>
        `
    };
  • Apply the template for the chosen shapes and prepare a data set for loading into Diagram. Check a detailed guide in the documentation >

New templates provide you with numerous options not only for adding brand new shapes but also for customizing the existing ones. For instance, you can equip org chart cards with icons, menu items, and any other custom elements required for your project:
Hospital org chartHospital org chart illustrating medical hierachy. Check the sample >

Combining Org Charts and Diagrams

And the cherry on the cake is that DHTMLX Diagram 2.2 enables you to mix flowchart and org chart shapes in one diagram by specifying particular types of shapes for each data item object:

// data to load
var data = [
    // the Org Chart shape
    {
        id: "1",
        text: "Chairman & CEO",
        title: "Henry Bennett",
        img: "../common/img/avatar-1.png",
    },
 
    // the Diagram shapes
    {
        id: "2",
        text: "Manager",
        type: "database",
        parent: "1"
    },
    {
        id: "3",
        text: "Technical Director",
        type: "process",
        parent: "1"
    },
    {
        id: "2.1",
        text: "Marketer",
        type: "database",
        parent: "2"
    },
    {
        id: "3.1",
        text: "Team Lead",
        type: "process",
        parent: "3"
    }
];
 
// initializing an org chart
var diagram = new dhx.Diagram("diagram", {
    type: "org",
    defaultShapeType: "img-card"
});
diagram.data.parse(data);

Read detailed instructions in the documentation >

Mixed org chartCheck the sample >

Export Diagrams to JSON from the Editor

Another novelty is the possibility to export your diagrams and org charts into the JSON format right from the editor. Our editors allow you to fine-tune diagrams and org charts on the fly via a simple and intuitive user interface. When you achieve the look and feel you need, you can export the result into the JSON format just in one click. After that, you are free to change our predefined shapes to custom ones using SVG and HTML templates, while preserving the structure and style of the whole diagram. Read more in the documentation >

DHTMLX Diagram 2.2 Round-Up

Summarizing the release news, here’s what you get with the updated Diagram 2.2:

We’re looking forward to receiving your feedback about the release of DHTMLX Diagram 2.2. Feel free to share your thoughts and ideas in the comments section below.

If you haven’t tried our Diagram library before, try it out during a free 30-day evaluation period.

We invite our current clients to visit their Client’s Area, where they can download the latest version 2.2.

The post DHTMLX Diagram 2.2: Build Any Type of JavaScript Diagrams and Org Charts with Custom Shapes appeared first on DHTMLX Blog.

How to Reorder Tasks in the Grid of JavaScript Gantt – DHTMLX Video Tutorial

$
0
0

While managing projects, users may face the need to change the order of tasks or move tasks between several Gantt projects. Today we’ll get acquainted with the ways of implementing this functionality in DHTMLX Gantt.

Our HTML5 Gantt provides two alternative ways of reordering tasks in the grid:

  • Via drag-and-drop
  • Via sorting

By default, both modes are disabled.

In order to enable the reordering of tasks by drag-n-drop, we need to set the order_branch option to ‘true’:

// ordering tasks only inside a branch
gantt.config.order_branch = true;

gantt.init("gantt_here");

The order_branch property activates the ‘branch’ mode that enables the reordering of tasks within the same nesting level.
JavaScript Gantt tasks reorderingCheck the sample >

Changing of the task position involves firing of the onBeforeTaskMove or onAfterTaskMove events; the first can be used to control where the task can be moved. To prevent moving to another sub-branch, use the onBeforeTaskMove event:

gantt.config.order_branch = true;
gantt.attachEvent("onBeforeTaskMove", function(id, parent, tindex){
    var task = gantt.getTask(id);
    if(task.parent != parent)
        return false;
    return true;
});
gantt.init("gantt_here");

Tasks reordering in JS GanttCheck the sample >
If your Gantt contains lots of tasks, the default mode of the branch reordering may slow down the performance. To speed it up, you can make use of the ‘marker’ mode:

gantt.config.order_branch = "marker";

In this mode, only the name of the task is reordered (on holding the left mouse key), and Gantt is re-rendered only when a task is dropped in the target position (on releasing the key):
Modes of task reordering - JS Gantt by DHTMLXCheck the sample >
Unlike the default mode, changing the task position doesn’t involve the firing of the onBeforeTaskMove or onAfterTaskMove events. To prevent dropping of a task in a particular position, we can use the onBeforeRowDragMove event instead. Note that it works only in the ‘marker’ mode:

// ordering tasks only inside a branch
gantt.config.order_branch = "marker";
gantt.attachEvent("onBeforeRowDragMove", function(id, parent, tindex){
        var task = gantt.getTask(id);
        if(task.parent != parent)
                return false;
        return true;
});
gantt.init("gantt_here");

Hope our tutorial turned out to be useful for you! If you’d like to experiment with DHTMLX Gantt yourself, download a free 30-day evaluation version.

Catch up with the previous tutorials from the series:

Subscribe to our YouTube channel to stay tuned: https://www.youtube.com/user/dhtmlx

The post How to Reorder Tasks in the Grid of JavaScript Gantt – DHTMLX Video Tutorial appeared first on DHTMLX Blog.

JavaScript/HTML5 Line & Spline Charts for Effective Forecasting

$
0
0

This article is a part of the series about DHTMLX JavaScript and HTML5 Charts – providing insights and best practices for the most popular graph types. Today, we’ll try to find out what a line chart is used for and what design tricks are needed to provide a better user experience.

Test our charting library during a 30-day free trial period.

JavaScirpt Line Chart by DHTMLX

A series of data points, joined by a line in a dot-to-dot fashion, can show startling results along its peaks and valleys. A simple line chart has the power to display the dynamic, highlight successes, and warn about potential dangers – all in seconds.

Horizontal line charts are primarily used for displaying behavior over a period of time: technology trends by a year, price dynamics over a quarter, website page visits per hour, and so on. In most cases, the way the data is trending allows predicting easily the results of data not yet recorded.

The time unit (years, months, days, etc.) is distributed evenly along the horizontal x-axis. The magnitude of each data element in the series is represented by its position on the vertical y-axis.

Specificities of a JavaScript Dynamic Line Chart

Dynamic Live Chart
Check the sample >

Dynamic or real-time charts are useful in displaying data that changes with time like a stock price, exchange rate, etc. These graphs are interactive, support animation and live updates.

Keys to Create a Simple JavaScript Line Chart
Consider Adding Data Comparison

It’s possible to include more than one line on the same axis. Thus, for instance, you can compare the number of tasks completed by each team for a certain period of time. Such a horizontal line graph depicts the totals with a separate line for a team.

However, if you’re building a multiple line chart, do not match too many data series. Graphs with more than 5 lines usually become cluttered and hard to understand.

Prefer Contrasting Colors for Multiple Lines

Users should not spend too much time trying to perceive your graph clearly. So when you draw a JavaScript line chart with multiple items, set clear contrasting colors. The color difference allows viewers to capture the aha moment quickly.

Simple Line Chart
Check the sample >

The palette you choose should be pleasing to look at. We recommend avoiding jarring and eyesore colors as well as variations of the same shade. If you have to build a JS line chart for a dashboard or business report, select a few brand colors harmonizing with each other.

Do Not Overwhelm Your JavaScript Line Chart with Text

When you add the text content, don’t be tempted to overcrowd the chart with too many symbols. There’s no need to mark every value on the x-axis and include all the data you have about the chart. Try to avoid bulky legends, paragraphs of texts, and multiple axis labels.

Line Chart Tooltip

Instead, you need readable titles and labels. The axis’ intervals have to be spaced evenly. Use special marks to label specific numbers that make sense for your datasets. Moreover, you can add tooltips to show the values when a user hovers over the data items.

Alternatives to a JS Horizontal Line Chart

We should note that line charts are not suitable for all kinds of data. For example, they fail in demonstrating percentages and proportions. Instead, consider choosing a pie chart. If you want to show how values differ in various categories or at the same time intervals, consider using JavaScript bar charts.

Differences Between a Line Graph and Spline Chart

Are you looking for a way to display changes over time that isn’t a line graph? Then you may experiment with a JavaScript/HTML5 spline chart. Line and spline charts are deeply related, the only difference is that the spline includes a fitted curve linking each data point in a series.

JavaScript Spline Chart by DHTMLX
Check the sample >

Why Choose DHTMLX JavaScript Visualization Library to Build a Line Chart

Our JavaScript charting library provides a simple and convenient way to integrate 10+ chart types into your web applications and interfaces. You can create Bar and X-Bar, Line and Spline, Area and Spline Area, Pie and Donut, Radar and Scatter graphs. Some of them have 3D variations.

Modern Design

DHTMLX follows the guidelines of a Material Design styling. We’ll help you build scalable web interfaces with a user-friendly look and feel.

Rich Configuration

A comprehensive DHTMLX Chart API allows configuring any element to achieve the desired appearance without a hitch. For instance, you can add multiple data items into your dynamic line chart. A new item will appear along the x-axis.

var config = {
    type:"line",
    scales: {
        "bottom" : {
            text: "text",
            showText: false
        },
        "left" : {
            maxTicks: 10,
            max: 100,
            min: 0
        }
    },
    series: [
        {
            value: "value",
            color: "#5E83BA",
            strokeWidth: 2
        }
    ]
};
 
var chart = new dhx.Chart("chart", config);
chart.data.parse([
    {
        value: Math.random() * 100,
        text: "u" + Date.now() + 1
    },
    {
        value: Math.random() * 100,
        text: "u" + Date.now() + 2
    },
    {
        value: Math.random() * 100,
        text: "u" + Date.now() + 3
    }
]);
function add() {
    chart.data.add({
        value: Math.random() * 100,
        text: "u" + Date.now()
    });
};

You can enable a legend and define its position. Indeed it should be available if your goal is to display more than one data series. The legend will provide information about the tracked data to help your users translate the graph.

var chart = new dhx.Chart("chart_container",{
    scales: {
        // scales config
    },
    series: [
        // list of series
    ],
    legend: {
        series: ["A", "B", "C"],
        valign: "top",
        halign: "right"
    }    
});

The API allows configuring a scale and setting a title for it. Besides, you can add a threshold line at any defined level to look for the particular value.

var chart = new dhx.Chart("chart_container",{
    type:"line",
    scales: {
        "bottom" : {
            text: 'month'
        },
        "left" : {
            padding: 10,
            max: 90
        }
    },
    series: [
        {
           value: 'company A',
           strokeWidth: 2
           // more options  
        }
    ]
});

Plus, our users can set maximum points to show an average number of values if your data is too large to display all the values in the chart.

var chart = new dhx.Chart("chart", {
    type:"line",
    maxPoints:100
});

Check the sample >

Simple Customization

DHTMLX Charting library lets you modify several aspects of the chart’s appearance. You can set the type of the point of the data item (circle, triangle, rectangular or rhombus state) and define its color. Series lines can be repainted and dashed. Moreover, developers can add new CSS classes in case they need specific options.

Conclusion

A line chart is a powerful data visualization tool for many different areas, including finance, marketing, and project management. It is extremely effective for monitoring trends over a certain period of time and making predictions. If two or more lines are on the graph, it can be used as a comparison between them.

DHTMLX Chart component is a part of the Suite UI library. You can download a dhtmlxChart free trial version as well as estimate a complete Suite kit with 20+ UI widgets included.

Our advanced solutions allow building rich web interfaces that are compatible with all modern browsers. Plus, we offer examples of smooth integration into applications based on React, Angular, and Vue.JS.

Access our documentation to get more information about dhtmlxChart features.

If you have questions for our team or want to share your opinion, do not hesitate to contact us.

The post JavaScript/HTML5 Line & Spline Charts for Effective Forecasting appeared first on DHTMLX Blog.

DHTMLX Suite 6.3 Introducing Grid Keyboard Navigation, Custom HTML Content in DHTMLX Components, and AJAX Helper

$
0
0

Our aspiring JS library of UI components has received a new update 6.3 with essential UX enhancements and deeper UI customization. From now on, end users can handily navigate through Grid cells with the help of keyboard shortcuts. Developers can create any kind of custom HTML content inside DHTMLX Grid, TreeGrid, Menu, Ribbon, Toolbar, and Sidebar components. Besides, the library obtains an AJAX helper for creating asynchronous web apps on the fly.

Get down to testing a new version 6.3 free of charge for 30 days >

Grid and TreeGrid Updated
Keyboard Navigation in Grid

V6.3 delivers a convenient set of keyboard shortcuts for navigating data in Grid. Due to a wide variety of shortcut keys, developers can greatly speed up the work with huge data tables. The default set of shortcuts enables users to scroll the grid up and down as well as navigate to the beginning or end of the data table, while the selected cell remains unchanged.

If needed, developers can quickly disable the default keyboard navigation:

var grid = new dhx.Grid("grid", {
    columns: [// columns config],
    data: dataset,
    keyNavigation: false
});

Additionally, the selection property enables developers to make the selection of cells possible for end users with the help of shortcut keys:
Grid keyboard navigationCheck the sample >

var grid = new dhx.Grid("grid", {
    columns: [// columns config],
    data: dataset,
    selection: "complex",
    keyNavigation: true // true - by default
});

Shortcut Keys - DHTMLX GridCheck the sample >

Besides, developers have broadened keyboard navigation in Grid to provide end users with shortcut keys for editing the content of cells. The Enter key opens an editor and allows saving changes, while the Esc key closes an editor without saving changes. To enable this feature, you need to set the editing property in the configuration object of Grid to true:

var grid = new dhx.Grid("grid", {
    columns: [// columns config],
    data: dataset,
    selection: "complex",
    editing: true,
    keyNavigation: true // true - by default
});

Key shortcuts for editing DHTMLX GridCheck the sample >

Custom HTML Content in Grid and TreeGrid

More customization opportunities have come with v6.3. The update brings out the ability to add any custom HTML content into the cells of Grid and TreeGrid right in the dataset. You can choose whether to use custom HTML elements either in all columns or only in particular columns of your data table.

For instance, in order to display countries’ flags together with their names in the first column of Grid, you need to specify the path to an image of the flag in the dataset and apply the htmlEnable: true configuration property:

var dataset = [
    {
        "country": "<span>China</span><img src='../flags/cn.jpg' />",
        "id": "1"
    }
];
 
var grid = new dhx.Grid("grid", {
    columns: [
        {
            width: 200, id: "country", header: [{ text: "Country" }],
            htmlEnable: true
        },
        {
            width: 150, id: "urban", header: [{ text: "Urban Pop" }]
        },
        // more columns
    ],
    data: dataset
});

Custom HTML content in DHTMLX GridCheck the sample >

Menu, Ribbon, Sidebar, and Toolbar Updated
Custom HTML Content

There is no limit to customization possibilities of your web apps with DHTMLX. V6.3 rolls out the ability to equip DHTMLX navigation components (Menu, Toolbar, Ribbon, and Sidebar) with any kind of custom content you might need to see in your apps. It’s possible to add a custom element like an image, icon, or other HTML content into the component itself or into its controls:
Custom uploader in DHTMLX RibbonUploader inside the Ribbon component. Check the sample >

The add method makes it easy to add custom content to the component – DHTMLX Ribbon in the first example above:

ribbon.data.add({
    type: "customHTML",
    html: "<div id='preloader'><div id='loader'></div></div >"
});

Meanwhile, the html property allows displaying custom content inside a control – for example, showing the uploader in the Progress button of DHTMLX Ribbon:

{
    type: "block",
    title: "Progress",
    items: [
        {
            html: "<div id='preloader'><div id='loader'></div></div >",
            size: "auto"
        }
    ]
};

Adding HTML content into controls of DHTMLX RibbonCheck the sample >

The same principle applies to other navigation components: Menu, Toolbar, and Sidebar.
Custom HTML content in DHTMLX MenuMenu items with custom icons. Check the sample >

Charts Updated

Minor enhancements have been made to DHTMLX Charts. From now on, you can fine-tune your charts and equip bars and pie slices with formatted data labels via the showTextTemplate property. Thus, your bar charts can include not only values but also currency symbols (or any other symbols), for instance:
Formatted labels in DHTMLX chartsCheck the sample >

AJAX Helper

In addition to new features and improvements, DHTMLX developers have prepared the AJAX helper at the request of our clients. It works smoothly with DHTMLX components and allows them to exchange data with a web server without reloading the page. The helper makes use of the dhx.ajax object with four common methods: delete, get, post, and put.

Other Updates
Calendar API Enlarged

The Calendar component is much more developer-friendly now, as we have included a range of new events for listening to user actions (cancelClick, modeChange, monthSelected, yearSelected) as well as the getCurrentMode() method for determining what the component is currently displaying: calendar, month, year, or time picker.

Manipulating Nodes in Tree and TreeGrid

Starting with v6.3, developers can collapse and expand all nodes of DHTMLX Tree and TreeGrid at once with the help of a couple of simple methods: collapseAll and expandAll. Check the sample >

CSS Measurement Units in List and DataView

In DHTMLX List and DataView developers can set the height of items (as well as of the whole component) not only as a number but also as a string value in any CSS measurement unit: px, %, em, whatnot. For instance, define the height of the list item as 30px:

// sets the height of an item as a string value
var list = new dhx.List("list_container", {
    itemHeight:"30px"
});

We do hope our December update will contribute to the efficient development of your web apps with DHTMLX. Please leave us your feedback in the comments section below.

We invite our current clients to download the latest version in their Client’s Area.

If you’re new to the DHTMLX UI components library, feel free to download and test the trial version 6.3.

Related Materials:

The post DHTMLX Suite 6.3 Introducing Grid Keyboard Navigation, Custom HTML Content in DHTMLX Components, and AJAX Helper appeared first on DHTMLX Blog.


DHTMLX Maintenance Release: Gantt 6.3.2, Scheduler 5.3.4, Scheduler.Net 4.0.2

$
0
0

The last significant updates of 2019 have already been delivered. DHTMLX Gantt released v6.3 with decimal durations of tasks, MS Project-like link formatting, and smart rendering update. The diagramming library acquired new customization possibilities. The Suite UI library rolled out keyboard navigation in Grid and custom HTML content in data and navigation components.

However, the development of JavaScript libraries never stops. The holiday season is the right time to polish the code and bring the components to perfection. So, meet the latest maintenance releases of November and December 2019.

DHTMLX Gantt

6.3.1 (November 29, 2019)

  • (Fixed) the regression in the smart rendering, which caused links not to be rendered in some cases
  • (Fixed) the bug that allowed modifying and creating new tasks with keyboard navigation when the read-only mode is activated
  • (Fixed) the display issue with Fullscreen extension, which allowed some page elements to be displayed over the Gantt in the fullscreen mode
  • (Fixed) the bug that caused the drag-timeline extension to reset the value of the readonly config

6.3.2 (December 10, 2019)

  • (Fixed) the script error, which happened when gantt.destructor was called when the click-drag feature was enabled
  • (Fixed) gantt.parse no longer modifies data objects passed into arguments, deep copies are made instead
  • (Updated) TypeScript type definitions were updated
  • (Updated) onBeforeBranchLoading and onAfterBranchLoading public events were added, so it would be possible to modify the URL or dynamic parameters of dynamic loading requests
  • (Updated) public method for changing the URL of the dataProcessor after its initialization

Learn more in the documentation >

DHTMLX Scheduler

5.3.4 (December 10, 2019)

  • (Fixed) the incorrect work of the vertical scroll in a scrollable timeline when the mouse pointer is over the sections column
  • (Fixed) the incorrect serialization of nested objects by the dataProcessor
  • (Fixed) the script error, which fired when creating a new event using a custom lightbox

Learn more in the documentation >

DHTMLX Scheduler.Net

4.0.2 (December 10, 2019)

  • (Updated) JS part updated to catch up with the latest DHTMLX JS Scheduler version
  • (Updated) Target.net framework updated from 4.0 to 4.5.2
  • (Updated) added ColumnWidth property to C# TimelineView class

Download the latest versions of our libraries and test them free of charge for 30 days:

Current clients may find the updated packages in their Client’s Area.

The post DHTMLX Maintenance Release: Gantt 6.3.2, Scheduler 5.3.4, Scheduler.Net 4.0.2 appeared first on DHTMLX Blog.

DHTMLX Suite 6.4: Grid and List Lazy Loading, Enhanced Multiselection and Sorting, Significantly Enlarged Suite API

$
0
0

We start the year 2020 with the new release of DHTMLX UI library – Suite 6.4. The update encompasses the most sought-after features boosting the performance of all JavaScript UI components.

The highlight of the release is the lazy loading of data in Grid and List, which accelerates data processing and saves you time and resources. Among other highly demanded features delivered in v6.4 are sorting operations in Grid and TreeGrid, advanced multiselection of Grid rows and cells, ability to disable an entire form or some of its controls, deeper customization of Charts, attaching Window to a custom node, and manipulating separate tabs in Tabbar.

However, that’s not all – read more in the release article and download Suite trial version 6.4 for testing the updated components for free for 30 days!

DHTMLX Grid Updated
Grid Lazy Loading [PRO]

Our JS data table component DHTMLX Grid is reinforced with lazy loading of data, which allows steadily adding data piece by piece for rendering records in the visible area of the Grid. Such dynamic loading reduces the amount of time and resources allocated for data processing and makes it smooth and speedy.
Lazy loading is enabled via the LazyDataProxy helper:

new dhx.LazyDataProxy("https://docs.dhtmlx.com/suite/backend/lazyload", {
    limit: 30,
    prepare: 5,
    delay: 150,
    from: 0
});

The parameters of its object constructor allow you to define the URL where data should be loaded and some other optional settings such as a limit of records and delay time for dynamic loading. Learn more about lazy loading in Grid >

After the LazyDataProxy initialization, you only have to call the load method and pass the lazyDataProxy as a parameter:

var grid = new dhx.Grid("grid_container");
grid.data.load(lazyDataProxy);

Check the sample >

Now, you’ll be all set for efficient data processing with DHTMLX Grid!

Multiselection of Grid Cells and Rows

DHTMLX Grid Multiselection
V6.4 introduces the ability to select multiple cells and rows in DHTMLX Grid. With the help of Ctrl and Shift shortcuts, end users can select random cells and rows situated in any order or an entire range of cells or rows.

For example, that’s how we turn on the multiselection of rows by setting the multiselection property to true and specifying the selection property to “row”:

var grid = new dhx.Grid("grid_container", {
    columns: [// columns config],
    multiselection:true,
    selection:"row",
    data: dataset
});

Row Multiselection in DHTMLX GridCheck the sample >

Besides the ability to switch on the multiselection functionality for end users, developers can manipulate the selection of Grid cells and rows on their own via the API.

The setCell() method allows defining which cells to select. Here we set up the the multiselection of one cell in the Yearly Change column and two cells in the Net Change column. By specifying the ctrlUp: true and shiftUp: false parameters we determine that it’s possible to select only separate cells, not ranges:

grid.selection.setCell(grid.data.getId(0),"yearlyChange");
grid.selection.setCell(grid.data.getId(1),"netChange", true, false);
grid.selection.setCell(grid.data.getId(3),"netChange", true, false);

Сell multiselection in DHTMLX Grid

Grid and TreeGrid Updated
Sorting Operations

From now on, you are free to choose which columns should be sortable in DHTMLX Grid and TreeGrid. In order to enable sorting of particular columns you need to specify the sortable: true property in their configuration while setting sortable: false in the configuration of Grid (or TreeGrid) to disable sorting in the rest of columns.

In the example below only the columns with countries and density can be sorted:

var grid = new dhx.Grid("grid_container", {
    columns: [
        { width: 200, id: "country", header: [{ text: "Country" }], sortable: true },
        { width: 150, id: "land", header: [{ text: "Land" }] },
        { width: 150, id: "density", header: [{ text: "Density" }], sortable: true }
    ],
    data: dataset,
    sortable: false,    
});

Sorting columns in DHTMLX GridCheck the sample >

Additionally, the new getSortingState method gives you an opportunity to receive the id of the column, by which Grid (or TreeGrid) is sorted, as well as the order of sorting (ascending or descending).

Adjusting Columns’ Width

Both Grid and TreeGrid obtain a new ability to adjust the width of their columns to the size of the entire table using the autoWidth configuration option:

var grid = new dhx.Grid("grid_container", {
    columns: [// columns config],
    autoWidth:true,
    data: dataset
});

If needed, it’s possible to change the width of a specific column to match the size of its content (cells or headers) automatically with the help of the adjust property:

var grid = new dhx.Grid("grid_container", {
    columns: [
        { id: "country", header: [{ text: "Country" }], adjust: "data" },
        { id: "population", header: [{ text: "Population" }] }
    ],
    adjust: false,
    data: dataset
});

As shown in the data table below, the width of all columns is adjusted to the width of Grid, however, the first column matches the width of its cell content:
Adjusting columns' width in DHTMLX GridCheck the sample >

In addition to the new functionality described above, now DHTMLX Grid and TreeGrid components allow developers to verify if a column is displayed or hidden via the isColumnHidden method. Grid keyboard shortcuts are also enlarged with new combinations for navigating Grid cells and changing the selection of cells simultaneously:

DHTMLX Grid keyboard navigationCheck the sample >

Charts Updated

Our appealing JS charting library acquires more flexibility in v6.4. New features include the ability to rotate scale labels and data labels inside bar and X-bar charts and use up to four axes (two vertical and two horizontal).

Rotate scale labels in DHTMLX chartsCheck the sample >

Rotate data labels in DHTMLX bar chartsCheck the sample >

Apart from that, we added a new event for tracking clicks on data series serieClick.

Form Updated

Starting with v6.4, developers can disable an entire form or its elements, so that end users won’t be able to interact with them. For that purpose, you just need to add the disabled: true property in the configuration of the form:

var form = new dhx.Form("form_container", {
    css: "dhx_widget--bordered",
    disabled: true
});

For instance, in order to disable a button control of the form, you need to apply the disable() method of the object returned by the getItem() method:

form.getItem("button_id").disable();

DHTMLX Form control disabledCheck the sample >

Tabbar Updated

Now working with DHTMLX tabbar becomes more convenient, as a new range of methods lets developers manipulate not only the entire tab bar but also separate tabs. For instance, here is how we can disable one of the tabs in DHTMLX Tabbar with the help of the disableTab() method:

tabbar.disableTab("London");
// -> true|false

DHTMLX tabbarCheck the sample >

Following the same logic, you can equip particular tabs with the close button by specifying the ids of the chosen tabs in the closable property:

var tabbar = new dhx.Tabbar("tabbar", {
    closable: ["paris", "london"]
});
Window Updated

The release brings out the ability to attach DHTMLX window to a custom node instead of the body of the page. It’s possible due to the node property, where you can specify the container for your window:

var dhxWindow = new dhx.Window({
    node:"customDiv"
});

Check the sample >

Other Updates

In the release article, we’ve described the most-awaited features of the Suite UI library 6.4. However, the update rolled out many other useful improvements:

  • Calendar and TimePicker: the new clear method
  • ColorPicker: the ability to specify the palette or picker mode of the component; the clear method
  • ComboBox: data object; specifying the label position; events updated
  • DataView: events and multiselection updated
  • Layout: expanding and collapsing Layout cells; events and methods updated
  • List: lazy loading [PRO]
  • Menu, Ribbon, Sidebar, Toolbar: checking if an item is disabled; methods and events updated
  • Slider: checking if the slider is disabled; defigning the label position of slider.

You can get acquainted with the full list of updates 6.4 in the documentation.

Try out all the new features – download the DHTMLX Suite 6.4 trial version (free for 30 days).

We invite our current clients to get the latest version of our UI library in their Client’s Area.

Looking forward to your feedback!

Related Materials:

The post DHTMLX Suite 6.4: Grid and List Lazy Loading, Enhanced Multiselection and Sorting, Significantly Enlarged Suite API appeared first on DHTMLX Blog.

How to Use DHTMLX Gantt with Vue.js Framework [Demo]

$
0
0

Firstly published on May 11, 2017. Updated on January 30, 2020

What’s extremely awesome about our Gantt Chart library (besides fast performance and vast variety of features) is that it allows integrations with almost all new and popular frameworks and technologies. And today we’ll show you the easiest way to use js gantt chart with Vue.js, progressive JavaScript framework.

So, follow the instructions below to create a Vue.js Gantt chart or jump to a complete demo on GitHub right away.

New to dhtmlxGantt? Learn more about the library now

How We Start

The first thing we need to do is to get an app skeleton. And for this, we’re going to use vue-cli. If you don’t have one, you can get it with the node package manager using command (npm install -g @vue/cli). See this article.

To create an app, run the following command:

vue create gantt-vue

It will request some project info. You can just leave default answers and press the enter button for each question or select functions manually.

Then you need to go to the app directory, install dependencies and run it.

cd gantt-vue

If you use yarn, you need to call the following commands:

yarn install
yarn serve

If you use npm, you need to call the following commands:

npm install
npm run dev

After these steps, the app should run on http://localhost:8080

vuejs-install

Moving to Gantt Chart Part

Now we should get the dhtmlxGantt code. To do so, run the following command:

yarn add dhtmlx-gantt --save (for yarn)
npm install dhtmlx-gantt --save (for npm)

Then, to add a Gantt chart to an application, we should create a component.

So, we’ll start by creating a folder for the app components. Open the src folder and create components folder in it. Then, create Gantt.vue file in the components folder and put the following code into it:

{{ src/components/Gantt.vue }}
<template>
  <div ref="gantt"></div>
</template>
 
<script>
import 'dhtmlx-gantt'
export default {
  name: 'gantt',
  props: {
    tasks: {
      type: Object,
      default () {
        return {data: [], links: []}
      }
    }
  },
 
  mounted: function () {
    gantt.config.xml_date = "%Y-%m-%d";
 
    gantt.init(this.$refs.gantt);
    gantt.parse(this.$props.tasks);
  }
}
</script>
 
<style>
    @import "~dhtmlx-gantt/codebase/dhtmlxgantt.css";
</style>

Now, the Gantt chart component is ready. When the element will be added to the page it will initialize the Gantt chart under “gantt” ref. Then, Gantt chart will load data from the tasks property.

And now it’s time to add the component to our app.

Open App.vue and add the following code instead of the one we’ve already had there.

{{ src/App.vue }}
<template>
  <div class="container">
    <gantt class="left-container" :tasks="tasks"></gantt>
  </div>
</template>
 
<script>
import Gantt from './components/Gantt.vue';
 
export default {
  name: 'app',
  components: {Gantt},
  data () {
    return {
      tasks: {
        data: [
          {id: 1, text: 'Task #1', start_date: '2020-01-17', duration: 3, progress: 0.6},
          {id: 2, text: 'Task #2', start_date: '2020-01-20', duration: 3, progress: 0.4}
        ],
        links: [
          {id: 1, source: 1, target: 2, type: '0'}
        ]
      },
    }
  }
}
</script>

Now, we should see the Gantt chart with predefined tasks on a page.

gantt-vue

Listening changes and handling events

Let’s say we need to trace changes in Gantt made by the user and process them somehow – show the details of the selected item in a separate form, keep data model of the parent component up to date, or send these changes to the backend. In other words, we need a way to let the rest of the app know what happens inside Gantt.

To do so we can create a DataProcessor with a custom router object, where the router is a function and $emit DataProcessor events to the parent component.

As a simple demonstration, let’s implement a ‘changelog’ feature – we’ll write all changes made in Gantt in a neat list somewhere on the page.

Firstly, go into the Gantt component and add code that will trace and emit changes of dhtmlxGantt. Add the following code right after the gantt.init call:

   {{ src/components/Gantt.vue }}  
gantt.createDataProcessor((entity, action, data, id) => {
      this.$emit(`${entity}-updated`, id, action, data);
   });

It adds handlers to the add/update/delete events for the links and tasks. If some particular handler is called, it will trigger vue event on our component with parameters.

The next step is to add listeners for these events into the app component and write a log of actions in another div.

Let’s extend the app component with the required functionality:

{{ src/App.vue }}
import Gantt from './components/Gantt.vue';
 
export default {
  name: 'app',
  components: {Gantt},
  data () {
    return {
      tasks: {
        data: [
          {id: 1, text: 'Task #1', start_date: '2020-01-17', duration: 3, progress: 0.6},
          {id: 2, text: 'Task #2', start_date: '2020-01-20', duration: 3, progress: 0.4}
        ],
        links: [
          {id: 1, source: 1, target: 2, type: '0'}
        ]
      }
    }
  },
  methods: {
    addMessage (message) {
      this.messages.unshift(message)
      if (this.messages.length > 40) {
        this.messages.pop()
      }
    },
 
    logTaskUpdate (id, mode, task) {
      let text = (task && task.text ? ` (${task.text})`: '')
      let message = `Task ${mode}: ${id} ${text}`
      this.addMessage(message)
    },
 
    logLinkUpdate (id, mode, link) {
      let message = `Link ${mode}: ${id}`
      if (link) {
        message += ` ( source: ${link.source}, target: ${link.target} )`
      }
      this.addMessage(message)
    }
  }
}

What you can see here – we’ve added an array property where we’re going to store log entries, a method that adds a new message to the top of that array (our log will show new entries first). Also, we’ve added two more methods that will create log messages for actions done with tasks and links and add them to the message stack.

And finally, update a template of the app component to utilize these functions:

{{ src/App.vue }}
<template>
  <div class="container">
    <div class="right-container">
      <ul class="gantt-messages">
        <li class="gantt-message" v-for="message in messages">{{message}}</li>
      </ul>
    </div>
    <gantt class="left-container" :tasks="tasks" @task-updated="logTaskUpdate" @link-updated="logLinkUpdate"></gantt>
  </div>
</template>

We’ve added a simple two-column layout, attached our log handlers to the Gantt events that we emit from the Gantt module, added a container for log messages and bound them to our log messages stack.

Now, if we make some changes to Gantt, messages should be shown on the right side.

vuejs-gantt-chart

If you want to display some info about the selected tasks, proceed to the instructions below.

To show information about selected tasks, we can capture API events of DHTMLX Gantt (‘onTaskSelected‘) and $emit them to the parent component. We can also use the ‘onTaskIdChange‘ event to update information after changing the task id.

Open the Gantt chart component and add the following code right before gantt.init call:

{{ src/components/Gantt.vue }}      
gantt.attachEvent('onTaskSelected', (id) => {
      let task = gantt.getTask(id);
      this.$emit('task-selected', task);
});
 
    gantt.attachEvent('onTaskIdChange', (id, new_id) => {
       if (gantt.getSelectedId() == new_id) {
         let task = gantt.getTask(new_id);
         this.$emit('task-selected', task);
        }
     });

Here we’ve added the onTaskSelected handler that is going to trigger a ‘task-selected’ event.

Open the app component to add a selection handler to it. We need to add some necessary elements to our template as well. It should look like this:

{{ src/App.vue }}
<template>
  <div class="container">
    <div class="right-container">
      <div class="gantt-selected-info">
        <div v-if="selectedTask">
          <h2>{{selectedTask.text}}</h2>
          <span><b>ID: </b>{{selectedTask.id}}</span><br/>
          <span><b>Progress: </b>{{selectedTask.progress|toPercent}}%</span><br/>
          <span><b>Start Date: </b>{{selectedTask.start_date|niceDate}}</span><br/>
          <span><b>End Date: </b>{{selectedTask.end_date|niceDate}}</span><br/>
        </div>
        <div v-else class="select-task-prompt">
          <h2>Click any task</h2>
        </div>
      </div>
      <ul class="gantt-messages">
        <li class="gantt-message" v-for="message in messages">{{message}}</li>
      </ul>
    </div>
    <gantt class="left-container" :tasks="tasks" @task-updated="logTaskUpdate" @link-updated="logLinkUpdate" @task-selected="selectTask"></gantt>
  </div>
</template>

Here we’ve added another container, which is bound to the selectedTask property of the app component using “v-if” directive. Besides, we’ve added a handler for the “task-selected” event we now emit.

Make sure to add this property to the app component:

   {{ src/App.vue }}    
   selectedTask: null

And add the selectTask method, which is used in the handler we’ve defined above:

    {{ src/App.vue }}    
    selectTask: function(task){
      this.selectedTask = task
    }

Thus, each time a user selects a task inside Gantt, the component emits the ‘task-selected’ event. Then this event is captured by the app component. Inside the event handler, we update the selectedTask property, which in its turn invokes a repaint of the .gantt-selected-info element with task details.

Note that the task object has the start_date/end_date properties of Date type and progress completion in float type – these should be formatted in a human-friendly form before being added to the page.

It’s implemented using toPercent and niceDate filters, which we define like this:

{{ src/App.vue }}  
filters: {
    toPercent (val) {
      if(!val) return '0'
      return Math.round((+val) * 100)
    },
    niceDate (obj){
      return '${obj.getFullYear()} / ${obj.getMonth()} / ${obj.getDate()}'
    }
  }

Now, if we run our app and select a task, we should see that its info is shown on the right.

Gantt-chart-vuejs

So, we’ve created a simple Gantt chart with the help of DHTMLX Gantt and Vue.js. The results of our work can be found on GitHub. If you follow the instructions above and meet any difficulties, don’t hesitate to share them with us.

Which technologies/frameworks are you using?

We need your feedback to provide the right integrations at the right time. Please leave your requests here:

Thank you in advance and stay tuned for new tutorials!

The post How to Use DHTMLX Gantt with Vue.js Framework [Demo] appeared first on DHTMLX Blog.

How to Use DHTMLX Scheduler with Vue.js Framework [Demo]

$
0
0

Great news for Vue.js lovers! Our dev team prepared a thorough guide on how to integrate our high-performing JS event calendar component – DHTMLX Scheduler – with the progressive JavaScript framework Vue.js.

So, below is a step-by-step tutorial for creating a Vue Scheduler component with code snippets and illustrations. You can also kick-start the development process with a complete demo on GitHub.

New to DHTMLX Scheduler? Learn more about the library now >

1. How to Start

Firstly, we need to create an app skeleton. For this purpose, we’re going to use vue-cli. If you don’t have one, you can easily install it with the node package manager using command (npm install -g @vue/cli). Check this article >

In order to use yarn in a project, it must be installed globally in the system (npm install -g yarn).

So, let’s run the next command to create an app:

vue create scheduler-vue

It will request you to provide project information. You can choose to leave the default answers and press Enter for each question or select functions manually.

The next step is to go to the app directory, install dependencies and run your Vue.js app:

cd scheduler-vue

For using yarn call:

yarn install
yarn serve

For using npm call:

npm install
npm run dev

Here we go – your app now runs on: http://localhost:8080

vuejs-install

2. Moving to Scheduler Part

At this point, we need to get the code of DHTMLX Scheduler – let’s run the command:

yarn add dhtmlx-scheduler --save (for yarn)
npm install dhtmlx-scheduler --save (for npm)

As we want to add DHTMLX Scheduler to our app, we have to create a component. Firstly, we’ll create a folder for the app components – open the src folder and create the components folder in it. After that, create Scheduler.vue file in the components folder and add the next lines of code into it:

{{ src/components/Scheduler.vue }}
<template>
  <div ref="scheduler"></div>
</template>
 
<script>
import 'dhtmlx-scheduler'
export default {
  name: 'scheduler',
  props: {
    events: {
      type: Array,
      default () {
        return {events: []}
      }
    }
  },
 
  mounted: function () {
    scheduler.skin = "material";
    scheduler.config.header = [
        "day",
        "week",
        "month",
        "date",
        "prev",
        "today",
        "next"
    ];
 
    scheduler.init(this.$refs.scheduler, new Date(2020, 0, 20), "week");
    scheduler.parse(this.$props.events);
  }
}
</script>
 
<style>
    @import "~dhtmlx-scheduler/codebase/dhtmlxscheduler_material.css";
</style>

Congrats! We’re done with the Scheduler component. When the element will be added to the page, it will initialize Scheduler under “scheduler” ref. Afterward, Scheduler will load data from the events property.

Right now we need to finally add the component to our Vue.js application. Open App.vue and replace the code we’ve already had there with the next lines:

{{ src/App.vue }}
<template>
  <div class="container">
    <scheduler class="left-container" :events="events"></scheduler>
  </div>
</template>
 
<script>
import Scheduler from './components/Scheduler.vue';
 
export default {
  name: 'app',
  components: {Scheduler},
  data () {
    return {
      events: [
        { id:1, start_date:"2020-01-20 6:00", end_date:"2020-01-20 15:00", text:"Event 1"},
        { id:2, start_date:"2020-01-23 6:00", end_date:"2020-01-23 20:00", text:"Event 2"}
      ]
    }
  }
}
</script>
 
<style>
  html, body {
    height: 100%;
    margin: 0;
    padding: 0;
  }
 
  .container {
    height: 100%;
    width: 100%;
  }
 
  .left-container {
    overflow: hidden;
    position: relative;
    height: 100vh;
  }
 
</style>

Once you are done, you will see DHTMLX Scheduler with predefined events on the page looking like that:

Basic Vue Scheduler component

3. Listening to changes and handling events

Suppose we need to track and process changes made by users in our Scheduler – for example, show details of selected events in a separate form, update the data model of the parent component or send these changes to the backend. Simply put, we need our app to be aware of what’s going on inside Scheduler.

For that purpose, we can capture API events of DHTMLX Scheduler and $emit them to the parent component.

To make it clearer, let’s see how to create a simple changelog noting down all the changes made in Scheduler in a neat list on the right side of the page.

At first, you should go into the Scheduler component and place the code that will trace and emit Scheduler changes just before calling scheduler.init:

  {{ src/components/Scheduler.vue }}  
        scheduler.attachEvent("onEventAdded", (id, ev) => {
            this.$emit("event-updated", id, "inserted", ev);
        });
        scheduler.attachEvent("onEventChanged", (id, ev) => {
            this.$emit("event-updated", id, "updated", ev);
        });
        scheduler.attachEvent("onEventDeleted", (id, ev) => {
            this.$emit("event-updated", id, "deleted");
        });

What this code does is add handlers to the create/update/delete events of DHTMLX Scheduler. If some particular handler is called, it will trigger the Vue event on our component with parameters.

Secondly, you need to attach event listeners to the app component and write a log of actions in another div. Let’s do it this way:

{{ src/App.vue }}
<script>
import Scheduler from './components/Scheduler.vue';
 
export default {
  name: 'app',
  components: {Scheduler},
  data () {
    return {
      events: [
        { id:1, start_date:"2020-01-20 6:00", end_date:"2020-01-20 15:00", text:"Event 1"},
        { id:2, start_date:"2020-01-23 6:00", end_date:"2020-01-23 20:00", text:"Event 2"}
      ],
      messages: []
    }
  },
  methods: {
    addMessage (message) {
      this.messages.unshift(message)
      if (this.messages.length > 40) {
        this.messages.pop()
      }
    },
 
    logEventUpdate (id, mode, ev) {
      let text = (ev && ev.text ? ` (${ev.text})`: '')
      let message = `Event ${mode}: ${id} ${text}`
      this.addMessage(message)
    },
  }
}
</script>
 
<style>
  html, body {
    height: 100%;
    margin: 0;
    padding: 0;
  }
 
  .container {
    height: 100%;
    width: 100%;
  }
 
  .left-container {
    overflow: hidden;
    position: relative;
    height: 100vh;
    display: inline-block;
    width: 82vw;
  }
 
  .right-container {
    border-right: 1px solid #cecece;
    float: right;
    height: 100%;
    width: 340px;
    box-shadow: 0 0 5px 2px #aaa;
    position: relative;
    z-index:2;
  }
 
.scheduler-messages {
    list-style-type: none;
    height: 50%;
    margin: 0;
    overflow-x: hidden;
    overflow-y: auto;
    padding-left: 5px;
  }
 
  .scheduler-messages > .scheduler-message {
    background-color: #f4f4f4;
    box-shadow:inset 5px 0 #d69000;
    font-family: Geneva, Arial, Helvetica, sans-serif;
    font-size: 14px;
    margin: 5px 0;
    padding: 8px 0 8px 10px;
  }
</style>

With this code we have equipped our app component with:

  • the array property for storing log entries;
  • method for adding a new message on top of our array so that new entries can be displayed first in our log;
  • two more methods for creating log messages for the actions performed with tasks and links and for adding them to the message stack.

All what’s left to do now is update the template of the app component to apply these functions:

{{ src/App.vue }}
<template>
  <div class="container">
    <scheduler class="left-container" :events="events" @event-updated="logEventUpdate"></scheduler>
    <div class="right-container">
      <ul class="scheduler-messages">
        <li class="scheduler-message" v-for="message in messages">{{message}}</li>
      </ul>
    </div>
  </div>
</template>

There you are!

Summing up our step-by-step guide, here we’ve created a simple two-column layout of DHTMLX Scheduler, attached our log handlers to the Scheduler events that we emit from the Scheduler module, added a container for log messages and bound them to our log messages stack.

Just to check everything works fine, try to make some changes to DHTMLX Scheduler – messages should be displayed on the right side:
Event listeners in Vue Scheduler component

These were three steps for creating a simple Vue Event/Booking Calendar with DHTMLX. The demo application can be found in our GitHub repository.

If you follow the instructions above and face any difficulties, share them with us!

What Else You Can Do:

The post How to Use DHTMLX Scheduler with Vue.js Framework [Demo] appeared first on DHTMLX Blog.

DHTMLX Maintenance Release: Gantt 6.3.7, Scheduler 5.3.5, Suite 6.4.1, Diagram 2.2.1, and Pivot 1.4.1

$
0
0

Kick-start your web app development with our sophisticated JavaScript libraries and catch up with the recent updates of all our major components in 2020: Gantt chart, Scheduler, Suite UI library, Diagram library, and Pivot table.

Here is a list of the latest maintenance updates delivered by our dev team:

DHTMLX Gantt 6.3.4 – 6.3.7

6.3.4 (December 27, 2019)

  • (Fixed) crashes of the resource load diagram when smart rendering is switched off
  • (Fixed) the issue with the custom task property named “unit”, as Gantt considered it as a duration unit value and multiplied the task duration after its dragging
  • (Fixed) the incorrect Tooltip position when the autosize config is enabled
  • (Fixed) the incorrect alignment behavior of grid cells when both the scrollable property and autofit config are set to true
  • (Fixed) the issue with the auto-scheduling extension that caused Gantt to freeze when a task has the constraint type (SNET/FNET/SNLT/FNLT) with no date specified, or with an invalid date
  • (Updated) creating a link between a task in the timeline and a placeholder in the grid is now blocked

6.3.5 (January 31, 2020)

  • (Fixed) the issue with task grouping, which caused vertical scroll position to reset after moving any task with drag and drop
  • (Fixed) the script error, which happened when drag_timeline config was set to null
  • (Fixed) the incorrect position of highlighted cells when static_background and static_background_cells are enabled and smart_rendering is disabled
  • (Fixed) the issue with the onAfterBranchLoading event not being called
  • (Fixed) the incorrect work of the smart rendering when the value of task_height is less than the value of row_height

6.3.6 (February 10, 2020)

  • (Fixed) the regression in gantt.resetLayout, which caused the script error
  • (Fixed) the issue with the QuickInfo popup, which caused it to be positioned behind the resource panel in some cases
  • (Fixed) the script error thrown from the gantt.getShortcutHandler method
  • (Fixed) the script error thrown from the tooltip.show(x, y) method gantt.getTaskNode now returns the correct HTML element for split tasks
  • (Fixed) the issue with horizontal scrollbars not being displayed when visibility groups are specified in some layout configurations

6.3.7 (February 12, 2020)

  • Significant performance improvement for the smart rendering of chart and resource panel

The v6.3.7 has made a substantial difference in the speed and performance of the DHTMLX Gantt chart, especially with the resource panel.


You can check it out yourself using the following snippets:
Previous versions: https://snippet.dhtmlx.com/5/1b0d9c4ec
The new version 6.3.7: https://snippet.dhtmlx.com/5/87e1c4df3

Learn more in the documentation >

Suite 6.4.1

6.4.1 (January 30, 2020)

  • (Fixed) the behavior of Lazy loading in Grid
  • (Fixed) the issue with the template configuration option in a column of Grid
  • (Fixed) the issue with the headerIcon property of a layout cell
  • (Fixed) the issue with the height of layout cells when the layout has a header

Besides, in February we updated the demo of Suite UI components with React on GitHub.

Learn more in the documentation >

DHTMLX Scheduler 5.3.5

5.3.5 (January 31, 2020)

  • (Fixed) styling of the ‘next’ button on the right side of the navigation panel in Terrace skin when the scheduler is initialized using header config
  • (Fixed) the incorrect work of the URL extension, which failed to highlight events by URL in some cases
  • (Fixed) the incorrect work of the Material skin when scheduler styles are loaded using the @import command
  • (Updated) If neither header config nor default markup is specified while initializing the scheduler, a default value for the scheduler header will be auto-generated to escape a script error

Learn more in the documentation >

Diagram 2.2.1

2.2.1 (December 30, 2019)

  • (Fixed) the issue with IE support for the image loader in Diagram editor

Learn more in the documentation >

Pivot 1.4.1

1.4.1 (January 15, 2020)

  • (Fixed) the issue with attaching Pivot to the Layout (Suite UI component)

Learn more in the documentation >

Download the latest versions of our libraries and test them free of charge for 30 days:

Current clients may find the updated packages in their Client’s Area.

The post DHTMLX Maintenance Release: Gantt 6.3.7, Scheduler 5.3.5, Suite 6.4.1, Diagram 2.2.1, and Pivot 1.4.1 appeared first on DHTMLX Blog.

Viewing all 392 articles
Browse latest View live