We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 3749
    • 24,544 Posts
      Did I help you? Buy me a beer
      Get my Book: MODX:The Official Guide
      MODX info for everyone: http://bobsguides.com/modx.html
      My MODX Extras
      Bob's Guides is now hosted at A2 MODX Hosting
      • 25551 ☆ A M B ☆
      • 1,231 Posts
      Thanks Bob, I already seen those... I totally forgot I added to your post about this article! I can’t seem to find it on the forum though, do you have a link at all?

      Cheers.
        Ross Sivills - MD AugmentBLU Edinburgh, Scotland UK
        AugmentBLU - MODX Partner

        BLUcart - MODX Revolution E-Commerce & Shopping Cart
        • 22303 MODX Staff
        • 10,725 Posts
        Quote from: rossco at Oct 18, 2010, 07:26 AM

        I hope it’s as easy as that! What resources did you use to get yourself in-tune with it? Did you read the PDO manual for PHP or should the modx xPDO manual be enough?
        I would definitely become acquainted with PDO since xPDO is just a class which wraps a PDO connection and provides additional functionality, like connect() on demand (i.e. when calling a PDO method via xPDO) and the simple CRUD features enabled by creating an xPDO model. IOW, you can use xPDO as if it is just PDO (similar to the DBAPI) or you can take advantage of the O/RM layer which provides an instant, consistent, and extensible OO API into your table model.

        Quote from: rossco at Feb 02, 2011, 08:59 AM

        Is there a tutorial on how to insert simple form data in to the modx database yet? I am about to start a project that will require data capture from forms in the database and would like to find out how best to send the input data for storage.
        It can really be as simple as:
        <?php
        $object = null;
        if (!empty($_POST) && isset($_POST['submitMyForm'])) {
            if (isset($_POST['obj_id')) $object = $modx->getObject('MyObject', $_POST['obj_id']);
            if (empty($object)) {
                $object = $modx->newObject('MyObject');
            }
            $object->fromArray($_POST, 'obj_');
            $object->save();
        }
        ?>

        Here you just prefix any form field names with obj_ that you are wanting to save into your custom database table and then use the fromArray() method to set the column values from the POST fields. You would probably add better error handling, validation, etc. into your Snippet to process the form, but that is the basic gist of saving data from a form into an xPDO table object (xPDOObject class).

        But the other tutorials BobRay is suggesting will go a bit deeper into the details...
          • 25551 ☆ A M B ☆
          • 1,231 Posts
          Hello OG,

          thanks for the example. I followed the tutorial Bob wrote and all the files have been created, the database tables are in place. I wrote a basic form that is ready to send to the database. Looking at your code I don’t see how it knows to INSERT nor which table it’s to be sent to.

          Sorry, still trying to get my head round how this works!

          I have a component in the core/components/contactGeneral/

          The schema.xml file looks like this.

          <?xml version="1.0" encoding="UTF-8"?>
          <model package="contactGeneral" baseClass="xPDOObject" platform="mysql" defaultEngine="MyISAM" version="1.1">
          	<object class="General" table="general" extends="xPDOSimpleObject">
          		<field key="title" dbtype="varchar" precision="200" phptype="string" null="false" default="" />
          		<field key="firstName" dbtype="varchar" precision="200" phptype="string" null="false" default="" />
          		<field key="SecondName" dbtype="varchar" precision="200" phptype="string" null="false" default="" />
          		<field key="email" dbtype="varchar" precision="200" phptype="string" null="false" default="" />
          		<field key="telephone" dbtype="varchar" precision="200" phptype="string" null="false" default="" />
          		<field key="enquiry" dbtype="mediumtext" phptype="string" null="false" />
          	</object>
          </model>


          The general.map.inc looks like this

          <?php
          $xpdo_meta_map['General']= array (
            'package' => 'contactGeneral',
            'version' => '1.1',
            'table' => 'general',
            'fields' => 
            array (
              'title' => '',
              'firstName' => '',
              'SecondName' => '',
              'email' => '',
              'telephone' => '',
              'enquiry' => NULL,
            ),
            'fieldMeta' => 
            array (
              'title' => 
              array (
                'dbtype' => 'varchar',
                'precision' => '200',
                'phptype' => 'string',
                'null' => false,
                'default' => '',
              ),
              'firstName' => 
              array (
                'dbtype' => 'varchar',
                'precision' => '200',
                'phptype' => 'string',
                'null' => false,
                'default' => '',
              ),
              'secondName' => 
              array (
                'dbtype' => 'varchar',
                'precision' => '200',
                'phptype' => 'string',
                'null' => false,
                'default' => '',
              ),
              'email' => 
              array (
                'dbtype' => 'varchar',
                'precision' => '200',
                'phptype' => 'string',
                'null' => false,
                'default' => '',
              ),
              'telephone' => 
              array (
                'dbtype' => 'varchar',
                'precision' => '200',
                'phptype' => 'string',
                'null' => false,
                'default' => '',
              ),
              'enquiry' => 
              array (
                'dbtype' => 'mediumtext',
                'phptype' => 'string',
                'null' => false,
              ),
            ),
          );
          


          My form is very basic.

          <form action="[[~10~]]" method="post" id="sendContact">
          
          <input type="text" name="obj_firstName" />
          
          <input type="text" name="obj_secondName" />
          
          <input type="text" name="obj_email" />
          
          <input type="text" name="obj_telephone" />
          
          <textarea name="obj_enquiry"></textarea>
          
          <input type="submit" value="send" />
          
          </form>


          I just don’t know what code should be in the snippet on Document 10 where the form takes you to, to then send that data to the Database.

          Does your code tie in with the object that I created?

          $object = null;
          if (!empty($_POST) && isset($_POST['submitMyForm'])) {
              if (isset($_POST['obj_id')) $object = $modx->getObject('MyObject', $_POST['obj_id']);
              if (empty($object)) {
                  $object = $modx->newObject('MyObject');
              }
              $object->fromArray($_POST, 'obj_');
              $object->save();
          }


          A little lost unfortunately but learning.
            Ross Sivills - MD AugmentBLU Edinburgh, Scotland UK
            AugmentBLU - MODX Partner

            BLUcart - MODX Revolution E-Commerce & Shopping Cart
            • 4172
            • 5,888 Posts
            you need to load your package before you can use it.
            xdbo does its update/insert when you call the ->save() - method.

            with ->newObject() you create a new Object, which xpdo will insert.
            with ->getObject() you get an Object and xpdo will do an update (if there was an Object to get).

            this code is from formit2db as an example.
            formit2db is a hook-snippet for formit to save by formit validated form-values to db.

            <?php
            $prefix=$scriptProperties['prefix'];
            $packageName = $scriptProperties['packageName'];
            $tablename = $scriptProperties['tablename'];
            
            $packagepath = $modx->getOption('core_path') . 'components/'.$packageName.'/';
            $modelpath = $packagepath.'model/';
            
            $modx->addPackage($packageName,$modelpath,$prefix);
            $manager= $modx->getManager();
            $generator= $manager->getGenerator();
            $classname = $generator->getClassName($tablename);
            
            //$errorMsg = '<pre>'.print_r($scriptProperties['fields'],true).'</pre>';  
            //$hook->addError('error_message',$errorMsg);  
            
            //$scriptProperties['hook']->formit->config['emailTo']='[email protected]';
            $dataobject=$modx->getObject($classname,array('id'=>$hook->getValue('resource_id')));
            
            if (empty($dataobject)){
                $dataobject = $modx->newObject($classname);
                //$dataobject->set('createdby', $modx->user->get('id'));
            }
            else{
                //$dataobject->set('editedby', $modx->user->get('id'));
            }
            if (!is_object($dataobject) || !($dataobject instanceof xPDOObject)) {
                $errorMsg='Failed to create object of type: ' . $classname;
                $hook->addError('error_message',$errorMsg); 
                return false;
            }
            
            $allFormFields = $hook->getValues();    
            foreach ($allFormFields as $field=>$value){
                
                if ($field !== 'spam' && $field !== 'resource_id'){
                    $dataobject->set($field,$value);
                }       
            }
            
            $dataobject->save();
            
            return true;
              -------------------------------

              you can buy me a beer, if you like MIGX

              http://webcmsolutions.de/migx.html

              Thanks!
              • 25551 ☆ A M B ☆
              • 1,231 Posts
              Thanks Bruno, unfortunately I’m learning how Xpdo etc works so I’m not seeing how this relates to what I’m after. I understand what you’re saying but the example doesn’t relate to what I have created so it’s hard to get my head round how to send the data.

              I’ll keep looking but examples are really needed for simple interaction like sending forms to databases in Rev.

                Ross Sivills - MD AugmentBLU Edinburgh, Scotland UK
                AugmentBLU - MODX Partner

                BLUcart - MODX Revolution E-Commerce & Shopping Cart
                • 25551 ☆ A M B ☆
                • 1,231 Posts
                I tried the following to do some testing and I’m not getting very far. Perhaps some settings are wrong but here’s what I tried.

                $prefix=$scriptProperties['contact_'];
                $packageName = $scriptProperties['contactGeneral'];
                $tablename = $scriptProperties['contact_general'];
                
                $packagepath = $modx->getOption('core_path') . 'components/'.$packageName.'/';
                $modelpath = $packagepath.'model/';
                
                $modx->addPackage($packageName,$modelpath,$prefix);
                $manager= $modx->getManager();
                $generator= $manager->getGenerator();
                $classname = $generator->getClassName($tablename);
                
                
                $show = $modx->getObject('General',array(
                    'title' => 'Mr'
                ));
                
                echo $show->get('title')."<br />\n";
                
                


                The database table is called contact_general, the table has title, firstName, secondName, email, telephone and enquiry fields. The component is called contactGeneral.

                Have I set the $prefix wrong for example? Should I include the "_" or not?

                Thanks for the help.
                  Ross Sivills - MD AugmentBLU Edinburgh, Scotland UK
                  AugmentBLU - MODX Partner

                  BLUcart - MODX Revolution E-Commerce & Shopping Cart
                  • 4172
                  • 5,888 Posts
                  normally you wouldn’t need any prefix, when you are using the same prefix as your modx-tables.

                  But when your tablename is contact_general and your class is named General then you need, I would think.
                  Then check you pathes. Are they ’components/contactGeneral/
                  And your model is in components/contactGeneral/model/
                  Your map-file is created?

                  Then you can try:

                  <?php
                  
                  $prefix='contact_';
                  $packageName = 'contactGeneral';
                  
                  $packagepath = $modx->getOption('core_path') . 'components/'.$packageName.'/';
                  $modelpath = $packagepath.'model/';
                  
                  $modx->addPackage($packageName,$modelpath,$prefix);
                  
                  $show = $modx->getObject('General',array(
                      'id' => 'herePutExistingId'
                  ));
                  
                  echo $show->get('title')."<br />\n";

                    -------------------------------

                    you can buy me a beer, if you like MIGX

                    http://webcmsolutions.de/migx.html

                    Thanks!
                    • 25551 ☆ A M B ☆
                    • 1,231 Posts
                    Thanks Bruno, I didn’t realise that $scriptProperties were the snippet parameters! After adding them to the snippet it actually worked and displayed the data I manually set in the database.

                    The next part is actually sending data from a simple form to the database table. Using your example, instead of displaying data from the database how would I insert data from $_POST?

                    I appreciate your help so far laugh

                    EDIT

                    I just checked the last post by OG and used that code and it’s worked. YEY!!!

                    If I have any more issues I’ll post back here. Once I get this working how I want it I will post a tutorial on what I done.

                    I will be extending it to use mootools, ajax and json as well.
                      Ross Sivills - MD AugmentBLU Edinburgh, Scotland UK
                      AugmentBLU - MODX Partner

                      BLUcart - MODX Revolution E-Commerce & Shopping Cart
                      • 25551 ☆ A M B ☆
                      • 1,231 Posts
                      For some reason, when I send the form it’s just overwriting the row that is in the table rather that creating a new one.

                      Is there a reason for this or do you have to specify that a new row should be created? I have the id field set to auto increment.
                        Ross Sivills - MD AugmentBLU Edinburgh, Scotland UK
                        AugmentBLU - MODX Partner

                        BLUcart - MODX Revolution E-Commerce & Shopping Cart