Modx query error

I upgraded to 2.1.3-pl from 2.0.8 version.
    • 7966

    • 90 Posts
    • Send PM

    I upgraded to 2.1.3-pl from 2.0.8 version.

    I am changing the $modx->db->select calls to $modx->db->query in a snippet but I get the following error, when I run the this code.

    PHP Fatal error:  Call to a member function query() on a non-object in ......modx/core/cache/includes/elements/modsnippet/8.include.cache.php on line 42 

    The code on error line is

    $res = $modx->db->query("select id FROM `modx`.`modx_org_access_actions`");

    I also tried adding the «global $modx;» but that doesn’t help.

    Any ideas what could be the problem?

    Thank you

      • 3749

      • 24,544 Posts
      • Send PM

      The db->query() methods have been deprecated for a while and are now gone in the latest versions. You can use PDO, or you can rewrite it using xPDO. There’s some information on that here:

      http://bobsguides.com/revolution-objects.html

        • 7966

        • 90 Posts
        • Send PM

        Quote from: BobRay at Jul 25, 2011, 09:13 AM

        The db->query() methods have been deprecated for a while and are now gone in the latest versions. You can use PDO, or you can rewrite it using xPDO. There’s some information on that here:

        http://bobsguides.com/revolution-objects.html

        Thanks Bob.

        I haven’t noticed that — modX->query() is the new function for $modx->db->select — and mixed it modx->db->query()

        For those not familiar with xpdo like me, below are some functions that might be helpful.

        OBSOLUTE —> $res = $modx->db->select($selectSQL , $fromSQL, $whereSQL , $OrderBy);
        NEW —> $res = $modx->query(«select * from table Where field1 =’a’»);

        OBSOLUTE —> $recordCount= $modx->db->getRecordCount($res);
        NEW —> $recordCount = $res->rowCount();

        OBSOLUTE —> $rows = $modx->db->makeArray( $res );
        NEW —> $rows = $res->fetchAll();

        OBSOLUTE —> $row = $modx->db->getRow($res);
        NEW —> $row = $res->fetch();

          • 36483

          • 11 Posts
          • Send PM

          Very helpful, thanks smiley

          Here is an example of code so you can get back to work. This change prevented me from developing new stuff for like 2 weeks. Enjoy, world.

          $results = $modx->query("SELECT * from your_table");
           
          $recordCount = $results->rowCount();
          echo $recordCount;
           
          foreach($results as $row)
          {
              echo $row['test'];
          }

          [ed. note: andrewnormore last edited this post 11 years, 5 months ago.]

          Please tell me where?:

          // harden it
          require_once(‘../../../manager/includes/protect.inc.php’);

          /**

          • EASY 2 GALLERY
          • @uses file to show the image for Easy 2 Gallery Module
          • @author Cx2 inteldesign@mail.ru
          • @author Temus temus3@gmail.com
          • @author goldsky goldsky@fastmail.fm
            */
            error_reporting(0);

          if (empty($_GET[‘fid’]) || !is_numeric($_GET[‘fid’])) {
          $text = isset($_GET[‘text’]) ? $_GET[‘text’] : ‘Error’;
          sh_err($text);
          }

          // MODx config
          require_once ‘../../../manager/includes/config.inc.php’;

          $modx->db->connect($database_server, $database_user, $database_password) or
          sh_err(‘MySQL connect error’);
          $modx->db->select_db(str_replace(‘`’, », $dbase));
          $modx->db->query(«{$database_connection_method} {$database_connection_charset}»);

          // e2g’s configs
          $e2g_res = $modx->db->query(‘SELECT * FROM ‘ . $table_prefix . ‘easy2_configs’);
          if (!$e2g_res)
          sh_err(‘MySQL query error for configs’);
          else {
          while ($row = $this->modx->db->getRow($e2g_res)) {
          $e2g[$row[‘cfg_key’]] = $row[‘cfg_val’];
          }
          }

          // get the image file ID
          $id = (int) $_GET[‘fid’];
          $res = $modx->db->query(‘SELECT * FROM ‘ . $table_prefix . ‘easy2_files WHERE id=’ . $id);
          if (!$res)
          sh_err(‘MySQL query error for files’);

          // get the filename
          $row = $this->modx->db->getRow($res);
          $filename = $row[‘filename’];

          $res = $modx->db->query(‘SELECT A.cat_id, A.cat_name ‘
          . ‘FROM ‘ . $table_prefix . ‘easy2_dirs A, ‘ . $table_prefix . ‘easy2_dirs B ‘
          . ‘WHERE B.cat_id=’ . $row[‘dir_id’] . ‘ ‘
          . ‘AND B.cat_left BETWEEN A.cat_left AND A.cat_right AND A.cat_level > 0 ‘
          . ‘ORDER BY A.cat_left’
          );
          if (!$res)
          sh_err(‘MySQL query error’);

          // get the file’s path
          $path = »;
          while ($l = $modx->db->fetch_row($res)) {
          $path .= $l[1] . ‘/’;
          }

          $fp = ‘../../../’ . $e2g[‘dir’] . $path . $filename;
          $fp = utf8_decode($fp);

          /**

          • WATERMARK
            */
            if ($e2g[‘ewm’] != 0) {
            $inf = getimagesize($fp);

            if ($inf[2] == 1)
            $im = imagecreatefromgif($fp);
            elseif ($inf[2] == 2)
            $im = imagecreatefromjpeg($fp);
            elseif ($inf[2] == 3)
            $im = imagecreatefrompng($fp);
            else
            sh_err(‘Imagecreate error’);

            if ($e2g[‘wmtype’] == ‘text’) {
            // X
            $len = strlen($e2g[‘wmt’]);
            if ($e2g[‘wmpos1’] == 3)
            $x = $inf[0] — 10 — ($len * 6);
            elseif ($e2g[‘wmpos1’] == 2)
            $x = ($inf[0] — ($len * 6)) / 2;
            else
            $x = 10;

            // Y
            if ($e2g['wmpos2'] == 3)
                $y = $inf[1] - 20;
            elseif ($e2g['wmpos2'] == 2)
                $y = ($inf[1] / 2) - 5;
            else
                $y = 10;
            
            $textColor = imagecolorallocate($im, 0, 0, 0);
            imagestring($im, 2, $x - 1, $y, $e2g['wmt'], $textColor);
            imagestring($im, 2, $x + 1, $y, $e2g['wmt'], $textColor);
            imagestring($im, 2, $x, $y - 1, $e2g['wmt'], $textColor);
            imagestring($im, 2, $x, $y + 1, $e2g['wmt'], $textColor);
            imagestring($im, 2, $x + 1, $y + 1, $e2g['wmt'], $textColor);
            imagestring($im, 2, $x - 1, $y - 1, $e2g['wmt'], $textColor);
            
            $textColor = imagecolorallocate($im, 255, 255, 255);
            imagestring($im, 2, $x, $y, $e2g['wmt'], $textColor);
            

            } elseif ($e2g[‘wmtype’] == ‘image’) {

            $wmfp = '../../../' . str_replace('../', '', $e2g['wmt']);
            if (!file_exists(realpath($wmfp))) {
                sh_err('WM file not found');
            }
            
            $wminfo = getimagesize($wmfp);
            
            if ($wminfo[2] == 1)
                $wmi = imagecreatefromgif($wmfp);
            elseif ($wminfo[2] == 2)
                $wmi = imagecreatefromjpeg($wmfp);
            elseif ($wminfo[2] == 3)
                $wmi = imagecreatefrompng($wmfp);
            else
                sh_err('WM error');
            
            imageAlphaBlending($wmi, false);
            imageSaveAlpha($wmi, true);
            $wm_w = imageSX($wmi);
            $wm_h = imageSY($wmi);
            
            // X
            $len = strlen($e2g['wmt']);
            if ($e2g['wmpos1'] == 3)
                $x = $inf[0] - 10 - $wm_w;
            elseif ($e2g['wmpos1'] == 2)
                $x = ($inf[0] - $wm_w) / 2;
            else
                $x = 10;
            
            // Y
            if ($e2g['wmpos2'] == 3)
                $y = $inf[1] - 10 - $wm_h;
            elseif ($e2g['wmpos2'] == 2)
                $y = ($inf[1] / 2) - $wm_h;
            else
                $y = 10;
            
            
            imagecopy($im, $wmi, $x, $y, 0, 0, $wm_w, $wm_h);
            imagedestroy($wmi);
            

            }

            // SAVE
            //header(«Content-type: image/jpeg»);
            //imagejpeg($im);
            //imagedestroy($im);

            ob_start();
            header(‘Last-Modified: ‘ . date(‘r’));
            header(‘Accept-Ranges: bytes’);
            header(‘Content-type: image/jpeg’);
            header(‘Content-Disposition: inline; filename=»‘ . $filename . ‘»‘);
            imagejpeg($im);
            imagedestroy($im);
            header(‘Content-Length: ‘ . ob_get_length());
            ob_end_flush();
            } else {
            header(‘Content-type: image/jpeg’);
            header(‘Location: ‘ . $fp);
            exit();
            }

          function sh_err($text) {
          $w = isset($_GET[‘w’]) ? $_GET[‘w’] : 300;
          $h = isset($_GET[‘h’]) ? $_GET[‘h’] : 200;
          $textHeight = isset($_GET[‘th’]) ? $_GET[‘th’] : 5;

          header("Content-type: image/png");
          $im = @imagecreate($w, $h)
                  or die("Cannot Initialize new GD image stream");
          $bgColor = imagecolorallocate($im, 255, 255, 255);
          $textColor = imagecolorallocate($im, 233, 14, 91);
          $text = trim($text) != '' ? $text : "Image error";
          $y = $h/2 - $textHeight * 4;
          $textWidth = imagefontwidth($textHeight) * strlen($text);
          $center = ceil($w / 2);
          $x = $center - (ceil($textWidth / 2));
          imagestring($im, $textHeight, $x, $y, $text, $textColor);
          imagepng($im);
          imagedestroy($im);
          exit();
          

          }

          xPDO::query¶

          Выполняет инструкцию SQL, возвращая набор результатов в виде объекта PDOStatement.

          Совет
          Это может быть хорошим способом создания отчетов, не беспокоясь о сложном синтаксисе, обычно требуемом xPDO.

          Синтаксис¶

          API Docs: Смотри https://api.modx.com/revolution/2.2/db_core_xpdo_xpdo.class.html#xPDO::query()

          xPDOObject|false query (string $statement)
          

          $statement

          Оператор SQL для подготовки и выполнения. Данные внутри запроса должны быть правильно экранированы.

          Примеры¶

          Выберите одну запись¶

          Вот простой запрос для извлечения одной строки из базы данных. Обратите внимание, что вы обычно используете getObject или getCollection извлечения данных из встроенных таблиц MODX.

          xPDOObject|false query (string $statement)

          $statement

          Оператор SQL для подготовки и выполнения. Данные внутри запроса должны быть правильно экранированы.

          $result = $modx->query("SELECT * FROM modx_users WHERE id=1");
          if (!is_object($result)) {
             return 'No result!';
          }
          else {
             $row = $result->fetch(PDO::FETCH_ASSOC);
             return 'Result:' .print_r($row,true);
          }
          

          Использование PDO::FETCH_ASSOC заставит результат быть ассоциативным массивом:

          Array
          (
              [id] => 1
              [username] => my_user
              [password] => xxxxxxxxxxxxxxxxxxx
              // ...
          )
          

          Без этого результаты представляют собой смесь ассоциативного и регулярного массивов:

          Array
          (
              [id] => 1
              [0] => 1
              [username] => my_user
              [1] => my_user
              [password] => xxxxxxxxxxxxxxxxxxxxxxx
              [2] => xxxxxxxxxxxxxxxxxxxxx
              // ...
          )
          

          Нет однострочников!
          Доступное для PDO объединение методов в одну строку невозможно с xPDO. Следующее не будет работать:

          $row = $modx->query("SELECT * FROM cms_users WHERE id=1")->fetch();

          Выбор нескольких записей¶

          PDO использует ленивый загрузчик, поэтому вы не можете просто распечатать все результаты сразу. Вместо этого вы перебираете каждый результат в наборе, используя цикл, например

          $results = $xpdo->query("SELECT * FROM some_table");
          while ($r = $results->fetch(PDO::FETCH_ASSOC)) {
                  print_r($r); exit;
          }
          

          Цитирование входов¶

          Для отдельных запросов, основанных на пользовательском вводе, вы должны вручную указывать входные строки.

          $username = $modx->quote($username);
          $sql = "SELECT * FROM modx_users WHERE username = $username";
          $result = $modx->query($sql);
          $row = $result->fetch(PDO::FETCH_ASSOC);
          return print_r($row,true);
          

          Функция цитаты может принимать 2-й аргумент, который вы можете использовать для точного цитирования целых чисел.

          • PDO::PARAM_INT для цитирования целых чисел
          • PDO::PARAM_STR для цитирования строк (по умолчанию)
          $id = $modx->quote(1, PDO::PARAM_INT);
          $sql = "SELECT * FROM cms_users WHERE id = $id";
          $result = $modx->query($sql);
          $row = $result->fetch(PDO::FETCH_ASSOC);
          return print_r($row, true);
          

          Выбор коллекции¶

          Вот простой запрос для извлечения нескольких строк из базы данных. Обратите внимание, что вы обычно используете getObject для извлечения данные из таблиц MODX.

          $output = '';
          $sql = "SELECT * FROM modx_users";
          foreach ($modx->query($sql) as $row) {
              $output .= $row['username'] .'<br/>';
          }
          return $output;
          

          Вы также можете использовать метод fetchAll() для возврата массива массивов (то есть набора записей):

          $output = '';
          $sql = "SELECT * FROM modx_users";
          $result = $modx->query($sql);
          $data = $result->fetchAll(PDO::FETCH_ASSOC);
          return $data;
          

          Fetch Style¶

          В http://php.net/manual/en/pdostatement.fetch.php перечислены доступные константы, которые влияют на способ возврата ваших результатов:

          • PDO::FETCH_ASSOC: возвращает массив, проиндексированный по имени столбца, как возвращено в вашем наборе результатов
          • PDO::FETCH_BOTH (по умолчанию): возвращает массив, проиндексированный как по имени столбца, так и по номеру столбца с 0 индексами, как возвращено в вашем наборе результатов
          • PDO::FETCH_BOUND: возвращает TRUE и присваивает значения столбцов в вашем наборе результатов переменным PHP, к которым они были привязаны с помощью метода PDOStatement :: bindColumn ()
          • PDO::FETCH_CLASS: возвращает новый экземпляр запрошенного класса, сопоставляя столбцы результирующего набора с именованными свойствами в классе. Если fetch_style включает в себя PDO::FETCH_CLASSTYPE (например,PDO::FETCH_CLASS | PDO::FETCH_CLASSTYPE), тогда имя класса определяется по значению первого столбца.
          • PDO::FETCH_INTO: обновляет существующий экземпляр запрошенного класса, сопоставляя столбцы результирующего набора с именованными свойствами в классе
          • PDO::FETCH_LAZY: объединяет PDO::FETCH_BOTH и PDO: FETCH_OBJ, создавая имена переменных объекта по мере их доступа
          • PDO::FETCH_NUM: возвращает массив, проиндексированный по номеру столбца, как возвращено в вашем наборе результатов, начиная с столбца 0
          • PDO::FETCH_OBJ: возвращает анонимный объект с именами свойств, которые соответствуют именам столбцов, возвращаемых в вашем наборе результатов.

          Подготовленные заявления¶

          Видеть

          • http://php.net/manual/en/pdo.prepare.php
          • http://php.net/manual/en/pdostatement.execute.php

          Смотрите также¶

          • Retrieving Objects
          • xPDO.getObject
          • xPDO.getObjectGraph
          • xPDO.getCollection
          • xPDO.getCollectionGraph
          • xPDO.getIterator
          • xPDO

          There are a number of nasty MODX errors that have bitten me repeatedly. I thought I would document some of then here to help other MODX users. Note that these are not bugs in MODX, they are common and not-so-common errors that people make when working with MODX. No matter what level of proficiency you attain in working with MODX, some of these will happen to you and a few of them are very hard to spot, especially when it’s three in the morning and you’ve been coding all night on a machine with a high-resolution screen and tiny type.

          I’ve tried to organize them so that the newbie errors are at the top.

          The Wayward Resource

          You’ve recently edited a Resource and when you look for it later it’s gone from the Resource tree. You haven’t messed with permissions at all. Where did it go? You may have accidentally dragged it with the mouse and put it under a container document. It’s still there, but you won’t see it until you expand the container.

          Back-ticks

          All snippet properties in MODX snippet tags should be surrounded by back-ticks: &propertyName=`value` — never single or double quotes. The back-tick symbol on most keyboards is at the upper left and is typed with shift-~. This is by far the most common error made by new users of MODX.

          The Missing Question Mark

          If a snippet tag has properties, there must be a question mark immediately after the snippet name,
          followed by a space:

          [[SnippetName? &propertyName=`value`]].

          If you forget to put one in, you can stare at the snippet properties forever trying to figure out why they’re not reaching the snippet.

          The extra space bug

          In some versions of MODX a snippet property with a space on either side of the equals sign will confuse the parser. This is especially
          difficult for experienced coders who are used to
          putting a space on both sides to make the code more readable. Snippet tags with properties should always look like this:

          [[SnippetName? &propertyName=`value`]]

          or, if you want the snippet uncached

          MODX Evolution:

          [!SnippetName? &propertyName=`value`!]

          MODX Revolution:

          [[!SnippetName? &propetryName=`value`]]

          The Mysterious Cache

          MODX saves documents, chunks, templates, plugins, and snippets in the MODX cache so they can be retrieved more quickly. That means that sometimes you can make a change and have the change not show up when you preview a document. This is particularly annoying when you fix an HTML, CSS, or PHP error, then when the fix appears not to work, you make another change that actually breaks something. Now, you clear the cache and things are worse than when you started.

          The Mangled Ampersand

          If you are editing a snippet in the MODX Manager using the Rich Text Editor (e.g., TinyMCE), the editor will helpfully replace ampersands with this: &amp;amp;. The MODX parser is smart enough to decompose that, but if you save the snippet multiple times, you can end up with &amp;amp;&amp;amp;propertyName, which is too much for the parser. The solution is easy enough: never, never use the RTE when editing code.

          The Dangling Snippet

          In some versions of MODX Evolution, long snippets have to be written on a single line with no carriage returns. It’s OK if they wrap automatically in the editor, but if you press Enter, you’ll break not just the line, but the snippet as well. (Contributed by Dimmy.)

          The Add-on Snippet Screen of Confusion

          In MODX Revolution, your getResources, Wayfinder, or other add-on snippet does nothing but output a whole lot of what looks like confusing PHP code. That’s because the default behavior of some snippets is to dump the internals of the current object if no Tpl chunks are supplied. It means that either you left out the &tpl property(s),
          or you misspelled the name. (Contributed by odeclass.)

          The Missing Output Bug I

          Why isn’t your snippet (or someone else’s snippet that you’ve installed) producing any output? One possibility is that you’ve misspelled its name. Snippet names are case-sensitive in MODX and it’s easy to get then wrong. I can never remember whether it’s EZfaq or ezFAQ. In MODX Revolution, FormIt works, but Formit doesn’t. And, it’s getResources, not GetResources.

          With your own snippets, always start with this code:

          <?php
          $output = «The snippet is running»;
          return $output;

          Don’t start working on the code until you see some output.

          The Missing Output Bug II

          You are writing your own snippet and you can’t see anything wrong with it, but nothing appears on the page where the snippet tag is placed. It’s because you forgot to return anything from the snippet. It’s working fine (maybe), but since nothing is returned, there’s no output for MODX to display. The accepted method for returning output from a snippet is to put this at the end:

          return $output;

          The best way to avoid this bug is to use the code in the example just above whenever you create a snippet. That way the «return $output» statement will always be there for you.

          The missing Output Bug III

          You’re trying to use a snippet like Wayfinder or getResources to display information about some pages. The pages are there, but they’re not showing up. In order for them to be seen, they have to be published, not protected by any permission rules, and the «Hide From Menus» checkbox must be unchecked. In Revolution, you may also have to check or uncheck the «Container» checkbox. In MODX Evolution, that checkbox is set automatically if the resource has children. In Revolution, it’s up to you to check it if you want snippets to consider it a container. (Contributed by odeclass.)

          Dude, where’s my CSS file?

          You have PHP code that refers to a CSS, JS, or image file (e.g., regClientCSS()) but your browser refuses to find the file even though the path looks correct when you view the source of the page. It’s because you’ve used MODX_ASSETS_PATH when you should have used MODX_ASSETS_URL. Unlike included files, which are specified by the file path, all web resources are referenced by URL.

          The Impossible URL

          MODX just won’t find the page or image you want and you’re sure you have the path and file name right. It might be because your template doesn’t have a base href statement to tell your browser where to find it. Every MODX template should have this statement in the <head> section:

          MODX Evolution:

          <base href=»[(site_url)]» />

          MODX Revolution:

          <base href=»[[!++site_url]]»

          The Intermittent Output Modifier

          You’re trying to use a PHX-like output modifier to control the output of a placeholder or other tag in MODX Revolution. Sometimes it works; sometimes it doesn’t. You’re probably calling it cached, so you’re only seeing what happened the first time it was parsed. If that matches what you expect, it looks like it’s working, otherwise not. Use an exclamation point to make the tag uncached so it will be evaluated every time the parser sees it:

          [[!+fi.error.name:notempty=`error`]]

          Note that in MODX Revolution, any tag can be uncached with the exclamation point. (Contributed by odeclass.)

          The Friendly URL Conundrum

          You’ve tried everything, but you just can’t get Friendly URLs to work. The problem is that, in order for FURLs to work properly, every one of these conditions have to be met:

          • Friendly URLs must be enabled in the Manager’s configuration section
          • The ht.access file must be renamed to .htaccess
          • The FURL section of .htaccess must be uncommented
          • The rewrite base in .htaccess must be set correctly
          • The rewrite engine must be enabled (it’s off by default in XAMPP)
          • You need to enable the rewrite engine in the correct php.ini file
          • All documents need to have an alias
          • The documents must be published
          • The documents must not be hidden by any permission rules
          • You may need the base href line from the section above

          The correct php.ini file can be found by looking in the Reports section of the Manager for System Information and clicking on the «view» link next to PhpInfo. The PhpInfo screen will show you the path of the php.ini file PHP is using. Remove the comments in front of the following two lines:

          LoadModule rewrite_module
          modules/mod_rewrite.so
          

          The Friendly URL Conundrum II

          I ran into this one recently. I went back to work on a local version of a site where FURLs had been working the last time I used it, but they weren’t working now. I checked everything but the php.ini file. I knew it couldn’t be that because they had been working before. After more time than I care to admit, I finally realized that a while back, I had reinstalled XAMPP. The install was unsuccessful and I had to uninstall it completely and start over. That undid my change to php.ini.

          The Phantom Property

          One of your snippet properties doesn’t seem to have any effect. This is just like the Missing Output Bug I,
          except that you’ve misspelled the name of the property rather than the name of the snippet. It’s particularly insidious for properties that have some form of the word «id» in the name (is it «StartId» or «startID»)? For Wayfinder, it’s «StartId».

          The Field Name Disaster

          You’re trying to use a query to retrieve a MODX object from the database. You know it’s there, but it just won’t be found. It’s because you’ve forgotten the name of the object’s «name» field. The «name» field for documents is «pagetitle»; and lest you think this bug only bites beginners, what prompted me to create this page was spending over an hour earlier this evening wandering through the MODX and xPDO code with a debugger trying to figure out why I couldn’t retrieve a Revolution document that I absolutely knew the name of with this code:

          $resource=$modx->getObject('modResource',array('name'=>'NewsPublisher'));

          The Unfindable Resource or Element

          This is similar to the error above, but you have the correct field name and the object still can’t be found. You have an array of pagetitles or element names and you’re trying to loop through them to get the objects using code something like this:

          $nameList = array (
              'page1' => 'Login',
              'page2' => 'Register',
          };
          
             foreach($nameList as $key => $value) {
                 $resource = $modx->getObject('modResource', array('pagetitle' => '$value'));
                 if (! $resource) {
                     $output .= 'WTF? Cannot find: ' . $value;
                 }
          
             }
             return $output;
          

          The snippet prints out the error message, each time giving the correct pagetitle. WTF indeed. The problem is that you’ve put $value in quotes. MODX is dutifully looking repeatedly for a non-existent document with a pagetitle of «$value».

          The $_POST Man Never Even Rings Once

          This is yet another version of the error above. You know the values you want are in the $_POST array, but the code to find them is never successful:

          $fields = array (
              'name',
              'address',
              'phone',
          };
          
          foreach($fields as $field) {
              if (in_array($field, array_keys($_POST)) {
                  $finalFields[$field] = $_POST['$field'];
             }
          
          return print_r($finalFields, true);
          

          The array is always empty. It’s because the $field variable is in quotes in the final array reference: $_POST[‘$field’].

          The Phantom Property II

          This is a particularly insidious bug for more advanced coders. If you’re bouncing back and forth between your PHP code and a snippet tag in MODX with many properties, it’s easy to accidentally put a property in the snippet tag that looks like this:

          $propertyName=`value`

          MODX doesn’t recognize the property (or any that follow it) as properties. The snippet will run fine,
          but those properties will have no effect because all properties must start with an ampersand, not a dollar sign.

          The Double Dollar Sign

          Because PHP has the concept of «variable variables», you can accidentally start a variable name with two dollar signs: $$variableName. PHP won’t complain, but the variable won’t do its job properly.

          The Devil’s Dot

          This one is particularly insidious. Very few code editors will catch it because it’s still valid PHP. It involves a dot where there should be a comma:

          $modx->addPackage(‘quotes’, $path . ‘model/’, ‘bobs_’);

          It should be:

          $modx->addPackage(‘quotes’, $path , ‘model/’, ‘bobs_’);

          The (almost) Duplicate Function

          This might be the most insidious of all, though it’s unlikely to happen to you. Let’s say you have a function in a plugin that is really handy — in this case a function that writes to a log file. You copy the code to another plugin and change it slightly to write to another log file. Because the plugins are attached to the same System Event and the function names are the same, you wrap the function definitions in if ( !function_exists() ) code.

          This seems to work fine for each plugin when tested individually. When both are enabled, however, the second one to execute writes to the wrong log file.
          Because the function is already defined, the function definition in the second plugin is ignored. Since you’re just checking the second log file (nothing is written to it) and you already know the function works, you think that there’s something wrong with the rest of the plugin. Eventually, you figure it out, but by that time, you’re nearly bald from pulling your hair out.

          The solution is to make the functions identical and pass the name of the log file as an argument (doh). It’s easy to think of plugins as independent pieces of code, but if they’re attached to the same System Event, they’re really not. Functions, variables (including $_SYSTEM variables), and placeholders can all collide leading to some very frustrating debugging.

          Update User Insanity

          This is not really a MODX error, but it’s certainly insidious. You want to update a particular User’s information so you go to Security | Manage Users, right-click on the user and select «Update User». MODX goes completely nuts and begins reloading the page over and over. It never stops. The problem is that you have a password manager (e.g. LastPass or Roboform) and it’s set to autologin to your MODX site. When the password manager sees the Update User page, it thinks it’s time to log in because it’s a form with username and password fields for a site it knows. Every time it submits the form, it’s time to log in again. The solution is to disable the password manager whenever you want to update users.

          The Invisible Transport Package

          You want to move an extra from one install of MODX to another. You copy the transport package from one core/packages directory to the other, and then «Search Locally for Packages,» but the package just won’t show up. The problem is that in the core packages directory, there are two files for each package. You’ve copied the wrong one. You need to copy the one that ends in .zip. The other file is created by MODX when the package is installed. It won’t be recognized as a Transport Package by Package Manager because it’s not a Transport Package.

          Setup Goes Down

          This one is caused by programmer error (in one case, mine) and it’s relatively rare. It’s frustrating and fairly insidious. You upgrade MODX, but when you run Setup, it crashes with a confusing error message. The problem is that a plugin you have installed is connected to an event that fires when a User or Resource is saved. If the particular MODX upgrade saves a User or Resource, the relevant event will fire and the plugin will execute. The plugin then tries to access a $user or

          $resource object that doesn’t exist during Setup and PHP throws a fit. The solution is to disable the plugins in the Database using PhpMyAdmin. Just put a 1 in the disabled field for every plugin. If you know which plugin it is, a note to the developer would be appreciated.

          The Crashing Element

          If your host upgrades PHP, E_NOTICE errors can be turned on. Very trivial problems can then trigger E_NOTICE errors. If error reporting is turned on (and it shouldn’t be on a production site) you will see the errors, but if it’s off, MODX tends to die quietly. Here’s a most insidious example. In a transport package, I accidentally set the empty properties field of every element to ‘array()’ (a string) instead of array() (and empty array). Every element in the package crashed MODX with a tidal wave of E_NOTICE errors. If I hadn’t had error reporting on for my development environment, I might never have figured it out.

          Понравилась статья? Поделить с друзьями:
        • Modx formit error message
        • Modx favicon как изменить
        • Modx error in xpdoconnection connect
        • Modx error 500 internal server error
        • Modx encountered the following error while attempting to parse the requested resource