1

I've created a database table that I am trying to add information too with a onBeforeSaveElement() hook.

For some reason, although it is telling me that the rows have been added in the $result, there is no records being added. Interestingly, if I run the page an then manually add a record to the database table, the id has been incremented by the amount of rows $result says it has added.. so it seems that the rows are being added then instantly deleted?

Thanks

SQL

CREATE TABLE `craft_lsclearance` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `path` text,
  `cleared` int(11) DEFAULT '0',
  `dateCreated` datetime DEFAULT NULL,
  `dateUpdated` datetime DEFAULT NULL,
  `uid` char(36) DEFAULT '',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=229 DEFAULT CHARSET=latin1;

Function

craft()->on('elements.onBeforeSaveElement', function(Event $event)
    {
        $element = $event->params['element'];
        $paths = craft()->plugin->getPaths($element);

        foreach ($paths as $path) {
            $newPath = preg_replace('/site:/', '', $path['path'], 1);

            if ($path['locale'] != 'en') {
                $newPath = $path['locale'] . '/' . $newPath;
            }

            $model[] = array(UrlHelper::getSiteUrl($newPath));
        }

        $result = craft()->db->createCommand()->insertAll('lsclearance', array('path'), $model);

        print_r($model);
        echo '<br /> Inserted: ' . $result . 'row(s)';

        exit;

    }
);

Output

Array ( 
  [0] => Array ( [0] => http://mydomain.com/ ) 
  [1] => Array ( [0] => http://mydomain.com/ ) 
  [2] => Array ( [0] => http://mydomain.com/results?q=regatta+ac ) 
  [3] => Array ( [0] => http://mydomain.com/watch/regatta-ac-titanium/19225 ) 
  [4] => Array ( [0] => http://mydomain.com/mens-watches ) 
  [5] => Array ( [0] => http://mydomain.com/mens-watches/p2 ) 
  [6] => Array ( [0] => http://mydomain.com/watch/ac-ii/19282 ) 
) 
Inserted: 7 rows
1

All of the element saving events (like onBeforeElementSave(), onElementSave(), onBeforeSaveEntry()..., etc. are all wrapped in a database transaction (specifically encapsulated in the CDbTransaction class).

When you call exit, you're killing the request and never giving a chance for the transaction to commit to the database.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.