We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 19328
    • 433 Posts
    Hi,
    I'm trying to create a resource through a snippet (hook on Formit form), like this:

    $newResource = $modx->newObject('modResource'); 
    $newResource->set('parent', $parentId);
    $newResource->save();
    return true;
    


    ParentId is a value that comes from the form.
    This works, but only if this parent resource is published. Otherwise, parent is set to zero and the resource appears in the root. Is this normal behavior? Is it possible to set the parent to an unpublished resource?

    This question has been answered by multiple community members. See the first response.

    • discuss.answer
      • 4172
      • 5,888 Posts
      I can't think why this should happen.
      Are you sure $parentId isn't empty at this time?
        -------------------------------

        you can buy me a beer, if you like MIGX

        http://webcmsolutions.de/migx.html

        Thanks!
      • discuss.answer
        if the $parentId is coming from a Formit form, you may need to load the hooks to get at it. Example in FormIt documentation:
        http://rtfm.modx.com/display/ADDON/FormIt.Examples.Custom+Hook

        Otherwise, you may need to grab it via the php $_POST['parentID']. Your code sample didn't show where you were setting $parentId so i can't tell.

        Jason
        • discuss.answer
          Also just for clarification the parent resource in script properties is from the active resource from which the snippet is called. You could call the resource parent object directly as well as based on your posted source we are not certain to how that variable is getting populated.

          To get a resources parent you can use the resource object get method, again as noted this will return the pages parent from where the snippet is being called on.

          $parentId = $modx->resource->get('parent');


            Evo Revo // Ubuntu, CentOS, Win // Apache 2x, Lighttp (Lighty)
            Visit CharlesMx.com for latest news and status updates.
            • 19328
            • 433 Posts
            Ai, now I feel stupid. I tested it again today and now it works just like it should. Yesterday I tried several times and the new resource ended up in the root every time I used the id of a unpublished resource as parent. I must have been doing something else wrong, but I can't figure out what could have caused it.

            Thank you Bruno, Jason and Charles for your help and suggestions! I use a select box on the form with the id's of existing resources as values. The user can choose a resource in this list, and this id gets set as the parent when creating the new resource. Your suggestions did make me realize that I need to have a contingency plan when for some reason the parent ID isn't set in the form. Thanks!