1. Fabrik 3.8 has been released. As usual, we strongly recommend that you backup your site (using Akeeba) before upgrading. Report any issues in the forums, we will answer promptly.

Common PHP tasks

Feb 17, 2017
Common PHP tasks

  • Standard Evaluations (top)

    Using eval
    Element_default_examples

    Forms (top)

    Form submission

    Databases (top)

    Joomla.25/Joomla3 syntax see http://docs.joomla.org/Accessing_the_database_using_JDatabase

    Examples:(top)


    Select (top)


    Load an array of rows as objects:
    PHP:
    // Get a db connection.
    $myDb = JFactory::getDbo();

    // Create a new query object.
    $myQuery = $myDb->getQuery(true);

    $myQuery
        ->select(array('fieldA', 'fieldB'))
        ->from('tablename')
        ->where('fieldC = ' . $myDb->quote('value'));

    // Assign the query to the db
    $myDb->setQuery($myQuery);

    // Load the results as an array of objects.
    $rows = $myDb->loadObjectList();
    Returning data from the array of rows (above) and display it
    e.g when using a calc element for this purpose? Let's say we want to display the rows as fieldA and fieldB in an ordered list:
    PHP:
    $list = array();
    foreach ($rows as $row)
    {
        $list[] = "<li>" . $row->fieldA . " " . $row->fieldB . "</li>";
    }
    return "<ol>" . implode($list) . "</ol>";
    Load a single ROW of data as an object:
    PHP:
    $myDb = JFactory::getDbo();
    $myQuery = $myDb->getQuery(true);

    $myQuery
        ->select(array('fieldA', 'fieldB'))
        ->from('tablename')
        ->where('fieldC = ' . $myDb->quote('value'));

    $myDb->setQuery($myQuery);

    $row = $myDb->LoadObject();
    Note: In additional to loading by table name, if you know the $id of the record you wish and want to load it from the list name (instead of table name), you can use the Fabrik List Model like this...

    PHP:

    $row = $listModel->getRow($rowId);


    Load a single VALUE from a ROW of data:
    PHP:
    $myDb = JFactory::getDbo();
    $myQuery = $myDb->getQuery(true);

    $myQuery
        ->select('fieldA')
        ->from('tablename')
        ->where('fieldC = ' . $myDb->quote('value'));

    $myDb->setQuery($myQuery);
    $fieldA = $myDb->loadResult();
    Note: loading a single row is often used to populate a field with some default data - if you are using eval on a field you should return the value as per this line of code:
    PHP:
    return $fieldA;
    See using eval for more info

    Insert (top)


    Insert data into a database:
    PHP:
    // Get a db connection.
    $myDb = JFactory::getDbo();

    // Create a new query object.
    $myQuery = $myDb->getQuery(true);

    // Insert columns.
    $columns = array('fieldA', 'FieldB');

    // Insert values.
    $values = array('1', '2');

    // Prepare the insert query.
    $myQuery
        ->insert($myDb->quoteName('tablename'))
        ->columns($myDb->quoteName($columns))
        ->values(implode(',', $myDb->quote($values)));

    // Reset the query using our newly populated query object.
    $myDb->setQuery($myQuery);

    try {
    // Execute the query
      $result = $myDb->execute();
    //use $myDb->query() in Joomla2.5
    }
    catch (Exception $e) {
    // catch any database errors.

    }
    $newid = (int)$myDb->insertid(); //get new record id
     

    Update (top)

    Update a table with a join (use another field [Status] instead of it's ID value):
    PHP:
    $IDinput = '{rowid}';

    // Get the db object
    $myDb = JFactory::getDbo();

    // Build the query – Tables names = CASE SENSITIVE
    $myQuery = $myDb->getQuery(true);

    $myQuery
          -> update('contacts AS c')
          -> join('INNER','contactsstatus AS s ON s.Status = \'New\'')
          -> set('c.Status = s.id')
          -> where('c.id = '. (int) $IDinput);

    $myDb->setQuery($myQuery);

    // Run the query
    $found = (int) $myDb->execute();
    //use $myDb->query() in Joomla2.5

    Use alternate Fabrik connection (top)


    Here we are loading the connection with an ID of 2:
    PHP:
    $myDb = FabrikWorker::getDbo(false, 2);

    Get A List's data (top)


    For Fabrik 3.0+, to get data from a List with an ID of 1:
    PHP:

    // Fabrik 3.1
    $listModel = JModelLegacy::getInstance('List', 'FabrikFEModel');

    // Fabrik 3.0
    $listModel = JModel::getInstance('List', 'FabrikFEModel');

    $listModel->setId(1);
    $data = $listModel->getData();

    // Get params
    $params = $listModel->getParams();
     
    If you want to access the list from a external script, you'll need to include the model by adding this line to your script prior to the the above:
    PHP:

    JModel::addIncludePath(JPATH_SITE . '/components/com_fabrik/models');
    And to read a record from a List when knowing the row's $id:
    PHP:

    $row = $listModel->getRow($rowid);

    Users (top)


    To get the current, logged-in user in Joomla you need this line:
    PHP:
    $user = JFactory::getUser();
    To grab a property from the user object:
    PHP:
    $userid = $user->get('id');
    $name = $user->get('name');
    $username = $user->get('username');
    $email = $user->get('email');
    To grab all user's groups you need this line :
    infos in an array and the "false" option remove default joomla groups( like admin or register...)
    PHP:
    $groups = JAccess::getGroupsByUser({$my->id}, false);
    return($groups);
    To grab a specifique user's group you need to return something like :
    PHP:
    $groups = JAccess::getGroupsByUser({$my->id}, false);
    return($groups['3']);

    Dates (top)


    Deciding in PHP if a date within an age range
    To check someone's age from their date of birth:

    PHP:
    $myApp = JFactory::getApplication();
    $date= $myApp->input->getString('tablename___dateelement');
    $date = strtotime($date);
    $now = time();
    $diff = $now - $date;
    $years = floor($diff / 31556926);
    return ($years >= 18 && $years <= 90);
    Difference in days between 2 dates in PHP
    This gives the difference in days between a date element and today, Alternatively you could swap 'today' with another date or field

    PHP:
    $nowdate = strtotime("{table___element}");
    $thendate = strtotime("today");
    $datediff = ($thendate - $nowdate);
    $diff = round($datediff / 86400);
    return $diff;
    It was used in a schedule task email plugin that required multiple conditions to be met, as follows

    PHP:
    $cond1 = ('{table___element}' == 'X');
    $nowdate = strtotime("{table___element}");
    $thendate = strtotime("today");
    $datediff = ($thendate - $nowdate);
    $diff = round($datediff / 86400);
    $cond2 = ($diff == X);
    return $cond1 <> $cond2;
    Send a reminder email only to the rows(users) that didn't update a record for more than 16 days.

    PHP:
    $date1 = strtotime("{table___update_raw}");
    $date2 = strtotime("{table___createdate_raw}");
    $date2 = strtotime("+16 day", $date2);
    return $date1 > $date2;
samani, Barcellos, daydah and 10 others like this.