hi

Has anyone read the book: 'Pro Drupal Development'? Well, anyways, I'm trying to get a custom module to work, only I'm having difficulty.
The module is supposed to let users make an annotation (a type of note that only the user can see) to a web page.

My files:


<?php

/var/www/drupal-6.16/sites/all/modules/custom/annotate/annotate.module
// $Id$

/**
 * @file
 * Lets users add private annotations to nodes.
 *
 * Adds a text field when a node is displayed
 * so that authenticated users may make notes.
 */
 
 /**
  * Implementation of hook_menu().
  */
 
 function annotate_menu() {
    $items['admin/settings/annotate'] = array(
        'title'             =>  'Annotation settings',
        'description'       =>  'Change how annotations behave.',    
        'page callback'     =>  'drupal_get_form',
        'page arguments'    =>  array('annotate_admin_settings'),
        'access arguments'  =>  array('adminsiter site configuration'),
        'type'              =>  MENU_NORMAL_ITEM,
        'file'              =>  'annotate.admin.inc'
    );
 
 return $items;
 }
 
  /**
  * Implementation of hook_nodeapi().
  */
 
 function annotate_nodeapi(&$node, $op, $teaser, $page) {
 
    global $user;
    switch ($op) {
        // The 'view' operation means the node is about to be displayed.
        case 'view':
            // Abort if the user is an anonymous user (not logged in) or
            // if the node is not being displayed on a page by itself
            // (for example, it could be in a node listing or search result).
            
            if($user->id == 0 || !$page) {
                break;
            }
        // Find out which node types we should annotate.
        $types_to_annotate = variable_get('annotate_node_types', array('page'));
        
    // Abort if this node is not one of the types we should annotate.
    if(!in_array($node->type, $types_to_annotate)) {
        break;
    }
 
    // Add our form as a content item.
    $node->content['annotation_form'] = array(
        '#value'    =>  drupal_get_form('annotate_entry_form', $node),
        '#weight'   =>  10  
    );   
    break;
   }
 }
   
  /**
  * Define the form for entering an annotation.
  */
   
 function annotate_entry_form($form_state, $node) {
 
    // Define a fieldset.
    $form['annotate'] = array(
        '#type'     =>  'fieldset',
        '#title'    =>  t('Annotations')
    );
 
    // Define a textarea inside the fieldset.
    $form['annotate']['note'] = array(
        '#type'             =>  'textarea',
        '#title'            =>  t('Notes'),
        '#default_value'    =>  isset($node->annotation) ? $node->annotation : '',
        '#description'      =>  t('Make your personal annotations about this content here.
            Only you (and the site administrator) will be able to see them.')
    );
    
    // For convenience, save the node ID.
    $form['annotate']['nid'] = array(
        '#type'     =>  'value',
        '#value'    =>  $node->nid,
    );
    
    // Define a submit function.
    $form['annotate']['submit'] = array(
        '#type'     =>  'submit',
        '#value'    =>  t('Update'),
    );
    return $form;     
 }
 
<?php
/var/www/drupal-6.16/sites/all/modules/custom/annotate/annotate.admin.inc


// $Id$

/**
 * @file
 * Administration page callbacks for the annotate module.
 */
 
/**
 * Form builder. Configure annotations.
 *
 * @ingroup forms
 * @see system_settings_form().
 */ 
 
 function annotate_admin_settings() {
    // Get an array of node types with internal names as keys and
    // "friendly names" as values. E.g.,
    //array('page' => 'Page', 'story' => 'Story')
    
    $options = node_get_types('names');
    
    $form['annotate_node_types'] = array(
        '#type'             =>  'checkboxes',
        '#title'            =>  t('Users may annotate these content types'),
        '#options'          =>  $options,
        '#default_value'    =>  variable_get('annotate_node_types', array('page')),
        '#description'      =>  t('A text field will be available on these content types to
                  make user-specific notes.')
    );
    
    return system_settings_form($form);
  
 
 } 
 

and

/var/www/drupal-6.16/sites/all/modules/custom/annotate/annotate.info

; $Id$
name = Annotate
description = Allows users to annotate nodes.
core = 6.x
package = Pro Drupal Development

The book goes on to read:

Create and view a Page node in your web browser, and you should see that the form has been appended with the annotations form.

Only, I can't see the form?

Ive enabled the annotate module and navigating to Adminsiter > Site Configuration > Annotate; successfully shows me that the configuration form for annotate.module is working correctly.

Ive pretty much followed the book to the letter, and I'm not sure what the problem is now?

help please..:)

Comments

lorinpda’s picture

Hi,
The "annotation" information is supposed to be saved in the database.

Therefore, did you create a custom database table (e.g. annotations) ?
....
Do have code code that saves an annotation to that database table? After a user submits the annotation form, where is the code that persists the user's entry?
....
Do you to retrieve (select) the annotation from the database? When a users requests display of an annotated node, where are you going to the database and selecting the corresponding annotation?
....
You need to implement:
-hook_install (to install a new database table). E.G. "annotate_install"
-hook_submit (and include code that saves the annotation to the database)
-modify annotate_nodeapi() so that it select the corresponding annotation and adds it to node->content
....
Hope that helps.

michaelcchastain’s picture

Looks like he should still be getting a fieldset and textfield when he navigates to a page node though, even without setting up the persistence code.

Michael

1cookie’s picture

hi

That's exactly my point michaelchastain. The database stuff comes later in the chapter. The book mentions the above: 'Create and view a Page node in your web browser, and you should see that the form has been appended with the annotations form'

:)

Rakward’s picture

Compare your code to the one foudn in this zip: http://www.drupalbook.com/node/2

Are you using the Drupal 6, 2nd edition-book? Cause there's also a drupal-5 version.

Also, there will be some small errors in the book, check here: http://www.drupalbook.com/errata2 to see wich ones. Though all in all, it's a very good book. Used it myself about a month ago :)

1cookie’s picture

hi Rakward

I'm reading the 2nd edition, and agree, on the whole it is an excellent insight into the Drupal framework. I compared my code to the archives and have managed get the form to display correctly. Thanks for the links, most helpful!

:)

michaelcchastain’s picture

What editor are using? Maybe it is the encoding?! Make sure that it is set to UTF-8.

After making alterations to your module's code make sure to reinstall the module in yoursite/admin/build/local.

Let us know when you figure it out.

Michael

1cookie’s picture

hi

I'm using ScITE, with Linux. A quick search for 'Encoding' in help reveals:

"SciTE will automatically detect the encoding scheme used for Unicode files that start with a Byte Order Mark (BOM). The UTF-8 and UCS-2 encodings are recognized including both Little Endian and Big Endian variants of UCS-2.

UTF-8 files will also be recognised when they contain a coding cookie on one of the first two lines. A coding cookie looks similar to "coding: utf-8" ("coding" followed by ':' or '=', optional whitespace, optional quote, "utf-8") and is normally contained in a comment:
# -*- coding: utf-8 -*-
For XML there is a declaration:
<?xml version='1.0' encoding='utf-8'?>

For other encodings set the code.page and character.set properties. "

After reading this, what do you think? Is it an encoding issue?

I've only recently moved to Linux. I've previously used notepad++ (which is easy to switch between encoding variables) with Windows, so it's a whole new experience.

"After making alterations to your module's code make sure to reinstall the module in yoursite/admin/build/local."

I will bear that in mind Michael, thanks for the "heads up".

michaelcchastain’s picture

maybe throw in a comment with "coding: utf-8" just to make sure that it is in utf-8. This probably isnt the reason though.

This is the problem with key:value coding. There is probably some underscore or hash mark missing somewhere and we are just missing it, and it is something that an IDE/editor is not going to recognize as a mistake.

Try throwing in commas and the end of every array key/value pair including the on just before the closing parenthesis.

this['array'] = array(
'has' => 'to many',
'things' => 'to go wrong',
);

Michael

1cookie’s picture

thanks Michael and everybody else for the help. Granted, mistakes do happen; I'm just relieved to get it working!

best wishes

michaelcchastain’s picture

what was it that kept it from loading?

1cookie’s picture

Well, I cut and pasted the code from the book archives; overwriting my original code, so I can't really say....sorry

:)

EDIT:

You could, I suppose visit: http://www.drupalbook.com/node/2 and compare the code with that above. Look for 2nd edition Drupal 6.x, annotate module....:)

hope this helps

michaelcchastain’s picture

if ($user->uid == 0 || !$page)

you had:
($user->id == 0..............

U seemed to have forgot the u.....

Now I'm not praising Java, but one of the benifits of it is that it would have caught that error for you! But not php.

Anyway that's was the thing keeping you from inserting your form. I added a comment in the global variables api doc for $user so you can see some of the options in the future. I pulled it from a thread somewhere here.

Michael

1cookie’s picture

ah, now that was a little bit careless of me..:)

You know what it's like, you buy a new book, and you can't get a module to work, help!!! I will in future be a little more careful; but its nice to speak to like minded individuals and get a little help and insight (Java mentioned!) form time to time..:)

thanks again...

Andrew

ChristianP’s picture

Hi, I've tried this and it doesn't work for me for some reason. I copied the code from the website zipfile above and I can't see a textfield in my nodes. :/ What could be the problem here? I tried clearing the cache and reinstall the module a couple of times because I thought that would solve it since I altered the code, but to no avail.

Keith’s picture

I had the same problem and struggled in vain for over an hour to get the annotations fieldset to appear on the edit page. Desperate to try anything, I went ahead and saved the note and ... the fieldset and textarea showed up when viewing the saved node!

But the authors designed the module that way: The form is added when the hook annotate_nodeapi() is called when the operation is 'view'. Of course, rereading that chapter uncovered the truth on page 22: "Create and view a Page node..." (italics mine). Duh! Serves me right, for not reading carefully.

ChristianP’s picture

Ah yeah, I realized that as well, lol. And it makes sense if you think about it, why create an annotation if you don't have any content to start with? :)

npoleon06’s picture

What were the problems with your code? I am having the exact same issue. Also, I am using NOTEPAD to creat my PHP files, should I be using some other editor. I have downloaded the code from the website (the website seems to be gone now, but) I compared my code with what was downloaded and it matched exactly. Also, I even cut/paste code from the downloaded files into my annotate.module file and I'm stuck at the same place you were. Configuration page works, but when I add a PAGE node, I get an error.
Personnally, I do not see how a book with errononeous coding examples can be considered good, let alone great.

rolodmonkey’s picture

What is the error that you are getting?

As for your other comment, because of the nature of technical books, they will always have errors. Always. That is why the term 'errata' exists. Some will have more, some less, but there no direct correlation between errata and quality. Luckily, Apress provides a convenient, free way to see the errata, and to download code samples with the corrections. Not all publishers are that good.

--

Read more at iRolo.net

npoleon06’s picture

THANLKS for your help....Its an HTTP: 500 Internal Server

This error (HTTP 500 Internal Server Error) means that the website you are visiting had a server problem which prevented the webpage from displaying.

For more information about HTTP errors, see Help.

As for the second part, the errata website does not seem to be up anymore. I have spent hours trying to debug this code, and have becomce increasingly frustrated because I am a programmer. Granted, not a PHP coder, but VB. Still, I couldn't possibly imagine writing a book with coding examples that don;t work. Any updates or changes to the languarge standards, syntax, api's, etc are handled in addendums, revisions or editions. I checked the web for all of these and couldn't find any issues with the code I'm using. And this is the worst part for me, I'm using the code I downloaded from Apress.

BUT

Obviousily I am missing something, (and as one of my programming axiom states "The solution to any problem soon presents itself to the first person who looks over your shoulder." ; here is the code:

<?php
// $Id$

/**
* @file
* Lets users add private annotations to nodes.
*
* Adds a text field when a node is displayed
* so that authenticated users may make notes.
*/

/**
* Implementation of hook_menu().
*/
function annotate_menu()
{
$items['admin/settings/annotate'] = array('title' => 'Annotation settings',
'description' => 'Change how annotations behave', 'page callback' =>
'drupal_get_form', 'page arguments' => array('annotate_admin_settings'),
'access arguments' => array('administer site configuration'), 'type' =>
MENU_NORMAL_ITEM, 'file' => 'annotate.admin.inc', );

return $items;
}

/**
* Implementation of hook_nodeapi().
*/
function annotate_nodeapi(&$node, $op, $teaser, $page)
{
global $user;
switch ($op) {
// The 'view' operation means the node is about to be displayed.
case 'view':
//Abort if the user is an anonymous user (not logged in) or
//if the node is not being displayed on a page by itself
//(for example, it could be in a node listing or search result).
if ($user->uid == 0 || !$page) {
break;
}
// find out which node types we should annotate.
$types_to_annotate = variable_get('annotate_node_types', array('page'));
// Abort if this node is not one of the tyupes we should annotate.
if (lin_array($node->type, $type_to_annotate)) {
break;
}

//Add out form as a content item.
$node->content['annotation_form'] = array('#value' => drupal_get_form('annotate_entry_form',
$node), '#weight' => 10);
break;
}
}

/**
* Define the form for entering an annotation.
*/
function annotate_entry_form($form_state, $node) {
// Define a fieldset.
$form['annotate'] = array(
'#type' => 'fieldset',
'#title' => t('Annotations'),
);

// Define a textarea inside the fieldset.
$form['annotate']['note'] = array(
'#type' => 'textarea',
'#title' => t('Notes'),
'#default_value' => isset($node->annotation) ? $node->annotation : '',
'#description' => t('Make your personal annotations about this content here. Only you (and the site administrator) will be able to see them.'),
);

// For convenience, save the node id.
$form['annotate']['nid'] = array(
'#type' => 'value',
'#value' => $node->nid,
);

// Define a submit button.
$form['annotate']['submit'] = array(
'#type' => 'submit',
'#value' => t('Update'),
);
return $form;
}

npoleon06’s picture

Server error? Does that mean that there is something wrong with the Apache, PHP, settings or something? Im using the MOWES Portable II package. It has MySQL, PHP, and Linux I think? Is there some setting in that applicationo/package or some PHP ini thing I need to check?

npoleon06’s picture

From the Apache2 error log:

[Wed Apr 13 15:23:42 2011] [error] [client 127.0.0.1] PHP Fatal error: Call to undefined function lin_array() in E:\\www\\drupal\\sites\\all\\modules\\custom\\annotate\\annotate.module on line 44, referer: http://localhost:8080/drupal/admin/content/node

npoleon06’s picture

I think that should be !in_array....not lin_array.

npoleon06’s picture

I am no longer getting the server error. Now I am getting a new error:

warning: in_array() expects parameter 2 to be array, null given in E:\www\drupal\sites\all\modules\custom\annotate\annotate.module on line 44.

SO what I learned:
1) Check the APACHE2 error log.
2) Where my glasses when coding.

npoleon06’s picture

Corrected another syntax error

I had

$type_to_annotate

and it should have been

$types_to_annotate

and now its working!

thalemn’s picture

Hi everyone,

Just wanted to say thanks for this excellent discussion! Yes, I'm using the book and couldn't get it to work, checked my code a zillion times...then googled it and found this. Whew. All is well.

Tom Hale
New Day Web Design
www.newdaywebdesign.com