Jump to main content Jump to doc navigation

What Does the Rule Do?

This rule checks whether another object exists. If that object doesn’t exist, validation on the current object fails. The object is specified by the className and pk attributes in the rule schema definition.

[!NOTE] pk is a fixed value written into the schema, not a reference to a field of the object being validated. The rule therefore always checks the same row, which is rarely what you want. To validate the current object’s field, use the xPDOForeignKeyConstraint rule instead.

Using the Rule

First, our model:

<model package="Test" baseClass="xPDO\Om\xPDOObject" platform="mysql"
    defaultEngine="InnoDB" version="3.0">
    <object class="myTest" table="test" extends="xPDO\Om\xPDOSimpleObject">
        <field key="name" dbtype="varchar" precision="255"
            phptype="string" default="" null="false" />

        <validation>
            <rule field="name"
                name="chunkExists"
                type="xPDOValidationRule"
                rule="xPDOObjectExistsValidationRule"
                pk="12"
                className="MODX\Revolution\modChunk"
                message="The Chunk does not exist, so this object cannot be saved."
            />
        </validation>
    </object>
</model>

Generate the model from the XML schema, then validate an object in a Snippet:

$output = '';
$modx->addPackage('Test', '/path/to/components/test/model/');
$obj = $modx->newObject('Test\myTest');
$validator = $obj->getValidator();
if (!$validator->validate()) {
    foreach ($validator->getMessages() as $errorMsg) {
        $output .= $errorMsg['message'];
    }
}
return $output;

This will display:

The Chunk does not exist, so this object cannot be saved.

See Also

  1. xPDOForeignKeyConstraint
  2. xPDOMaxLengthValidationRule
  3. xPDOMaxValueValidationRule
  4. xPDOMinLengthValidationRule
  5. xPDOMinValueValidationRule
  6. xPDOObjectExistsValidationRule

Support the team building MODX with a monthly donation.

The budget raised through OpenCollective is transparent, including payouts, and any contributor can apply to be paid for their work on MODX.

Backers

  • modmore
  • STERC
  • Digital Penguin
  • Jens Wittmann – Gestaltung & Entwicklung
  • CrewMark
  • Fabian Christen
  • Sepia River Studios
  • Dannevang Digital
  • Alex
  • A. Moreno
  • Chris Fickling
  • Stéphane Jäggi
  • Murray Wood
  • Anton Tarasov
  • JT Skaggs
  • deJaya
  • Lefthandmedia
  • eydolan
  • Following Sea
  • Guido Gallenkamp
  • YJ
  • Raffy
  • Snow Creative
  • Nick Clark
  • Guest
  • Helen
  • krisznet
  • Yanni
  • Richard

Budget

$194 per month—let's make that $500!

Learn more