This site has been archived and you can no longer log in or post new messages. For up-to-date community resources please visit ezplatform.com

eZ Community » Learn » eZ Publish » Creating Custom Admin Modules & Views

Creating Custom Admin Modules & Views

Monday 18 April 2011 11:42:34 pm

  • Currently 4 out of 5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Allowing user input in our Template

We can make the required changes to the page by adding a link in each row to the same page, whilst adding the additional “remove” parameter. Open the main template file for the page again (/extension/mynewsletter/design/admin/templates/newsletter/userlist.tpl) and update the div with the class “box-content” with the following code (the changes are highlighted in bold):

…
<div class="box-content">    
    <div class="content-navigation-childlist">
        {if $newsletter_users|count()}
            <table cellspacing="0" class="list" id="ezasi-subitems-list">
                <thead>
                    <tr>
                        <th>Name</th>
                        <th>Email</th>
                        <th></th>
                    </tr>
                </thead>
                <tbody>
 
                    {for 0 to $newsletter_users|count()|dec() as $counter}
                        <tr class="eq($counter|mod(2),0)}bglight{else}bgdark{/if} {if">
                            <td>{$newsletter_users[$counter].name}</td>
                            <td>{$newsletter_users[$counter].data_map.user_account.content.email}</td>
                            <td>
                                <b><a href={concat($module_details['module_name'],'/',$module_details['function_name'],'/remove/',$newsletter_users[$counter].contentobject_id)|ezurl()}>
                                    Remove from list
                                </a></b>
                            </td>
                        </tr>
                      {/for}
 
                    </tbody>
            </table>
        {else}
            <p>No users are signed up!</p>
        {/if}
    </div>
</div>
…
 

When clicked, the buttons next to each set of user details will bring the operator back to the same page of the site so we now need to take additional steps in our PHP file to make sure something is done about the input.

 

Updating our PHP to allow user interaction

The PHP we create needs to update the content object of the user so that the newsletter attribute is set to false. eZ Publish 4.3 launched the perfect functionality to do this easily with the introduction of the function eZContentFunctions::updateAndPublishObject. Unfortunately though, the code is not as straightforward if your eZ Publish build is pre 4.3.

Both unordered and ordered parameters can be accessed in your PHP using the $Params array. This is a simple associated array so in our case remove can be accessed using $Params[‘remove’]. We can check whether this value has been set and if it has, carry out our additional

I have split the code for this example into two parts to deal with the two versions of the code. These are the complete files. Make sure to update all of the lines in bold text:

 

eZ Publish 4.2 and earlier

<?php
/**
 * File containing the eZ Publish view implementation.
 *
 * @copyright Your Name here
 * @license licence details
 * @version 1.0.0
 * @package mynewsletter
 */
<b>function ezUpdate42($contentObject)/*adapted from updateAndPublishObject in version 4.3*/
{
    $db = eZDB::instance();
    $db->begin();
    $newVersion = $contentObject->createNewVersion( false, true, $languageCode );
 
    if ( !$newVersion instanceof eZContentObjectVersion )
    {
        eZDebug::writeError( 'Unable to create a new version for object ' . 
                             $contentObject->attribute( 'id' ), 'userlist.php' );
        $db->rollback();
        return false;
     }
 
    $newVersion->setAttribute( 'modified', time() );
    $newVersion->store();
 
    $attributeList = $newVersion->attribute( 'data_map' );
    $newsletter_attribute = $attributeList['newsletter'];
    $newsletter_attribute->fromString( 0 );
    $newsletter_attribute->store();
 
    $db->commit();
 
    $operationResult = eZOperationHandler::execute( 'content', 'publish', 
                  array( 'object_id' => $newVersion->attribute( 'contentobject_id' ),
                         'version'   => $newVersion->attribute( 'version' ) ) );
    return $operationResult;
}</b>
 
//version <4.3 of eZ Publish:
include_once( 'kernel/common/template.php' );
$tpl = templateInit();
 
<b>if ( $Params['remove'] != null )
{
    $result = 0; //used to measure whether the update has been made successfully or not
    $contentObject = eZContentObject::fetch( $Params['remove'] );
    if( $contentObject instanceof eZContentObject )
    {            
        /*code for eZ Publish 4.2 and earlier - see additional function for full code*/
        $result = ezUpdate42($contentObject);
    }
    if ($result==0)
    {
        $tpl->setVariable( 'error', "There was a problem updating the user" );
    }
    else 
    {
        $tpl->setVariable( 'feedback', "The user has been removed successfully" );
    }
}</b>
 
// Process template and set path data:
$Result = array();
$Result['content'] = $tpl->fetch( 'design:newsletter/userlist.tpl' );//main tpl file to display the output
 
$Result['left_menu'] = "design:newsletter/leftmenu.tpl";
 
$Result['path'] = array( array( 'url' => 'newsletter/userlist',
                                'text' => 'User List' ) );
?>
 

eZ Publish 4.3 onwards

<?php
$tpl = eZTemplate::factory();//this line of code is for ez publish 4.3, replace it with the following lines for versions prior to that
 
if ($Params['remove']!=null)
{
    $result = 0;//used to measure whether the update has been made successfully or not
    $contentObject = eZContentObject::fetch( $Params['remove'] );
    if( $contentObject instanceof eZContentObject )
    {
        /*code for eZ Publish 4.3 onwards*/
        $params = array();
        $attributes = array("newsletter"=>0);
        $params['attributes'] = $attributes;
        $result = eZContentFunctions::updateAndPublishObject( $contentObject, $params )                    
    }
    if ($result==0)
    {
        $tpl->setVariable( 'error', "There was a problem updating the user" );
    }
    else 
    {
        $tpl->setVariable( 'feedback', "The user has been removed successfully" );
    }
}
 
// Process template and set path data:
$Result = array();
$Result['content'] = $tpl->fetch( 'design:newsletter/userlist.tpl' );//main tpl file to display the output
 
$Result['left_menu'] = "design:newsletter/leftmenu.tpl";
 
$Result['path'] = array( array( 'url' => 'newsletter/userlist',
                                'text' => 'User List' ) );
?>
 

How it works

The difference between the two versions is primarily due to the update process (the only other difference is how the template object is initialised). The logic makes use of built in eZ Publish functionality to update the content, if we establish that a content object update is required.

Once we have established the user has requested to remove a mailing list entry, we extract the Content Object ID of the mailing list and then ensure that this is valid. If it is we update the object so that the newsletter field is turned off.

In order for us to provide feedback to the user we then need to pass details of what we have done to the template. This is carried out through the template object we create at the start of the code. In our initial code this only fetched the template we were using. This time, before we fetch the template we pass in one of two variables to the page:

if ( $result == 0 ) //setting a template variable to return feedback to the user
{
    $tpl->setVariable( 'error', "There was a problem updating the user" );
}
else 
{
    $tpl->setVariable( 'feedback', "The user has been removed successfully" );
}
 

If the user could not be updated we pass an error into the template and if not we pass the message that the user was removed from the list successfully. We now need to make sure this message is displayed in our template.

 

Providing user feedback

To provide the feedback to the user, we are going to use the message box used elsewhere in the admin siteaccess to display the variable we have just set in our PHP . Accessing these variables is easy and is identical to if you would of declared these variables in your template. To access the error variable we use {$error} and for the feedback variable we use {$feedback}.

We are going to store the feedback message in a new template so we can easily reuse the functionality in our other views.

 

Creating the error message template

Go into your newsletter template directory (/extension/mynewsletter/design/admin/templates/newsletter/). Within the directory create a file called “newsletter_feedback_box.tpl”. We are going to use a simplified version of the code used to provide feedback elsewhere. In our case we can display errors or warnings and so the following code is sufficient. Add this to the template and then save and exit (this code will not need to be changed again) :

{if is_set($error)}
        <div class="message-error">
            <h2><span class="time">[{currentdate()|l10n( shortdatetime )}]</span> Problem encountered</h2>
            <p>{$error}</p>
        </div>
    {elseif is_set($feedback)}
        <div class="message-feedback">
            <h2><span class="time">[{currentdate()|l10n( shortdatetime )}]</span> Success!</h2>
            <p>{$feedback}</p>    
        </div>
{/if}
 

All the code does is check to see if an error or feedback is passed into the template and if it has this is displayed in the usual style for the admin siteaccess. Now we need to include this in our main view template.

 

Updating our main view template

Go back into the userlist.tpl file (/extension/mynewsletter/design/admin/templates/newsletter/userlist). Add the code in bold (the code block is taken from the start of the template):

{def $users_folder = fetch( 'content', 'node', hash( 'node_path', 'Users/Members'))
     $newsletter_users = fetch( 'content', 'list', 
                           hash( 'parent_node_id', $users_folder.node_id,
                                 'attribute_filter',array(array('user/newsletter','=',1))))
}
{*Include message box if necessary:*}
{if or(is_set($feedback),is_set($error))}
    {include uri="design:newsletter/newsletter_feedback_box.tpl" feedback=$feedback error=$error}
{/if}
<div class="box-header">
    <div class="button-left">
        <h2 class="context-title">Newsletter Users ({$newsletter_users|count()})</h2>
    </div>
    <div class="float-break"></div>
</div>    
…
 

The rest of the template is left out for brevity.

 

The finished view

You will now receive feedback messages when you remove users from the newsletter list. If you open the page in your browser (http://www.yoursite.com/admin/newsletter/userlist) when you click on a user to remove them, you will receive notification they have been removed, similar to the below:

The finished view

 

We have now covered how to implement custom PHP based on user input and how you can return information back to the user through the Template object. Let’s now look at how to implement a second view within the same module. We’ll create a view which will send out an email to all users on the newsletter list we have just set up. This will allow us to see how POST and GET parameters can be used within your views

 

Printable

Printer Friendly version of the full article on one page with plain styles

Author(s)

Proudly Developed with from