cancel
Showing results for 
Search instead for 
Did you mean: 

Changing color of table cells

JBrook
Explorer
0 Kudos

We have created a SAPUI5 application using the SAPUI5 "table" control and with a gateway service for oData and  I'd like to change the background color of the cells based on the data. If D1 red if D2 blue if D3 yellow.

So far I can do this only based on a menu event, click on a menu button to change the color. I've tried parsing the DOM with

document.getElementsByTagName(SPAN'), and looping thru the DOM and changing the background color but the data is not there until the bindrows has completed. I've tried window.onload and still the data is not there. Is there an event after when oTable.bindrows() gets the data?

Accepted Solutions (1)

Accepted Solutions (1)

former_member104694
Participant
0 Kudos

Hi Jesse,

You could try using the formatter function of the bindProperty method, this is called for each row in your table, for example...

var oControl = new sap.ui.commons.TextView().bindProperty("text", "bindpath",function(cellValue){

          switch(cellValue){

                    case 'D1':

                              backgroundColor = 'red';

                              break;

                    case 'D2':

                              backgroundColor = 'blue';

                              break;

                    case 'D3':

                              backgroundColor = 'yellow';

                              break;

                    default:

                              backgroundColor = 'white';

          }

          cellId = this.getId();

          $("#"+cellId).parent().parent().css("background-color",backgroundColor);

          return cellValue;

});

var oColumn = new sap.ui.table.Column({label: new sap.ui.commons.Label({text: "Columnhead1"}), template: oControl});

oTable.addColumn(oColumn);

Hope this helps.

Regards,

Ian

JBrook
Explorer
0 Kudos

Fantastic! Thanks Ian

Jesse

Former Member
0 Kudos

Hi,

Your code works great but I'm facing an issue.

If I move a column or change its width the custom css disappear.

Do you know how to fix this ?

Regards

former_member104694
Participant
0 Kudos

Hi Loic,

Some of the responses in the below thread may be able to help you with this...

http://scn.sap.com/thread/3383698

Cheers,

Ian

Former Member
0 Kudos

Hi Ian,

Thanks ! The thread you mentioned helped me a lot and it works now.

Cheers

Former Member
0 Kudos

Hi Loic, I know it's been a while but do you remember what you did to fix this issue?  Did you switch to using the CustomData appoach or were you able to get it working using Ian's code suggestion above?  I have tried a few things from the other blog but no luck getting it to work yet, I lose the background color when re-sizing or moving columns and when I scroll the behavior is really strange.

Thanks!

Amy

Former Member
0 Kudos

Hi Aguedelo,


if possible post a workig example of your current implementation.

Coloring the cells is a littlebit tricky and it would be easier to have some code then to guess what's wrong there...


Greets,

ben

Former Member
0 Kudos

Hi,

I think I did switch to the CustomData approach exactly because of the issues you mentionned regarding  the loss of the custom color when the table is redrawn etc.

I remember having solved this issue but I do not have the code right now to check what I'm saying.

Try the customdata and let me know if you need further help.

Regards.

Former Member
0 Kudos

Thank you both.  I switched to CustomData today as well and it's working better but still a bit quirky.  I have some if/else logic in the template since my coloring is based off of values in 2 different columns (I'm sure there is a better way to handle that logic), I believe that's where I'm running into issues (re-sizing the columns is fine now but scrolling still causes the coloring of any cells that were changed by conditional logic to disappear).

I also can't find a way to color the entire row with this approach, with the original code I had that working with this statement "$("#"+cellId).parent().parent().parent().css("background-color",backgroundColor);" inside of the addColumn/bindProperty function.

I attempted to add my code but when I hit reply the formatting was lost.  I'm pretty sure this is where my issue with the scrolling is occurring though, the conditional logic:

oDataTemplateS.bindProperty("value", "STATUS", function(cellValue){ 

    switch (cellValue) { 

    case 'Error':  

           backgroundcolorchanged = 'true';

           return('red');       

    case 'Executed':

        if (backgroundcolorchanged === 'true')

          {

                  return('default');

          }

        else

         {

             backgroundcolorchanged = 'true';

                  return('yellow');

          }    

Former Member
0 Kudos

Hi again,

you should remove all classes from the control before you add a new one - otherwise the classes will "stack" which results in strange behaviour.

Add this at the beginning of your formatter function:


this.removeStyleClass('red'); 

this.removeStyleClass('default'); 

this.removeStyleClass('yellow');

Regarding you problem coloring the whole row I have to take a look first...

Greets,

ben

Former Member
0 Kudos

Thanks Ben.  I added the removeStyleClass statements but I still get the odd behavior with "yellow".  When I scroll down it disappears but if I re-size the column or go to another tab and back it reappears. I have set multiple colors without conditional logic and they all work just fine.

Former Member
0 Kudos

Hey,

It would be really helpfull if you can share a code sample where the problem is shown (best using a json mode with local data).

When formatting is lost, that's no problem

You can also use github, take a look here:

Greets,

ben

Former Member
0 Kudos

ok try this please -  https://gist.github.com/agudeloa/8605027. I stripped down and moved the code into an html file so that it's easier to work with (and made the data local and using a JSON model). 

2 issues...

1. when you scroll down and back up the yellow background is lost.  Background is set to yellow if STATUS = Executed AND ACTION = Replication.  Since it loads by columns I'm not sure of another way to accomplish this.  And when you scroll down and back I up I noticed that it doesn't always reload the ACTION column which is why the replication variable isn't set and therefore the STATUS column isn't made yellow.

2. If possible I'd like to color the entire row vs just the cell.

Any help is greatly appreciated!!

Thanks,

Amy

Former Member
0 Kudos

Hi Agu,

I checked your code but wasn't able to get it working as expected using the "CustomData"-approach.

In my own app I'm using the formatter function of the column binding, and this works OK for me.

Here's the code of one of the columns of my table:


//Define the columns and the control templates to be used

var oColumn = new sap.ui.table.Column({

    label: new sap.ui.commons.Label({text: "Last Name"}),

    template: new sap.ui.commons.TextView().bindProperty("text", "lastName", function(cellVal) {

        this.removeStyleClass('highlight');

        if (cellVal === 'Barr' ||cellVal === 'Dente' || cellVal === 'Dewit') {

            this.addStyleClass('highlight');

        }

        return cellVal;

    }),

    sortProperty: "lastName",

    filterProperty: "lastName",

    width: "200px"

});

I don't know if you are using the customData for other reasons, but if you can I would try to pass them...

For your second question:

It seems there's no easy to color the whole row, since the row-element lacks the function "addCustomStyle".

Maybe you could extend the class sap.ui.table.Row and add the addCustomStyle-method. In this case I think you have to write a custom renderer function, but I'm not an expert with that.

Maybe it's an good idea to open a seperate topic for this one!

Greets,

ben

Answers (2)

Answers (2)

Former Member
0 Kudos

Hi Ian,

That code works fine for me, perfectly actually but, if I navigate away from my the worksetitem page with the table to another worksetitem page in my shell I lose the colours when I come back to the page with the table.

Does this only work when the model has changed? So i.e. when the model is initially filled with new data and updated but if you have switch between the pages in a shell it loses the css for the cell?

Thanks!

Former Member
0 Kudos

Anyone have any idea why I lose the colors if I switch between tabs on a shell?

Former Member
0 Kudos

Hi,

I had the same issue and the code below should help you.

The purpose of this code is to add a custom data to your table cell depending on the cell value and use some css magic to define the color

Here's the javascript :


// custom color for positive or negative amounts

var oControlCOB = new sap.ui.commons.TextView().bindProperty("text", "CorpOpBudget", function(cellvalue) {

  return toMoney(cellvalue, 2, ',', ' ') + " €";

}).setTextAlign("Right");

var oDataTemplateCOB = new sap.ui.core.CustomData({

  key : "colortype",

  writeToDom : true

});

oDataTemplateCOB.bindProperty("value", "CorpOpBudget", function(cellValue) {

  if (cellValue) {

  if (cellValue >= 0) {

  return "green";

  } else {

  return "red";

  }

  }

});

oControlCOB.addCustomData(oDataTemplateCOB);

oTable.addColumn(new sap.ui.table.Column({

  label : new sap.ui.commons.Label({

  text : "Corp./Op. budget",

  tooltip : "Corp./Op. budget"

  }),

  template : oControlCOB.setTextAlign("Right"),

  sortProperty : "CorpOpBudget",

  filterProperty : "CorpOpBudget",

  width : "60px",

  hAlign : "Right"

}));

here is the css :


[data-colortype="green"] {

  color: green;

  background-color: #BBE3C8;

}

[data-colortype="green"]:hover {

  color: #FFFFFF;

  background-color: green;

}

[data-colortype="red"] {

  color: red;

  background-color: #FFC2C2;

}

[data-colortype="red"]:hover {

  color: #FFFFFF;

  background-color: red;

}

Hope it helps.

Regards.

Former Member
0 Kudos

Thanks Loic that does keep the colour thank you! Do your colours fully occupy the cell? With the code above it just seems to colour the area around the text but not all of the cell?

MariusStoica
Active Participant
0 Kudos

Hi everybody,

I want to a similar thing to my table cells, but I find it hard to transform the code to XMLView from JSView. Can you guys give me a hand ?

What I've managed so far, is to add the text of the color:

but what I want is to color the text itself (or the background):

Here is the code:


        <ObjectIdentifier

            title="{Invoices>BillValue}"

            text = "{parts : [ 'Invoices>InvoiceRest' ],

              formatter: 'Invoices.Formatter.BillColor'

            }"/>

And in the "formatter";


jQuery.sap.declare("Invoices.Formatter");

Invoices.Formatter = {

BillColor :  function (fValue1) {

try {

if (Number(fValue1) > 0) {

return "red";

} else {

return "green";

}

} catch (err) {

      return "None";

    }

}

};

Thanks,

Marius

former_member207744
Contributor
0 Kudos

Hi Marius Stoica,

No more zombie model. Please open a new thread.

agentry_src
Active Contributor
0 Kudos

Thread is now locked by the Moderator.  Please open a new thread as Sriram has requested.

Regards, Mike (Moderator)

Former Member
0 Kudos

Hi there,

I just tried to color a cell using this way, but unfortunately it doesn't work for me.

When the table data is loaded, none of the cells is colored.

When using the scrollbar of the table and move it up and down, the first 2 or 3 cells get the background color.

It seems that at the point of time when jquey tries to access the element, its not sure that it does exist in the DOM.

Maybe somebody got a solution for that?

thanks!

former_member104694
Participant
0 Kudos

Hi Ben,

Is it possible to share some of your code? I'm think the formatter function should only be called once the DOM element (table cell in this case) actually exists

Cheers,

Ian

JBrook
Explorer
0 Kudos

Here's what I did to get the colors based on the data

  // Add New Columns

  function new_cols() {   

    for( var j=0;j<LabelList.length;j++)
        {
        if (j<2)
          {
        oColumn = new sap.ui.table.Column({
            label: new sap.ui.commons.Label({text: LabelList[j]}),
            template: new sap.ui.commons.TextView().bindProperty("text", TempList[j]),

'            width: "120px"});                                  

            }

        else            {
            oColumn = new sap.ui.table.Column({
            label: new sap.ui.commons.Label({text: LabelList[j]}),
            template: new sap.ui.commons.TextView().bindProperty("text", TempList[j]

             function(cellValue) {
              switch(cellValue) {
              case 'D1':
                backgroundColor = 'pink';

              case 'D2':
                backgroundColor = 'red';

              case 'E':
                backgroundColor = 'yellow';

              default:
                backgroundColor = 'white';
              }
              cellId = this.getId();

                $("#"+cellId).parent().parent().css("background-color",backgroundColor);
                return cellValue;
            }),

            width: "55px"});
          };        

          oTable.addColumn(oColumn);           
        };

 

 

Former Member
0 Kudos

Hi Ian,

yes of course, here's the code snippet it tested it with:

var oMappedData = new sap.ui.model.odata.ODataModel('/app1/services/test.xsodata/', false);

var oMappedTable = new sap.ui.table.Table({visibleRowCount: 20, selectionMode : 'Single', editable: false});

oMappedData.attachRequestSent(function() {

    oMappedTable.setFooter(new sap.ui.core.HTML({content : '<div class="table-footer" style="">Please wait - data is loading...</div>'}));

});

oMappedData.attachRequestCompleted(function() {

    oMappedTable.setFooter(new sap.ui.core.HTML({content : '<div></div>'}));           

});       

tvUserColor = new sap.ui.commons.TextView().bindProperty("text","COLOR", function(cellValue) {

    cellId = this.getId();

    $("#"+cellId).css("background-color","red"); 

    return cellValue;

});

// Table Column-Definition

oMappedTable.addColumn(new sap.ui.table.Column({label: new sap.ui.commons.Label({text:"Color"}), template: tvUserColor, width: "100px", sortProperty: "COLOR", filterProperty: "COLOR"}));

       

oMappedTable.setModel(oMappedData);

oMappedTable.bindRows("/test", new sap.ui.model.Sorter("COLOR"));

oMappedTable.setTitle("Some title" );

oMappedTable.attachRowSelectionChange(function(oEvent) {

    /* unintersting code... */

});

tabUserMapping.addContent(oMappedTable);

Maybe I should mention that I'm on SAPUI5 urntime 1.8.4 (the version cloudshare has currently installed).

Here's a screenshot how it looks like:

http://www.pic-upload.de/view-19624873/sapui5_color_cell.png.html

the upper one is like it looks after the pages is loaded, the second is like it looks when you've scrolled down using the scrollbar.

Thanks a lot for your help,

greets,

Ben

Former Member
0 Kudos

Hi Jesse,

that definitely doesn't work for me and results in a quite wired behaviour

Which SAPUI5 runtime you are on?

Thanks,

Ben.

former_member104694
Participant
0 Kudos

Hi Ben,

I just tried with your code (using a different OData service) and got the same result as you, then once I removed the calls to oMappedTable.setFooter() it worked...haven't checked out yet exactly what the setFooter method is doing to stop this from working, but hopefully this might point you in the right direction.

Cheers,

Ian

Former Member
0 Kudos

Hey Ian,

thanks a lot for your effort checking out this problem!

I've just tried it and it works so far - one little problem still exists: if the table has a scrollbar, the coloring of the cells is only visible after scrolling up/down...

Have a nice weekend,

greets,

Ben