Snippets for eZ publish 3: Creating new content objects with php


From eZ Publish 3.9 on, there's also the static method eZContentFunctions::createAndPublishObject() which handles object creation, filling attributes and publishing at one location. The filling of the attributes is handled by the fromString functions implemented by the datatypes. For more information on this, see the fromString and toString feature doc.

Permission checking

If you want to bypass the policy system, then remove the conditional check on $accessResult

Code sample

The following code will create a new content object and an initial draft version. It is based on a part of the action view of the content module (kernel/content/action.php).

The known variables

  • $contentClassIdentifier: identifier of the content class we want to make an object of
  • $node: the parent node for the new object's main location in the node tree
$class = eZContentClass::fetchByIdentifier( $contentClassIdentifier );

if ( is_object( $class ) )
    $contentClassID = $class->attribute( 'id' );
    $parentContentObject =& $node->attribute( 'object' );

    $accessResult = $parentContentObject->checkAccess( 'create', $contentClassID, $parentContentObject->attribute( 'contentclass_id' ) ); 

    if ( $accessResult == '1' )
        include_once( 'kernel/classes/datatypes/ezuser/ezuser.php' );
        $user =& eZUser::currentUser();
        $userID =& $user->attribute( 'contentobject_id' );
        $sectionID = $parentContentObject->attribute( 'section_id' );

        include_once( 'lib/ezdb/classes/ezdb.php' );
        $db =& eZDB::instance();

        $contentObject =& $class->instantiate( $userID, $sectionID );
        $nodeAssignment = eZNodeAssignment::create( array( 'contentobject_id' => $contentObject->attribute( 'id' ),
                                                           'contentobject_version' => $contentObject->attribute( 'current_version' ),
                                                           'parent_node' => $node->attribute( 'node_id' ),
                                                           'is_main' => 1 ) );


Now that you have created a new content object, you will probably want to fill it's attributes with data and publish it.