Alpha Software Mobile Development Tools:   Alpha Anywhere    |   Alpha TransForm subscribe to our YouTube Channel  Follow Us on LinkedIn  Follow Us on Twitter  Follow Us on Facebook

Announcement

Collapse

The Alpha Software Forum Participation Guidelines

The Alpha Software Forum is a free forum created for Alpha Software Developer Community to ask for help, exchange ideas, and share solutions. Alpha Software strives to create an environment where all members of the community can feel safe to participate. In order to ensure the Alpha Software Forum is a place where all feel welcome, forum participants are expected to behave as follows:
  • Be professional in your conduct
  • Be kind to others
  • Be constructive when giving feedback
  • Be open to new ideas and suggestions
  • Stay on topic


Be sure all comments and threads you post are respectful. Posts that contain any of the following content will be considered a violation of your agreement as a member of the Alpha Software Forum Community and will be moderated:
  • Spam.
  • Vulgar language.
  • Quotes from private conversations without permission, including pricing and other sales related discussions.
  • Personal attacks, insults, or subtle put-downs.
  • Harassment, bullying, threatening, mocking, shaming, or deriding anyone.
  • Sexist, racist, homophobic, transphobic, ableist, or otherwise discriminatory jokes and language.
  • Sexually explicit or violent material, links, or language.
  • Pirated, hacked, or copyright-infringing material.
  • Encouraging of others to engage in the above behaviors.


If a thread or post is found to contain any of the content outlined above, a moderator may choose to take one of the following actions:
  • Remove the Post or Thread - the content is removed from the forum.
  • Place the User in Moderation - all posts and new threads must be approved by a moderator before they are posted.
  • Temporarily Ban the User - user is banned from forum for a period of time.
  • Permanently Ban the User - user is permanently banned from the forum.


Moderators may also rename posts and threads if they are too generic or do not property reflect the content.

Moderators may move threads if they have been posted in the incorrect forum.

Threads/Posts questioning specific moderator decisions or actions (such as "why was a user banned?") are not allowed and will be removed.

The owners of Alpha Software Corporation (Forum Owner) reserve the right to remove, edit, move, or close any thread for any reason; or ban any forum member without notice, reason, or explanation.

Community members are encouraged to click the "Report Post" icon in the lower left of a given post if they feel the post is in violation of the rules. This will alert the Moderators to take a look.

Alpha Software Corporation may amend the guidelines from time to time and may also vary the procedures it sets out where appropriate in a particular case. Your agreement to comply with the guidelines will be deemed agreement to any changes to it.



Bonus TIPS for Successful Posting

Try a Search First
It is highly recommended that a Search be done on your topic before posting, as many questions have been answered in prior posts. As with any search engine, the shorter the search term, the more "hits" will be returned, but the more specific the search term is, the greater the relevance of those "hits". Searching for "table" might well return every message on the board while "tablesum" would greatly restrict the number of messages returned.

When you do post
First, make sure you are posting your question in the correct forum. For example, if you post an issue regarding Desktop applications on the Mobile & Browser Applications board , not only will your question not be seen by the appropriate audience, it may also be removed or relocated.

The more detail you provide about your problem or question, the more likely someone is to understand your request and be able to help. A sample database with a minimum of records (and its support files, zipped together) will make it much easier to diagnose issues with your application. Screen shots of error messages are especially helpful.

When explaining how to reproduce your problem, please be as detailed as possible. Describe every step, click-by-click and keypress-by-keypress. Otherwise when others try to duplicate your problem, they may do something slightly different and end up with different results.

A note about attachments
You may only attach one file to each message. Attachment file size is limited to 2MB. If you need to include several files, you may do so by zipping them into a single archive.

If you forgot to attach your files to your post, please do NOT create a new thread. Instead, reply to your original message and attach the file there.

When attaching screen shots, it is best to attach an image file (.BMP, .JPG, .GIF, .PNG, etc.) or a zip file of several images, as opposed to a Word document containing the screen shots. Because Word documents are prone to viruses, many message board users will not open your Word file, therefore limiting their ability to help you.

Similarly, if you are uploading a zipped archive, you should simply create a .ZIP file and not a self-extracting .EXE as many users will not run your EXE file.
See more
See less

Grid Save Zero as Null

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

    Grid Save Zero as Null

    What are some of the simple ways I can have a grid automatically save 0's as null values?

    I have a grid where users can forecast hours per week. Some users have been entering 0 to clear out cells instead of entering null. How can I go about converting 0 to NULL when the edited page of the grid is submitted?

    2018-06-20_8-20-24.png

    #2
    Re: Grid Save Zero as Null

    Ben,

    You can probably simply set the display property of the field - see image...

    Grid Blank if zero.png
    Peter
    AlphaBase Solutions, LLC

    [email protected]
    https://www.alphabasesolutions.com


    Comment


      #3
      Re: Grid Save Zero as Null

      Will that save the 0 values as null? My guess is that will only affect how a zero is displayed. Ultimately I don't want zeros stored in my table because it affects other areas of the application.

      Do you have any other suggestions?

      Comment


        #4
        Re: Grid Save Zero as Null

        Did you try checking the Blank is null?
        blankIsNull.png
        You can force the field to be Null if it is zero with this js on the OnBlur event:


        var rowNum = {Grid.RowNumber};
        var fieldValue = {grid.Object}.getValue("G","AMT_PAID",rowNum);
        if (fieldValue == 0){
        {grid.Object}.setValue("G","AMT_PAID",rowNum,'');
        }
        (with AMT_PAID being the field you want to make null)
        Jay
        Attached Files
        Last edited by Jay Talbott; 06-20-2018, 03:12 PM.
        Jay Talbott
        Lexington, KY

        Comment


          #5
          Re: Grid Save Zero as Null

          Thank you Jay! This is a great start. I didn't know a concise way to address the row number.

          I already had the "Blank is null" property checked. In your example code you are setting the new value to be ''. Is there an advantage of that over setting it to null?

          I had started experimenting with the onChange event instead of onBlur. I noticed that onBlur runs the code every time I tab over the cell. I'd prefer to not have code running unnecessarily. Unfortunately there seems to be a side effect using the onChange event. The code below runs in an endless loop if 0 is entered into the grid cell. Is there a way to tell the Change event not to fire if its value is changed within the event?

          PHP Code:
          var rowNum = {Grid.RowNumber};
          var 
          fieldValue = {grid.Object}.getValue('G','FCST_2018_25_JUN22',rowNum);

          console.log('FCST_2018_25_JUN22 CHANGE: ' + {grid.Object}.getValue('G','FCST_2018_25_JUN22',rowNum));   

          if (
          fieldValue == 0){
              {
          grid.Object}.setValue('G','FCST_2018_25_JUN22',rowNum,'');

          Comment


            #6
            Re: Grid Save Zero as Null

            You could try something like this using the server side CanInsertRecord & CanUpdateRecord events:

            Code:
            function CanUpdateRecord as v (DataSubmitted as P, Args as p, PageVariables as p, Result as p )
            with PageVariables
            Result.Cancel = .f.
            Result.ErrorHTML = ""
            
            Dim args as SQL::Arguments
            args.SetNull("DataSubmitted.Account_Id","N")
            DataSubmitted.Account_Id =  :Account_Id
            
            
            end with
            end function
            But I'm not sure it will work?
            Peter
            AlphaBase Solutions, LLC

            [email protected]
            https://www.alphabasesolutions.com


            Comment


              #7
              Re: Grid Save Zero as Null

              Processing this from the server side is an acceptable approach but I know less about Xbasic than I do JavaScript.

              Is there a way to loop through all columns and rows of a grid? I have 30 data entry columns that I need to run this against and the columns shift every week. I'd prefer to not have to hard code the column names. If I had a loop where I could identify the column name and if it is prefixed with 'FCST_' then I could look for a 0 and replace it with null. I don't know how to get the column name from the grid. I could do this on the client or the server.

              Comment


                #8
                Re: Grid Save Zero as Null

                I'm not sure how the columns can "shift each week", but presuming you are saving this data in some kind of sql database, I would use before insert and before update triggers to do this work.
                Gregg
                https://paiza.io is a great site to test and share sql code

                Comment


                  #9
                  Re: Grid Save Zero as Null

                  Originally posted by madtowng View Post
                  I'm not sure how the columns can "shift each week", but presuming you are saving this data in some kind of sql database, I would use before insert and before update triggers to do this work.
                  We have an denormalized database schema (like a pivot table) so we have a forecast column for each work week in the year. Every Monday we delete the first forecast column from the grid because it now represents a week in the past and we don't want to show it. We then re-publish the application. We do the same to show only the last 4 weeks of actual hours.

                  It's tedious publishing every week. We're using this method because there doesn't seem to be an easy way to store data in a normalized (un-pivoted) table, then allow it to be pivoted by work week and editable in a grid, and then stored back in a normalized way.

                  Using Triggers to do this is an option I originally hadn't considered. There are at least 52 columns that I'd have to validate in the trigger.

                  Comment


                    #10
                    Re: Grid Save Zero as Null

                    I think this can be done with a subquery to get the data for the first column.
                    My preferred database is MySQL and I'm quite creative with date related queries,
                    but it would help me greatly to see what the current query is.
                    Gregg
                    https://paiza.io is a great site to test and share sql code

                    Comment


                      #11
                      Re: Grid Save Zero as Null

                      The code below will select rows with pickup_dates between the most recent Monday and the following Sunday.
                      I think it would give you the data desired for the first column.

                      Code:
                      select  pickup_date, city, state FROM table 
                      where PICKUP_DATE between curdate() - interval (DAYOFWEEK(curdate())-2) day and curdate() - interval (DAYOFWEEK(curdate())-2) day+interval 6 day
                      Gregg
                      https://paiza.io is a great site to test and share sql code

                      Comment


                        #12
                        Re: Grid Save Zero as Null

                        Thanks for your input. I have put together a solution to this issue. This implementation allows the user to enter zeros into the cells but it sets them to null before they are submitted to the database.


                        I created a Published Session Variable in the grid properties named SESSION.GRID_COLUMN_STRING

                        In the grid OnGridInitialize server-side event I added a routine to populate that session variable with a comma delimited list of the grid column headings.

                        Code:
                        	' Create a session variable containing a comma delimited string of the grid column headings.
                        	dim columnString as c = ""
                        	colNum = e.tmpl.field_info.size()
                        	for i = 1 to colNum
                        		columnString = columnString + "," + Upper(e.tmpl.field_info[i].BaseFieldExpression) 
                        	next
                        	
                        	' Remove the first comma
                        	columnString = substr(columnString,2) 
                        	
                        	' Set the published session variable that is defined in the grid properties.	
                        	SESSION.GRID_COLUMN_STRING = columnString

                        I created a function to loop through all of the grid cells by row and column. It specifically looks for my Forecast columns that may be named like 'FCST_2018_52_Dec28'. If the cell contains 0 it is replaced with null.

                        PHP Code:
                        function validateGridCells() {
                        /*
                         This code will loop through all grid cells and change all Forecast values of 0 to null.
                         This is called by the canGridSubmit() Client-side event.
                         BS 6/21/2018
                        */
                            
                            // Get the column string from the session variable and convert it into an array.
                            
                        var columnString = {grid.Object}.getSessionVariable('GRID_COLUMN_STRING');
                            var 
                        colArray = new Array();
                            
                        colArray columnString.split(',');
                            var 
                        colArrayLen colArray.length// Number of columns.
                            
                            
                        var rowNum;
                            var 
                        colNum;
                            var 
                        colName;
                            var 
                        fieldValue;
                            
                            
                        // If you want this to only process the selected row in the grid replace the first For loop with the following statement.
                            //rowNum = {Grid.RowNumber};

                            
                        for (rowNum 1rowNum <= {grid.Object}.getRowsInGrid(); rowNum++ ) {

                                for (var 
                        colNum 0colNum colArrayLencolNum++ ) {
                            
                                    
                        colName colArray[colNum];

                                    
                        // Process all of the weekly forecast columns    
                                    
                        if (colName.substr(0,7) == 'FCST_20') {                
                                        
                        fieldValue = {grid.Object}.getValue('G',colName,rowNum);
                            
                                        
                        // Must use quotes around '0' because an empty string '' == numeric 0.
                                        
                        if (fieldValue === '0'){
                                            
                        //console.log('Row: ' + rowNum + ', Column: ' + colNum + ' (' + colName + ') = ' + fieldValue);
                                            
                        {grid.Object}.setValue('G',colName,rowNum,null);
                                        }        
                                    }
                                }    
                            }
                            
                        // Always return True unless we have a reason to cancel the action that calls this function.
                            
                        return true;

                        In the grid canGridSubmit client-side event I added a function call to validateGridCells();
                        During testing I was calling this function from the grid onDblClick event so I didn't keep saving over my test data.

                        If you know of a method to get the column headers from JavaScript without relying on Xbasic and a Session variable, please share that below.

                        Comment


                          #13
                          Re: Grid Save Zero as Null

                          Originally posted by madtowng View Post
                          I think this can be done with a subquery to get the data for the first column.
                          My preferred database is MySQL and I'm quite creative with date related queries,
                          but it would help me greatly to see what the current query is.
                          My current table is flat and denormalized. It is laid out just the way the user would use it. Data entry is very easy with this schema. Querying by date range is very hard. See screenshot at the top of this thread.

                          If you want to private message me, I can give you a demonstration of my application over Skype. I would like to know your feedback in case there is a better way I can do this.

                          Comment


                            #14
                            Re: Grid Save Zero as Null

                            What database are you using? If this is sql, you could just create a trigger to set all your zeros to null.

                            Comment


                              #15
                              Re: Grid Save Zero as Null

                              Hi Ben,
                              I couldn't make an exact copy, but I think I'm on the right path.
                              The date related columns are all generated programmatically.
                              Starting next week, it should shift the dates left 1 column, and put the next week into the right-most column.
                              I attached a script to create the table, as well as the query for the grid, and the sample data I used.
                              I did not create the suggested triggers yet, but those are relatively simple.

                              Capture.PNG
                              Attached Files
                              Gregg
                              https://paiza.io is a great site to test and share sql code

                              Comment

                              Working...
                              X