We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 40092
    • 265 Posts
    Hi y'all,

    Been wrestling through the documentation of revolution (as a years stubborn evo user), and some thing are quite amazing and some i don't really get. One thing i can't seem to ffind and/or understand is how i will translate i.e.

    something like this:
    $sql = "SELECT * FROM custom_table WHERE active='1' AND setfrontpage='1' LIMIT 3";
    $query = mysql_query($sql);
    echo mysql_error();
    while($row = mysql_fetch_object($query)){


    To a good and solid one in xPDO?
    I know modx is now always connected to the database and i can simply issue a query by doing something like:
    $modx->query->($sql);


    But that's about as far as i do understand what it is i need to be doing.

    Best Regards

      • 42049 ☆ A M B ☆
      • 250 Posts
      Here you go...

      //Query the table
      $query = $modx->newQuery('custom_table');
      $query->where(array(
          'active' => 1,
          'setfrontpage' => 1,
      ));
      //Limit the results (offset start, number to return)
      $query->limit('0', '3');
      
      //Fetch the results as a collection of objects with our custom query attached
      $items = $modx->getCollection('custom_table', $query);
      
      //Loop through each object
      foreach($items as $item) {
          $item->get('cell_name');
      }
        GEL STUDIOS
        MODX Professional | MODX Ambassador

        Website | Email | Twitter | Facebook
        • 8386 ☆ A M B ☆
        • 160 Posts
        Quote from: gelstudios at Nov 28, 2012, 07:42 AM
        Here you go...

        //Query the table
        $query = $modx->newQuery('custom_table');
        $query->where(array(
            'active' => 1,
            'setfrontpage' => 1,
        ));
        //Limit the results (offset start, number to return)
        $query->limit('0', '3');
        
        //Fetch the results as a collection of objects with our custom query attached
        $items = $modx->getCollection('custom_table', $query);
        
        //Loop through each object
        foreach($items as $item) {
            $item->get('cell_name');
        }

        As far as I am aware this is not completely correct. You need to have a class definition for your table. Just using custom_table won't work. However if custom_table was per say modx_content table then you would do:

        $query = $modx->newQuery('modResource');


        You will need to create class definition for any custom table you want to use xPDO Objects with, there is a guide on how to reverse engineer this so it creates the maps from your current db tables.
          • 40092
          • 265 Posts
          That actually makes a whole lotta sense to me. smiley Thanks a million.
          Am i maybe missing some documentation where this is in?
            • 8386 ☆ A M B ☆
            • 160 Posts
            Docs are available here http://rtfm.modx.com/display/xPDO20/Home, you can also dig into some of the extras using xPDO and the MODX core itself to get some more insight.
              • 40092
              • 265 Posts
              @silent works

              Well, that probably explains why my foreach is returning invalid. If the table is not known, there would be nothiong to loop.
              I will try and find the doc you mentioned.
                • 42049 ☆ A M B ☆
                • 250 Posts
                This a worth while read http://bobsguides.com/custom-db-tables.html

                Make and call the snippet as documented under "Code for CreateXpdoClasses",

                i.e, if you made your snippet called XPDO you would call it in a resource like this...

                [[!XPDO? &myPackage=`NAME` &myPrefix=`dbprefixname_`]]


                Then at the top of the snippet I have made above put...

                $modx->addPackage('aspire', MODX_CORE_PATH . 'components/NAME/' . 'model/','dbprefixname_');


                Obviously replacing NAME for the route to your component folder, and dbprefixname with the prefix you have put against your custom table.

                What bob rays snippet will do, is make all the classes and methods so that XPDO can interact with your database as an object...
                  GEL STUDIOS
                  MODX Professional | MODX Ambassador

                  Website | Email | Twitter | Facebook
                  • 8386 ☆ A M B ☆
                  • 160 Posts
                    • 40092
                    • 265 Posts
                    Thanks both for your input.

                    When running the snippet by Bob, it frankly does nothing at all, when i'm almost sure i have the code right.

                    I'm calling the snippet like this:
                    [[!CreateXpdoClasses? &myPackage=`mypackage` &myPrefix=``]]


                    And the code in the snippet is:
                    <?php
                    /**
                    * @package = CreateXpdoClasses
                    *
                    * Create Xpdo Classes script
                    *
                    * This script creates xPDO-ready classes from existing custom
                    * database tables. It only needs to be run once.
                    *
                    * It assumes that your custom tables have been imported into
                    * the MODx DB and use a different table prefix than the MODx tables.
                    
                    * In theory, you can use a separate DB but this has not been tested
                    * and the process of using the classes would be more complicated.
                    * To do this, you would need to set the following variables after
                    * including the config file, but before creating the $modx object:
                    * 
                    * $database_server = 'yourDbServer';
                    * $database_type = 'mysql';
                    * $dbase = 'yourDbName';
                    * $database_user = 'user';
                    * $database_password = 'password';
                    * $table_prefix = 'yourPrefix_';
                    *
                    * In the snippets that use the classes, you'd need to instantiate
                    * a new $xpdo object, and use $xpdo-> rather than $modx-> to call
                    * the methods.
                    * $xpdo = new xPDO('mysql:host=localhost;dbname=yourDbName',
                    *   $database_user,$database_password,$table_prefix);
                    *
                    * Note: If you are running this outside of MODx and testing it
                    * in the Manager, it will log you out when it runs, even though
                    * the Manager screen will still be visible. Actions taken in the
                    * Manager (e.g., saving a snippet) will not be successful. After
                    * running the script, reload the Manager page in your browser
                    * and you will be prompted to log back in.
                    *
                    *
                    */
                    /* assume we're in a snippet */
                    $outsideModx = false;
                    
                     if (!defined('MODX_CORE_PATH')) {
                         $outsideModx = true;
                        /* put the path to your core in the next line to run outside of MODx */
                        define(MODX_CORE_PATH, 'c:/xampp/htdocs/cubarevo/core/');
                        include_once MODX_CORE_PATH . '/model/modx/modx.class.php';
                        $modx= new modX();
                        $modx->initialize('mgr');
                    }
                    
                    /* set these if running outside of MODx */
                    
                    if ($outsideModx) {
                        $myPackage = 'mypackage';
                    
                        /* table prefix; must match the prefix of the tables to process */
                        $myPrefix  = '';
                    
                        /* optional -- only if your table prefix is the same as the modx prefix */
                        // $myTables = 'bobs_quotation';
                    }
                    
                    
                    
                    /* These two switches let you write the schema and/or create the classes;
                     * useful for debugging and for leaving a manually edited schema file alone*/
                    
                    $createSchema = $modx->getOption('createSchema',$scriptProperties,true); 
                    $createClasses = $modx->getOption('createClasses',$scriptProperties,true);
                    
                    /* Used to include the phpDoc templates below or other custom templates */
                    $includeCustomTemplates = empty($includeCustomTemplates)? 
                        false : $includeCustomTemplates;
                    
                    /* $myPackage is the name of your package. Use this in your
                     * addPackage() call to load all classes created by this script.
                     *  The class files will be created under the
                     * /core/components/$myPackage/model/ 
                     * directory.
                     * Example:
                     *     $myPackage = 'quotes';
                     *     $myPrefix = 'bobs_';
                     *     $path = MODX_CORE_PATH . 'components/' . $myPackage . '/';
                     *     $result = $modx->addPackage($myPackage, $path . 'model/', $myPrefix);
                     *     if (! $result) {
                     *         return('Failed to add package');
                     *     }
                     */
                    $myPackage = empty($myPackage)? 'mypackage' : $myPackage;
                    
                    /* table prefix; must match the prefix of the tables you want to process */
                    $myPrefix = empty ($myPrefix)? '' : $myPrefix;
                    
                    /* Table names to process -- this is only necessary if your table prefix is
                     * the same as that of the MODx tables. You can send a comma-separated list
                     * of full table names. In that case the class name will be the table name 
                     * minus the prefix with any underscores removed and any letter after an 
                     * underscore in upper case.
                     *
                     * You can also send an array of arrays of tableName => className, 
                     * which allows you to specify the exact class name rather then letting
                     * MODx create it from the table name. Each inner array specifies a full
                     * table name and the class name to use.
                     *
                     * NOTE: This feature may not be implemented yet.
                     *
                     * Examples:
                    
                     $myTables = 'bobs_quotation';
                    
                     $myTables = array(
                         array(
                            'bobs_quotation'=>'bobQuotation'
                         )
                     );
                    
                    */
                    $myTables = empty($myTables)? '' : $myTables;
                    
                    /* You shouldn't need to modify the code beyond this point
                    ********************************************************** */
                    
                    $sources = array(
                        'config' => MODX_CORE_PATH . 'config/config.inc.php',
                        'package' => MODX_CORE_PATH . 'components/' . $myPackage . '/',
                        'model' => MODX_CORE_PATH. 'components/' . $myPackage . '/model/',
                        'schema' => MODX_CORE_PATH . 'components/' . $myPackage . '/schema/',
                        );
                    
                    if (! file_exists($sources['package'])) {
                        mkdir($sources['package'],0777);
                    }
                    
                    if (! file_exists($sources['model'])) {
                        mkdir($sources['model'],0777);
                    }
                    if (! file_exists($sources['schema'])) {
                        mkdir($sources['schema'],0777);
                    }
                    
                    $modx->setLogLevel(modX::LOG_LEVEL_INFO);
                    $modx->setLogTarget(XPDO_CLI_MODE ? 'ECHO' : 'HTML');
                    
                    $manager = $modx->getManager();
                    $generator = $manager->getGenerator();
                    
                    if ($includeCustomTemplates) {
                        customTemplates($generator);
                    }
                    
                    
                    $file = $sources['schema'] . $myPackage . '.mysql.schema.xml';
                    
                    // echo '<br />File: ' . $file;
                    
                    /* boolean writeSchema (
                     *   string $schemaFile,  // Full path to the schema file you want to write
                     *   [string $package = ''], //  Name of your component
                     *   [string $baseClass = ''], // xPDO base class to use; 
                     *                                 send '' if using args below
                     *   [string $tablePrefix = ''], // Table prefix (of tables to process)
                     *   [boolean $restrictPrefix = false]), // Process only tables 
                     *                                          with $tablePrefix
                     *   [mixed $tableList = '' // Array of arrays of 
                     *                             full-table-name=>className or 
                     *                             a string with a comma-separated 
                     *                             list of full table names; 
                     *                             if you send the string the table
                     *                             name will be used as the class name.
                    */
                    
                    if ($createSchema) {
                    
                        $xml= $generator->writeSchema($file,
                                    $myPackage, '',$myPrefix,true,$myTables);
                    
                        if ($xml) {
                           $modx->log(modX::LOG_LEVEL_INFO, 
                               'Schema file written to ' . $file);
                        } else {
                            $modx->log(modX::LOG_LEVEL_INFO, 
                               'Error writing schema file');
                        }
                    }
                    
                    if ($createClasses) {
                         if ($generator->parseSchema($file, $sources['model'])) {
                             $modx->log(modX::LOG_LEVEL_INFO,
                                'Schema file parsed -- Files written to '. $sources['model']);
                         } else {
                             $modx->log(modX::LOG_LEVEL_INFO, 'Error parsing schema file');
                         }
                    }
                     $modx->log(modX::LOG_LEVEL_INFO, 'FINISHED');
                     exit();
                    
                     function customTemplates($generator) {
                    $generator->classTemplate= <<<EOD
                    <?php
                    /**
                     * [+phpdoc-package+]
                     * [+phpdoc-subpackage+]
                     */
                    class [[+class]] extends [[+extends]] {
                    }
                    ?>
                    EOD;
                    $generator->platformTemplate= <<<EOD
                    <?php
                    /**
                     * [+phpdoc-package+]
                     * [+phpdoc-subpackage+]
                     */
                    require_once (dirname(dirname(__FILE__)) . '/[+class-lowercase+].class.php');
                    class [+class+]_[+platform+] extends [+class+] {
                    }
                    ?>
                    EOD;
                    $generator->mapHeader = <<<EOD
                    <?php
                    /**
                     * [+phpdoc-package+]
                     * [+phpdoc-subpackage+]
                     */
                    EOD;
                    }
                    
                    
                      • 42049 ☆ A M B ☆
                      • 250 Posts
                      Your not passing anything in as your custom db prefix?

                      Create a folder under core/packages called "mypackage" - this is where bobs snippet will save the created classes and methods. Then give your custom DB table a prefix and put that in the snippet...
                        GEL STUDIOS
                        MODX Professional | MODX Ambassador

                        Website | Email | Twitter | Facebook