Getting Reports To User Hierarchy in Sugar CRM as Array

Create File custom_utils.php in custom/include directory and add the following functions in to it

The getReportsToUserArray Function has two parameters
$userid is the id of user
$teamArray returns the array of private team of reporting user hierarchy



function getReportsToUserArray($userId, $teamArray = array()) {
    if (!empty($userId) && $userId != 1) {
        $reportingUser = new User();
        $reportingUser->retrieve($userId);
        if (!empty($reportingUser->reports_to_id) && $reportingUser->reports_to_id != 1) {
            $teamArray[] = User::staticGetPrivateTeamID($reportingUser->reports_to_id);
            $nextuserId = $reportingUser->reports_to_id;
            return getReportsToUserArray($nextuserId, $teamArray);
        }
        return $teamArray;
    }
}

The getUserIdByPrivateTeam Function has two parameters
$teamArray is the array of private team of reporting user which will be return by above function
This Function returns the Array of userid by private team of users

function getUserIdByPrivateTeam($teamArray = array()) {
    global $db;
    if (!empty($teamArray)) {
        $privateteamstring = implode("','", $teamArray);
        $result = $db->Query("SELECT associated_user_id  from teams WHERE id in ('$privateteamstring')");
        while ($row = $db->fetchByAssoc($result)) {
            $UserIDArray[] = $row['associated_user_id'];
        }
    }
    return $UserIDArray;
}

After Getting this array we can check the selected assigned user id in this array
if the id is available we can restrict the save action by javascript or jquery in view.edit.php of case module

Pass Php Array to Javascript using JSON – Sugar CRM


Consider that we are restricting user to assign a case to his/her reporting person so create the file like below as view.edit.php in custom/module/cases/view/ .
The functions which are used to get reporting person of current user are in another post getReportsToUserArray(); getUserIdByPrivateTeam();

require_once('include/EditView/EditView2.php');

class CasesViewEdit extends SugarView {

    var $ev;
    var $type = 'edit';
    var $useForSubpanel = true;  //boolean variable to determine whether view can be used for subpanel creates
    var $useModuleQuickCreateTemplate = false; //boolean variable to determine whether or not SubpanelQuickCreate has a separate display function
    var $showTitle = true;

    function CasesViewEdit() {
        parent::SugarView();
    }

    /**
     * @see SugarView::preDisplay()
     */
    public function preDisplay() {
        $metadataFile = $this->getMetaDataFile();
        $this->ev = $this->getEditView();
        $this->ev->ss = & $this->ss;
        $this->ev->setup($this->module, $this->bean, $metadataFile, 'include/EditView/EditView.tpl');
    }

    function display() {

        global $db, $current_user;
        //Get All Reports To Id User of Current User in Array Format
        $ReportsToTeamArray = getReportsToUserArray($current_user->id);
        //Get User Id By Reports To Id from team table
        $AssignedUserIdArray = getUserIdByPrivateTeam($ReportsToTeamArray);

        $js1 = <<<EOF
<script>

                            var restictedUsers='$AssignedUserIdArray';                           
                            if(document.getElementById('EditView')!=null)
                            {
                                var _form = document.getElementById('EditView');
                                var formElements = _form.getElementsByTagName("*"); 
 for(var i=0;i < formElements.length; i++)
                                {
                                      // Check if the value of the current element is Save
                                      if (formElements[i].value == "Save")
                                      {
                                         formElements[i].setAttribute("onclick", "return SetSaveActionEditView()");
                                      }
   }  
                            }
                            function SetSaveActionEditView()
                            {                              
                                var _form = document.getElementById('EditView'); 
                                _form.action.value='Save';                            
                                if(check_form('EditView'))
                                {
  data=eval('('+restictedUsers+')');
                                    if(data.indexOf(_form.assigned_user_id.value) > -1)
                                    {
                                     alert('Not Autorized To Assign Case To Reporting To Person');
                                     return false;
                                    }

                                    SUGAR.ajaxUI.submitForm(_form);
                                    return false;
                                }
                                return false;
</script>
EOF;

        $this->ev->process();
        echo $this->ev->display($this->showTitle);       
        echo $js1;
    }

    /**
     * Get EditView object
     * @return EditView
     */
    protected function getEditView() {
        return new EditView();
    }

}

Converting CSV to Array – Php

This function will convert the CSV file to array

function csv_to_array($filename=”, $delimiter=’,’)
{
if(!file_exists($filename) || !is_readable($filename))
return FALSE;

$header = NULL;
$data = array();
if (($handle = fopen($filename, ‘r’)) !== FALSE)
{
while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
{
if(!$header)
$header = $row;
else
$data[] = array_combine($header, $row);
}
fclose($handle);
}
return $data;
}

Basic Syntax of Regular Expressions

First of all, let’s take a look at two special symbols: '^' and '$'. What they do is indicate the start and the endof a string, respectively, like this:

  • ^The“: matches any string that starts with “The”;
  • of despair$“: matches a string that ends in the substring “of despair”;
  • ^abc$“: a string that starts and ends with “abc” — that could only be “abc” itself!
  • notice“: a string that has the text “notice” in it.
You can see that if you don’t use either of the two characters we mentioned, as in the last example, you’re saying that the pattern may occur anywhere inside the string — you’re not “hooking” it to any of the edges.
There are also the symbols '*''+', and '?', which denote the number of times a character or a sequence of characters may occur. What they mean is: “zero or more”, “one or more”, and “zero or one.” Here are some examples:

  • ab*“: matches a string that has an a followed by zero or more b‘s (“a”, “ab”, “abbb”, etc.);
  • ab+“: same, but there’s at least one b (“ab”, “abbb”, etc.);
  • ab?“: there might be a b or not;
  • a?b+$“: a possible a followed by one or more b‘s ending a string.
You can also use bounds, which come inside braces and indicate ranges in the number of occurences:

  • ab{2}“: matches a string that has an a followed by exactly two b‘s (“abb”);
  • ab{2,}“: there are at least two b‘s (“abb”, “abbbb”, etc.);
  • ab{3,5}“: from three to five b‘s (“abbb”, “abbbb”, or “abbbbb”).
Note that you must always specify the first number of a range (i.e, “{0,2}“, not “{,2}“). Also, as you might have noticed, the symbols '*''+', and '?' have the same effect as using the bounds “{0,}“, “{1,}“, and “{0,1}“, respectively.
Now, to quantify a sequence of characters, put them inside parentheses:

  • a(bc)*“: matches a string that has an a followed by zero or more copies of the sequence “bc”;
  • a(bc){1,5}“: one through five copies of “bc.”
There’s also the ‘|’ symbol, which works as an OR operator:

  • hi|hello“: matches a string that has either “hi” or “hello” in it;
  • (b|cd)ef“: a string that has either “bef” or “cdef”;
  • (a|b)*c“: a string that has a sequence of alternating a‘s and b‘s ending in a c;
A period ('.') stands for any single character:

  • a.[0-9]“: matches a string that has an a followed by one character and a digit;
  • ^.{3}$“: a string with exactly 3 characters.
Bracket expressions specify which characters are allowed in a single position of a string:

  • [ab]“: matches a string that has either an a or a b (that’s the same as “a|b“);
  • [a-d]“: a string that has lowercase letters ‘a’ through ‘d’ (that’s equal to “a|b|c|d” and even “[abcd]“);
  • ^[a-zA-Z]“: a string that starts with a letter;
  • [0-9]%“: a string that has a single digit before a percent sign;
  • ,[a-zA-Z0-9]$“: a string that ends in a comma followed by an alphanumeric character.
You can also list which characters you DON’T want — just use a '^' as the first symbol in a bracket expression (i.e., “%[^a-zA-Z]%” matches a string with a character that is not a letter between two percent signs).
In order to be taken literally, you must escape the characters "^.[$()|*+?{\" with a backslash ('\'), as they have special meaning. On top of that, you must escape the backslash character itself in PHP3 strings, so, for instance, the regular expression “(\$|¥)[0-9]+” would have the function call: ereg("(\\$|¥)[0-9]+", $str)(what string does that validate?)
Just don’t forget that bracket expressions are an exception to that rule–inside them, all special characters, including the backslash ('\'), lose their special powers (i.e., “[*\+?{}.]” matches exactly any of the characters inside the brackets). And, as the regex man pages tell us: “To include a literal ']' in the list, make it the first character (following a possible '^'). To include a literal '-', make it the first or last character, or the second endpoint of a range.”
For completeness, I should mention that there are also collating sequencescharacter classes, andequivalence classes. I won’t be getting into details on those, as they won’t be necessary for what we’ll need further down this article. You should refer to the regex man pages for more information.

Passing Parameters by Reference

Clearly when we pass parameters to a function it’s not by reference. How to check this? Well, like this.
/////////////////////////////
function f($param)
{
$param++;
}

$a = 5;
f($a);

echo $a;
//////////////////////////////////
Now the value of $a equals 5. If it were passed by reference, it would be 6. With a little change of the code we can get it.
/////////////////////////////////
function f(&$param)
{
$param++;
}

$a = 5;
f($a);
/////////////////////////////////
Now the variable’s value is 6.

echo $a;
///////////////////////////////////////