10

I am working on an extension that must create a component. Until now, my code looks like this:

var item = $models.createNewItem($const.ItemType.COMPONENT);
item.setPublication(pubId);
item.setOrganizationalItem(folderId);
item.setDefaultSubType($const.ComponentSubType.COMPONENT);
item.setSchema(schemaId);
item.setTitle("Test Title");

$evt.addEventHandler(item, "save", HandlerSave);
$evt.addEventHandler(item, "savefailed", HandlerSaveFailed);
$evt.addEventHandler(item, "validatefailed", HandlerValidateFailed);

item.setChanged(true);
item.save(false);

The error I get is: Unable to load XML: XML document must have a top level element.. Unable to update Component (tcm:0-0-0).

I think the problem is creating the xml. I tried with setXml/setContent..., but I don't know how to build the required xml for the component.

1 Answer 1

9

The thing is that you should have new component Xml set to the component before you can save it. Imagine you have a schema with default values associated with folder where this component (will)resides.

You should create component (UI side, just like you did) then load it (it will load xml of created item) and only then do save.

increment = 0;

var publicationId = "tcm:0-xx-1";
var orgItemId = "tcm:xx-yy-2";
var schemaId = "tcm:xx-zz-8";

var item = $models.createNewItem($const.ItemType.COMPONENT);
item.setPublication(publicationId);
item.setOrganizationalItem(orgItemId);
item.setDefaultSubType($const.ComponentSubType.COMPONENT);

var onLoad =  function() {
    $evt.removeEventHandler(item, "load", onLoad);
    var schema = $models.getItem(schemaId);
    item.setSchema(schema.getId());

    var onInstanceDataLoad =  function()
    {
        $evt.removeEventHandler(schema, "instancedataload", onInstanceDataLoad);

        item.setTitle("Test Title " + (increment++));
        item.setContent(schema.getInstanceData(orgItemId, true));
        item.save(true);
   };

   $evt.addEventHandler(schema, "instancedataload", onInstanceDataLoad);

    schema.loadInstanceData(orgItemId);
};

$evt.addEventHandler(item, "load", onLoad);
item.load(true);
3
  • There is nothing created through UI, everything happens on a button click. I tried to use load method of the newly created component, it fires the loading event but it remains unloaded. The only things I modify through UI are some content fields, but I need the rest of the xml of the component which I cannot reach/generate. Commented Sep 25, 2015 at 11:27
  • I`ve added a code sample. Please check. Commented Sep 25, 2015 at 15:03
  • Thank you very much. That helped a lot. Didn't knew the orgItem and schema must be in the same publication. Also, the instancedataload event was pure gold ^^. Commented Sep 29, 2015 at 9:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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