Item Ajax Framework

From VYRE

Jump to: navigation, search

The Item Ajax Framework is used to asynchronously create and edit Items in Unify in the frontend without forcing form submission and page redirects. This aims to provide a number of benefits to the Unify system including:

  • allowing site developer the option of building item creation facilities on a page that does not involve iframes or popups.
  • the ability to create items without the end user knowing that anything has happened.
  • the option to edit items without a page redirect.

N.B Same as with the Item edit portlet, a user will need to be logged in to be creating items. If a guest user needs to be creating items through AJAX use the Guest Account

Item Ajax Framework
type: javascripscript Framework
module: Publishing module


Contents

Getting Started

The item ajax framework will be included in VYRE Unify 4.6.3 and above. We will see in this section basic and common examples about how to use the framework.

Including the Javascript files

This script is reliant on jQuery. You need to include it on your page. If you do not have jQuery or want to use another library, you will have to rewrite the methods from VYRE.Utils.ItemAjax.

NOTE: if you want to use Item Ajax Framework on some older sites built with Forsight, you cannot use jQuery versions above 1.3.2 as there are conflicts with Forsight scripts. An alternative is to replace 'isObject' method in item-ajax.js with 'isPlainObject' implementation from jQuery 1.4 [1] and you should be good to go with Item Ajax and jQuery 1.3.2.

<!-- Here I use the google CDN, you can replace this with your local jQuery script -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.js"></script>
 
<!-- JSON utility -->
<script type="text/javascript" src="/javascript/pub_module/JSONstring.js"></script>
 
<!-- Item Ajax Framework -->
<script type="text/javascript" src="/content_module/js/item-ajax.js"></script>

Item creation example

Creating an item is really simple. First you need to create an item object, with the required information, then you use the VYRE.ItemService object to persist it on the server and passing it a callback function

    var item = new VYRE.Item ({
        name: 'my test item',
        description: 'my description',
        collectionSchema: 123
    }),
 
    callback = function (data) {
        if (data.response.overallResult === 'successful') { // Check for errors
            console.log('item ajax callback response:', data);
        } else {
            console.log('ERROR: Item creation failed', data.response.error);
        }
    };
 
    VYRE.ItemService.createAndActivate (item, callback);

NOTE! YOU SHOULD ALWAYS CHECK THE RESPONSE IS SUCCESSFUL BEFORE COMMENCING ANY FURTHER ACTION WITH A CALLBACK

Item update example

Updating an item is quite similar, only the required set of information changes. In this example, we will just add a metadata attribute.

var item = new VYRE.Item({
	id: '12345',
	version: 'active'
});
item.addMetadata ({
	'comment': 'updated using item ajax framework'
});
 
callback = function (data) { console.log('item ajax callback response:', data); }
 
VYRE.ItemService.createAndActivate(item, callback);

Item deletion example

To delete an item, only the action changes:

var item = new VYRE.Item ({
	id: '12345',
	version: 'active'
});
 
callback = function (data) { console.log('item ajax callback response:', data); }
 
VYRE.ItemService.remove(item, callback);

Adding metadata and content

This example shows how to add content and metadata to an item.

var item = new VYRE.Item({
	name: 'my test item',
	description: 'my description',
	collectionSchema: 123
});
 
item.addContent({
             comment: 'test',
             body: 'test test test'})
	.addMetadata({
            completed: 1,
            participants: 13})
 
callback = function (data){ console.log('item ajax callback response:', data); }
 
VYRE.ItemService.createAndActivate(item, callback);

Adding/removing taxonomy

This example shows how to add and remove taxonomy to an existing item.

var item = new VYRE.Item({
	id: '12345',
        version:'active'
});
 
item.removeTaxonomy('/path/to/category1')
       .addTaxonomy(['/path/to/category2', '/path/to/category3'])
 
callback = function (data){ console.log('item ajax callback response:', data); }
 
VYRE.ItemService.createAndActivate(item, callback);

Adding/removing item links and user links

This example shows how to add/remove item links and user links to an existing item.

var item = new VYRE.Item({
	id: '12345'
        version:'active'
});
 
item.addUserLink(11, [1234, 5678])
        .removeUserLink(11, 765)
        .addItemLink(13, [4563,4567])
	.removeItemLink(13, [8765,987]);
 
callback = function (data){ console.log('item ajax callback response:', data); }
 
VYRE.ItemService.createAndActivate(item, callback);

VYRE.Item

This object is the main object of the framework. it defines a Unify Item. We will see here the constructor and the different methods available.

Constructor

The VYRE.Item constructor can be used for creating or updating an item. When creating a new item - 'name, 'description' and 'collectionSchema' are required.

var item = new VYRE.Item({
	name: 'my test item',
	description: 'my description',
	collectionSchema: 123 // the store id
});

When updating an item - 'id' and 'version' are required. The version value can be:

  • 'active': use the last active version
  • 'working': use the last working version
  • any, valid, version number lower than the max version.
var item = new VYRE.Item({
	id: 123,
	version: 'active'
});

General information

Except for the getters, all methods return the Item object. It means that actions are chainable like in this example:

var item = new VYRE.Item({
	name: 'my test item',
	description: 'my description',
	collectionSchema: 123
}).addTaxonomy('/path/to/categry/')
  .addContent({comment: 'test'})
  .addMetadata({completed: 1});

The general methods accessible are the following getters:

  • getName()
  • getDescription()
  • getCollectionSchema()
  • getUniqueKey() : the unique key is a unique identifier generated by the framework for use in the front-end for linking newly created items without knowing what the Unify Item Id is going to be. See the corresponding section for more details.

Content and Metadata

Metadata and content attributes for an item are described by an object of key:value pairs. The name, or key, used for a metadata/content attribute should match the XML name of the attribute.

Methods

  • getMetadata(): returns a JSON object describing the item metadata
  • setMetadata(metadata): metadata is a JSON object representing metadata attributes as an xml_name:value pair. It overwrites the metadata attributes of the item.
  • addMetadata(metadata): metadata is a JSON object. it adds metadata to the existing metadata attributes.
  • removeMetadata(metadataKey): metadataKey is a string representing an XML name of an attribute. It replaces the metadata by an empty string

The same methods are available for content attributes:

  • getContent()
  • setContent(content)
  • addContent(content)
  • removeContent(contentKey)

Sectioned attributes

When using sectioned attributes the framework will expect you to pass them as in this example:

var item = new VYRE.Item({
	name: 'my test item',
	description: 'my description',
	collectionSchema: 123
});
item.addMetadata({
	basic_metadata: 'test',
	section_attribute:{
		sub_section_attribute_1: '123',
		sub_section_attribute_2: '456'	
	}
})

Taxonomy

We support the use of both the category path and category id when manipulating taxonomy. This will give front-end developers the option of using whichever method they want.

This works as follows. Given the following taxonomy tree:

  • Assets (id=34)
    • Logo (id=56)
    • Documentation (id=58)

The following actions will be equivalent:

item.addTaxonmy([
	"/Assets/Logo",
	"/Assets/Documentation" 
]);

and

item.addTaxonmy([
    "56",
    "58" 
]);

Methods

actions

The following methods are available:

  • addTaxonomy(categories): add categories to the item
  • replaceTaxonomy(categories): replace all categories attached to the item. When updating the item on the server, all categories linked to the items will be overwritten.
  • removeTaxonomy(categories): remove categories from the item

The parameter can describe eiher one or many categories by passing either a number, a string or an array of string/numbers.

You should also keep in mind that the taxonomy actions are process in this order:

  • add
  • replace
  • remove

So if you manipulate the same category, the order you will call the actions might not be the same as the order used by the server to process the item. This can lead to errors difficult to debug.

Getters

  • getAddedTaxonomy(): returns an array of categories that have been added to the item
  • getReplacedTaxonomy(): returns an array of categories that have been replaced to the item
  • getRemovedTaxonomy(): returns an array of categories that have been removed to the item
  • getExistingTaxonomy(): returns an array of categories that are already linked to the item. This array of exisiting categories is only used when retrieving an item from the server. If this item is taxonomized, categories will be added to this 'existing' array.

Note: these functions are similar to:

  • getTaxonomy("add")
  • getTaxonomy("replace")
  • getTaxonomy("remove")
  • getTaxonomy("existing")

Item Links and User Links

Metods

  • getItemLink(itemLinkId): returns an instance of VYRE.ItemLink object corresponding to the itemLinkId passed in parameters
  • getItemLinks(): returns an array of all VYRE.ItemLink objects linked to the item
  • addItemLink(itemLink, items): itemLink is either an instance of an VYRE.ItemLink or a user link definition id, add an item link to an item
  • removeItemLink(linkId, items): linkId is the id of the item link. items is an item id or an array of item ids. It removes items from the link defined by the linkId

Similar methods are available for user links:

  • getUserLink(userLinkId): returns an instance of VYRE.UserLink object corresponding to the userLinkId passed in parameters
  • getUserLinks: returns an array of all VYRE.UserLink objects linked to the item
  • addUserLink(userLink, users): userLink is either an instance of an VYRE.UserLink or a user link definition id, adds a user link to an item
  • removeUserLink(userLinkId, users): userLinkId is the id of the user link. user is an user Id or an array of item ids. it removes users from the link defined by the userLinkId

VYRE.ItemLink

This object represents a link between two Items defined by an item link definition id.

constructor

var itemLink = new VYRE.ItemLink({id:123});

methods

actions

  • setItems(itemIds): replace itemIds to be the list of items linked. When updating the item on the server all previous linked items will be replaced.
  • addItems(itemIds): add itemIds' to the list of items linked.
  • removeItems(itemIds): remove itemIds from the list of items.

The parameter itemIds can be:

Note: for a shortcut you can use these functions which does exactly the same:

  • set(itemIds)
  • add(itemIds)
  • remove(itemIds)

options

These options work the same way as the corresponding options in the content template Item Link Tag. setLinkStatus corresponds to createAsActive and setActivateExistingLinks to activateCurrentLinks.

  • setLinkStatus(status): status can either be "active" or "working". Sets the status of the new links which are being created by this item link action.
  • setActivateExistingLinks(activateExistingLinks): activateExistingLinks is a boolean. Any item links that already exist will be updated to be active when this is set to true. This will affect links which are being referenced by the ItemLink object. So, for example, if an item (1) is already linked to item (2) through a working link, in order to link the item to another item (3) and activate the link to item 2, you would need to do something like new VYRE.ItemLink({id:123}).set([2, 3]).setActivateExistingLinks(true)

getters

  • getAdded(): returns an array of items that have been added to the item link object
  • getReplaced(): returns an array of items that have been replaced to the item link object
  • getRemoved(): returns an array of items that have been removed to the item link object
  • getExisting(): returns an array of items that are already linked to the item. This array of exisiting items is only used when retrieving an item from the server. If this item has linked items they will be added to this 'existing' array.

Note: these functions are similar to:

  • get("add")
  • get("replace")
  • get("remove")
  • get("existing")

example

var itemLink = new VYRE.ItemLink({id:123}).setItems([999, 754, 124]).setLinkStatus("working").setActivateExistingLinks(true);

VYRE.UserLink

This object represents a link between an item and a user defined by a user link definition id.

constructor

var userLink = new VYRE.UserLink({id:123});

Methods

actions

For all these methods the parameter userIds can represent one or many user profile ids by passing one profile id (string or number) or an array of ids.

  • setUsers(userIds): replace userIds to the list of users linked. When updating the item on the server all previous linked users will be replaced by these ones.
  • addUsers(userIds): add userIds' to the list of users linked.
  • removeUsers(userIds): remove userIds from the list of users

Note: you can use these functions which does exactly the same:

  • set(userIds)
  • add(userIds)
  • remove(userIds)

getters

  • getAdded(): returns an array of users that have been added to the user link object
  • getReplaced(): returns an array of users that have been replaced to the user link object
  • getRemoved(): returns an array of users that have been removed to the user link object
  • getExisting(): returns an array of users that are already linked to the item. This array of exisiting users is only used when retrieving an item from the server. If this item has linked users they will be added to this 'existing' array.

Note: these functions are similar to:

  • get("add")
  • get("replace")
  • get("remove")
  • get("existing")

VYRE.ItemService

The VYRE.ItemService is used to communicate with the server. All |item workflow actions are available as a method for this object:

  • create
  • createAndCheckin
  • createAndActivate
  • update
  • checkout
  • checkoutAndUpdate
  • checkin
  • discard
  • remove
  • activate
  • createAndCheckout
  • checkoutUpdateAndCheckin
  • deactivate

These methods take 2 parameters:

  • items: is an instance of VYRE.Item or an array of VYRE.Item (in this case, the ordering of the items does not matter, see chaining item creation for more details)
  • callback: is a function that will be called when the server has finished processing the items, he will receive, as a parameter, a JSON object describing the response (more details)

Example:

var itemA = new VYRE.Item({
                name:"AAA",
                description:"test",
                collectionSchema:"2356"
});
 
var itemB = new VYRE.Item({
                name:"BBB",
                description:"test",
                collectionSchema:"2356"
})
 
var callback = function(data){
                console.log(data);
};
 
VYRE.ItemService.createAndActivate([itemA, itemB], callback);
// to create and activate only item A:
VYRE.ItemService.createAndActivate(itemA, callback)

Notes

Link ordering

Item link ordering is supported as it is in the item edit portlets and item importer. The order in which items are specified is the order that they will be linked to the item being created/updated.

Referencing a newly created item

It is possible to reference/link a newly created item; like in these examples:

var B = new VYRE.Item({
                name:"itemB",
                description:"test",
                collectionSchema:"2356"
});
 
var D = new VYRE.Item({
                name:"itemD",
                description:"test",
                collectionSchema:"2356"
}).addItemLink(new VYRE.ItemLink({id:"528"}).addItems(B)); //itemD will be linked to itemB throw link definition 528
 
 
var C = new VYRE.Item({
                name:"itemC",
                description:"test",
                collectionSchema:"2356"
}).addItemLink(new VYRE.ItemLink({id:"528"}).addItems([D,B,"34"])); // itemC will be linked to item D, B and item with id 34
 
 
 
A = new VYRE.Item({
                name:"itemA",
                description:"test",
                collectionSchema:"2356",
}).addItemLink(new VYRE.ItemLink({id:"528"})
               .addItems(new VYRE.Item({
                         name:"otherItem",
                         description:"test",
                         collectionSchema:"2356"
                })
));    // itemA will be linked to otherItem

Chaining item creation

When sending several items to the server, the order inside the array of items doesn't matter. For example: if we have two items, itemA and itemB, where itemB references itemA:

var itemA = new VYRE.Item({
                name:"AAA",
                description:"test",
                collectionSchema:"2356"
});
 
var itemB = new VYRE.Item({
                name:"BBB",
                description:"test",
                collectionSchema:"2356"
}).addItemLink(new VYRE.ItemLink({id:"528"}).addItems(itemA));

These 2 calls will do the same action:

VYRE.ItemService.createAndActivate([itemA, itemB], callback);

and

VYRE.ItemService.createAndActivate([itemB, itemA], callback);

The framework will sort them in the right order before sending them to the server.

Get/update an item from the server

If you need to get or update items from the server you can perform an AJAX search using the Ajax Search Framework and adding the parameter "outputFormat" with the value "json" when initialising the ajax search. You will have, in the callback, an array of items that you can use directly with the item ajax framework.

Example:

var ajs = new VYRE.AjaxSearch({
	searchType: 'content',
	gatewayId: 1,
	pageId: "$page_id",
	portletId: "$portlet_id",
	storeId: 34,
	displayItemId: null,
	contextPath: '$context_path',
	outputFormat: "json"     //  <---- DON"T FORGET THIS
});
 
ajs.setSavedSearch("item:2617");
 
ajs.callBackFunctions.add(function(data){
	var responseItems  = JSON.parse(data).response.result.items; 
        //in this example responseItems contains one element due to the saved search but it can be more items.
 
	var items = [];
	for (var i=0, len = responseItems.length; i < len; i++) {
		var item = new VYRE.Item(responseItems[i].item);
		items.push(item);
	}
 
	//now all items in the items array are instances of VYRE.Item
	//so you can call all methods for VYRE.Item
        // for example:
        // items[0].getName();
});
 
ajs.search();

Response

Validation

We provide some validation on the data that is sent to the server from the client. We check that the item adheres to these validation rules:

  • Name and description are not missing
  • Any required attributes are not missing.
  • All attributes are of the correct type. (e.g. you cannot put text into an attribute of type boolean - N.B. Boolean values are sent as '1' or '0' )
  • Supplying a content tag for file items
  • Trying to move an item to the incorrect state (e.g. from checked out to active).

All requests made to the server to create/update an item will have a JSON response. This will indicate whether the request was successful, and if it wasn’t it will provide the reasons why the request was not successful.

Errors

When an error occurs during the processing of the request we will respond with the following response:

File:Item_ajax_error_message.png

Success

When a request is successful the response will look like:

File:Item_ajax_success_message.png

Personal tools