I have no idea what happened, but hook_form_alter suddenly stopped working while I was doing some editing (not in that function). I reverted all my changes anyway and nothing changed, I'm still just getting the same original version of the form. the forums suggested it could be a cache issue, but I've cleared my cache and also tried it in a different browser and its still the same original form.

anyone have any ideas?

Comments

kunalkursija’s picture

Hi There,

First thing you need to check is...
1) Your Module is enabled or not !

If it is enabled then, Can you paste your module code here, so we can take a look ?

fudge714’s picture

Hi,

yes it is enabled. and thanks for taking a look, here is the code..

<?php

// Convert Image filename
function convert_to_filename ($string) {

	$string = strtolower($string);
	$string = str_replace (" ", "_", $string);
	$string = str_replace ("'", "", $string);
	$string = str_replace (",", "", $string);
	$string = str_replace (".", "", $string);

	preg_replace ("/[^0-9^a-z^_^.]/", "", $string);
	if($string=='') return 'default_photo_name';
	return $string;
}

// Write image to drupal site
function write_image_info($remote_image_path, $remote_image_name, &$fid)
{

	$image_path = $remote_image_path;
	// Save image file to drupal
	$remote_image_name = convert_to_filename($remote_image_name) . '.jpg';

        //Create the directory if it does not already exist, otherwise check the permissions
        $directory = 'public://amazon_book_images';
        file_prepare_directory($directory, FILE_CREATE_DIRECTORY);

	$file_temp = file_get_contents($remote_image_path);
	$file_temp = file_save_data($file_temp, 'public://' .'/amazon_book_images/'.  $remote_image_name, FILE_EXISTS_RENAME);
	$image_path = $file_temp->uri;

    //Set the file status to permanent so it is not deleted in next cron run
    $file_temp->status = FILE_STATUS_PERMANENT;
    file_save($file_temp);

    if (file_exists($image_path)){
 	return $file_temp;
    }
    else{
	return null;
    }

}


/**
 * Implementation of hook_form_alter().
 */
function diolibrary_form_alter(&$form, $form_state, $form_id) {
  switch ($form_id) {
    case 'library_item_node_form':
	  	
    //if we're not adding a single item without an isbn or editing an item... 
    if (!isset($_GET["isbn"]) && strpos($form['#action'],'add') !== false) {
		
		//link to single item add form
    	print "<a href='/?q=node/add/library-item&isbn=none'>Add an item without an isbn</a>";

	    //print form array details for debugging purposes      
   		/* print "<pre>";
      	print_r($form);
	  	print "</pre>"; */

      	//edit form elements
      	$form['title']['#title'] = "ISBN";
      	$form['title']['#size'] = 20;
      
		//get rid of stuff that will be automatically answered      
	    unset($form['body']);
    	unset($form['field_author']);
     	unset($form['field_return_date']);
     	unset($form['field_lender']);
     	unset($form['field_publisher_information']);
     	unset($form['field_picture']);
	 	unset($form['captcha']);
	 	unset($form['revision_information']);
	 	unset($form['comment_settings']);	 	
	 	unset($form['additional_settings']);	 	
	 	unset($form['author']);
	    unset($form['options']);
	    //can't figure out a good way of getting rid of the url path settings box - short of searching for the html and putting in comment signs around it. figured it didn't matter too much, but if you wanted to share this module, you might want to get round to it. 

      	// unset preview because with multiple nodes this is hard to deal with
      	unset($form['actions']['preview']);
      
      	//set at 2 for debugging. change to 10 or 20 later. 
      	//also need to change this in diolibrary_node_validate
		for ($i=1; $i <= 2; $i++) {
	      	
	      	$form['grouper'.$i]['#type'] = 'fieldset';
	        $form['grouper'.$i]['#weight'] = $i;
	      	
          	$form['grouper'.$i]['title'.$i] = $form['title'];
          	$form['grouper'.$i]['title'.$i]['#title'] = "ISBN ".$i;
          	$form['grouper'.$i]['title'.$i]['#weight'] = 1;
          	//only the first one should be compulsory
          	if ($i > 1) {
          		$form['grouper'.$i]['title'.$i]['#required'] = false;
          	}
          	
          	$form['grouper'.$i]['field_object_type'.$i] = $form['field_object_type'];
          	$form['grouper'.$i]['field_object_type'.$i]['#weight'] = 2;
          	
          	$form['grouper'.$i]['field_categories'.$i] = $form['field_categories'];
          	$form['grouper'.$i]['field_categories'.$i]['#weight'] = 3;
          	
        }

		//killing the original fields since they aren't grouped/weighted correctly. 
		unset($form['title']);
		unset($form['field_object_type']);
		unset($form['field_categories']);

   } else { //if its an edit form or a single add form, just print the normal form..
   		print "<a href='/?q=node/add/library-item'>Add multiple items with isbns</a>";
   }
   break;
  }

}


// brett: this allows people to put a bar code in the item field and gets book info and image
function diolibrary_is_valid_book_barcode( $form_item, $barcode ) {
print "Is valid barcode";
  // barcodes for books section e.g. 9780006862451
  if ( is_numeric( $barcode ) ) {
    if ( strlen($barcode ) == 13 && !strncmp($barcode, '978', 3) ) {
      return TRUE;
    } else {
      form_set_error( $form_item, 'Your numeric entry is not a valid book barcode - 13 digits and starting with 978' );
      return FALSE;
    }
  }
  return FALSE;
}


function diolibrary_check_for_book_barcode( $isbn ) {
  // barcodes for books section e.g. 0140433821 or 9780006862451
  // although the parameter is called isbn it actually starts off as a barcode
  //$isbn = $node->title;


  if ( is_numeric( $isbn ) && strlen($isbn) == 13 && !strncmp($isbn, '978', 3) ) {
    //convert barcode (or isbn-13) to isbn-10: SEE: http://en.wikipedia.org/wiki/International_Standard_Book_Number
    $isbn = substr( $isbn, 3, 9);
    $checksum = ( substr($isbn,0,1)+2*substr($isbn,1,1)+3*substr($isbn,2,1)+4*substr($isbn,3,1)+5*substr($isbn,4,1)+6*substr($isbn,5,1)+7*substr($isbn,6,1)+8*substr($isbn,7,1)+9*substr($isbn,8,1) )%11;
    if ( $checksum == 10 ) $checksum = 'X';
    if ( $checksum == 11 ) $checksum = 0;
    $isbn .= $checksum;    //var_dump( $isbn );
    }
    
/*
- Check abebooks and see if the isbn is available; use that for metadata if so.
- If not, try isbndb.com
- pull the picture from Amazon out of laziness
- And then if we're really desperate, maybe consider pulling data from Amazon or openisbndb           
*/
    
    $book_found = false;
        $author = "";
        $image = "";
        $description = "";
        $year = "";
        $publisher = "";
        $title = "";
    
    $abedata = @file_get_contents('http://www.abebooks.com/products/isbn/'.$isbn);

    if ( strpos( $abedata, 'The ISBN is not valid.') === false && strlen ($abedata) > 1) {
// Crap, abebooks have changed their website already!
//      $t_start = strpos( $abedata, '<h2 id="plp-sub-heading" class="nopadding plptitle">') + 52;
      $t_start = strpos( $abedata, '<meta itemprop="name" content="') + 31;
      $t_end   = strpos( $abedata, '" />', $t_start);
      if ($t_start > 0) {
        $title   = substr( $abedata,  $t_start, $t_end - $t_start);
      }      
      $a_start = strpos( $abedata, '<span id="author-1">') + 20;
      $a_end   = strpos( $abedata, '</span>', $a_start);   
      $author  = substr( $abedata,  $a_start, $a_end - $a_start);
      $d_start = strpos( $abedata, '<span id="publish-date">') + 24;
      $d_end   = strpos( $abedata, '</span>', $d_start);   
      $year    = substr( $abedata,  $d_start, $d_end - $d_start);
      $p_start = strpos($abedata, '<span id="publisher">') + 21;
      $p_end   = strpos( $abedata, '</span>', $p_start);
      $publisher = substr( $abedata,  $p_start, $p_end - $p_start);
      $syn_exists = strpos( $abedata, '<div role="tabpanel"  id="synopsis"' );   
      if ($syn_exists > 0){
        $syn_start = strpos( $abedata, 'class="toggle">', $syn_exists) + 15;
        $syn_end   = strpos( $abedata, '</div>', $syn_start);   
        $description = substr( $abedata,  $syn_start, $syn_end - $syn_start);
      }

    } else {
      $isbndbxml = file_get_contents('http://isbndb.com/api/books.xml?access_key=A625OKS5&index1=isbn&value1='.$isbn);
      if ( strpos( $isbndbxml, 'BookList total_results="1"') === false ) {
        $title = $node->title.' (BOOK '.$isbn.' not found at isbndb.com or abebooks.com - sorry!)';
      } else {
        $t_start = strpos( $isbndbxml, '<Title>');
        $t_end = strpos( $isbndbxml, '</Title>');
        $title = substr( $isbndbxml,  $t_start + 7, $t_end -  $t_start - 7 );      
        $a_start = strpos( $isbndbxml, '<AuthorsText>');
        $a_end = strpos( $isbndbxml, '</AuthorsText>');      
        $author = substr( $isbndbxml,  $a_start + 13, $a_end -  $a_start - 13 );
        $d_almost_start = strpos( $isbndbxml, '<PublisherText publisher_id="');
        $d_start = strpos( $isbndbxml, '">', $d_almost_start) ;
        $d_end = strpos( $isbndbxml, '</PublisherText>');  
        $year = substr( $isbndbxml,  $d_start + 2, $d_end -  $d_start - 2 );
        $description = '';
    }

    
      
// change TZZ.. to MZZ.. to get bigger. see: http://digilib.weblog.ub.rug.nl/node/48
//      $image = '<a href="http://www.amazon.com/gp/product/'.$isbn.'/"><img src="http://images.amazon.com/images/P/'.$isbn.'.01.TZZZZZZZ.jpg"></a>';
      
// Ok, let's try to get the image:

//   $image_count = count($node->field_picture);
   $image_import = write_image_info('http://images.amazon.com/images/P/'.$isbn.'.01.MZZZZZZZ.jpg', 'amazon_image_'.$isbn,  $fid);


// if this has worked make this a book

    $item->title = $title;


   $item->field_picture[$node->language][0] = (array)$image_import;
//$node->field_picture[$image_count]['fid'] = $fid;
//$node->field_picture[$image_count]['data']['description'] = $image_description;
//$node->field_picture[$image_count]['data']['alt'] = $image_alt;
//$node->field_picture[$image_count]['data']['title'] = $image_title;

    }

    
// This is really naughty, but until Drupal 8 supplies field_set_items, it's the lazy way:
    $item->body[LANGUAGE_NONE][0]['value'] = $description;
    //.'<br>'.$image;  
    $item->field_year[LANGUAGE_NONE][0]['value'] = $year;                
    $item->field_author[LANGUAGE_NONE][0]['value'] = $author;                
	if ($publisher) {
		$item->field_publisher_information[LANGUAGE_NONE][0]['value'] = $publisher;
	}

 
 
 return $item;
}


function diolibrary_node_validate($node, $form, &$form_state) {
	//print array details for debugging purposes      
   	/* print "<pre>";
    print_r($form_state);
	print "</pre>"; */
  
	if ($form_state['build_info']['form_id'] == 'library_item_node_form') { 
  	//form_set_error('title1', "in");

		for ($i=1; $i <= 2; $i++) {
	    	if ($form_state['values']['title'.$i] !== "" && $form_state['values']['field_categories'.$i]['und'][0]['tid'] == "") {
    	    	form_set_error('field_categories'.$i, 'The categories field is compulsory for any item you attempt to add');
        	}
        }  
	}
          
}



/*
    case 'presave':
*/
function diolibrary_node_presave($node) {//$form, &$form_state){
      // if its a barcode we must set the category fields and get title etc
      if ($node->form_id == 'library_item_node_form' ) {
        //diolibrary_check_for_book_barcode( $node );
      }
 }

function diolibrary_node_insert($node) {  
    if ($node->form_id == 'library_item_node_form' /* && !isset($node->not_orig_node) */ ) { // && there is extra data/a new node

		for ($i = 1; $i <= 2; $i++) {

    		if ($node->{'title'.$i} != "") {

 				//get book data           	
            	$item[$i] = diolibrary_check_for_book_barcode($node->{'title'.$i});

              	// build another node, save it, remove extra data from original node
                $node->title = $item[$i]->title;
                $node->body = $item[$i]->body[LANGUAGE_NONE][0]['value'];
                $node->teaser = $item[$i]->body[LANGUAGE_NONE][0]['value'];

/*
  				//the below are just guesses, haven't tested yet cos form stopped working.
  				//might be $node->taxonomy, might be $node->{'field_categories'.$i} or something within that.. 
  				$node->taxonomy = $node->{'taxonomy'.$i};
  				$node->field_object_type = $node->{'object_type'.$i};
  				$node->field_author = $item->field_author[LANGUAGE_NONE][0]['value'];
  				$node->field_year = $item->field_year[LANGUAGE_NONE][0]['value'];
				$node->field_publisher_information = $item->field_publisher_information[LANGUAGE_NONE][0]['value'];
				$node->field_picture = $item->field_picture[$node->language][0];
*/

                unset($node->nid);
                unset($node->vid);
                //set to stop this going recursive - dont think we need this
                //$node->not_orig_node = TRUE;
                node_save($node);
                drupal_set_message("Library item <i>" . $node->title . "</i> has been created.");
            }
        }
    }
}

//9780060081584

/*
//brett: override form theme to have multiple nodes
function sharehood_theme($existing, $type, $theme, $path) {
  return array(
    'item_node_form' => array(
    'arguments' => array('form' => NULL)
     )
  );
}

*/

/*not sure if we need this, hopefully not
function theme_item_node_form($form) {
  $header = array("What is it?", "Categories:", "Comments:");
  $row[] = array(drupal_render($form['title']), drupal_render($form['taxonomy']), drupal_render($form['body_field']));
  if (!isset($form['title']['#default_value']) ) {  //single edit node form
    for($i=2; $i <= SHAREHOOD_NUM_NODES; $i++) {
      $row[] = array(drupal_render($form['title'.$i]), drupal_render($form['taxonomy'.$i]), drupal_render($form['body'.$i]));
    }
  }
  $output = theme_table( $header, $row);
  $output .= drupal_render($form); // Process any other fields and display them
  return $output;
}
*/



karthid’s picture

Is Form Id is printing fine inside ?

fudge714’s picture

what do you mean?

fudge714’s picture

just uncommented the stuff to print the form array inside hook_alter if thats what you mean, and its not printing. it seems as if the function is just not getting called. i also tried printing something before the form_id if, and it didn't print that either

kunalkursija’s picture

Hey,

Just some quick observations.

1) You have not defined $form_state properly, Its a reference to $form_state represented as &$form_state.

2) In your hook_node_insert, You have written node_save() . I doubt if that should be written inside, cause hook_node_insert() is called by node_save() itself. I think this is becoming a infinite loop.

3) You can try commenting everything in this file except form_alter, Specially the node_hooks (Presave and insert) .

Please correct step 1. And let us know if form_alter got called.

Question : Where have you written this hook_form_alter() ?, Is it in one of your Inc files ?

P.S : There could be a possibility that you have defined your hook name "diolibrary_form_alter" TWICE, once in your .module file and other in your inc file or something like that, This is just a guess :)

fudge714’s picture

I'm guessing its not anything to do with the code though, since it was working at the start of the night and even if I upload the file from that time, it still doesn't work.

In case its useful though, tonight I was mainly editing in the node_insert function

oh and if a bit of context might be useful for reading the code, its basically a module for a library cataloging system. The main thing is changing the form so that multiple items can be added at once, and grabbing all the data from websites from the isbn which we can input easily with a barcode scanner.

leramos’s picture

Hi fudge714,

As what kunal.kursija suggested, you could try commenting all of the functions inside your module file except the hook_form_alter. Then comment all of your code inside the hook_form_alter then try to put
drupal_set_message($form_id); only.

If it shows the form_id in all the forms you are hitting then your hook_form_alter is working fine. Then try uncommenting your functions one by one , see if your form alter still works, and to verify what is causing the trouble.

You could also try using hook_form_FORM_ID_alter() as an alternative.

And also don't forget to pass $form_state by reference (&$form_state), make sure your module is enabled, you are using the correct module name in your hooks, no duplicate form alters, and clear caches from time to time.

Regards,
leramos

fudge714’s picture

thanks guys, turned out I was only clearing my browser cache and not the server cache and that did it.

and thanks for pointing out the other issues as well..