I am basically trying to create a function which would take an array of elements, and then use the entity_create() function to create an entry in a custom entity that I created passed on the values passed inside the array:

function entm_add($arr)
{
	$projects = entity_load('entm', array($arr[0]));

	if (!isset($projects[$arr[0]]))
	 {
	   $enn = entity_create('entdemo', array('id' => $arr[0]));
	   $enn->name = t($arr[1]);
	   $enn->nickname = t($arr[2]);
	   $enn->save();
	 }
 	return 'Some string';
}

$arr = array(3, 'Tye Dillinger', 'Ten');
entm_add($arr);

In the above example, 'entm' is my custom entity. I am now calling the 'entm_add()' function and passing $arr as the parameters. The 'entm_add()' function then creates a new entity node using the entity_create() function. However, I'm encountering the following error:

Fatal error: Call to undefined function field_info_instances() in /opt/lampp/htdocs/drupal/sites/all/modules/entityreference/entityreference.module on line 366

However, this works perfectly fine:


function entm_menu() {
 $items['entm/add'] = array(
    'title' => 'View ENTMs',
    'page callback' => 'entm_add',
    'access arguments' => array('access content'),
    'type' => MENU_SUGGESTED_ITEM,
  );

  return $items;
}

function entm_add()
{
	$projects = entity_load('entm', array(1, 2, 3, 4));

	 if (!isset($projects[4])) {
	   $entity = entity_create('entm', array('id' => 4));
	   $entity->name = t('TYE');
	   $entity->nickname = t('ten');
	   $entity->save();
 }


 return 'Some string';
}

What seems to be wrong with my first approach?

Comments

leramos’s picture

Hi,

In your first approach, Seems like you are calling the function you created outside a Drupal hook, function or a callback. Assuming that your code is in .module file, you can't call functions directly. It must be inside a hook, or a callback.

In your 2nd approach, you specified it as a callback function of the menu item you created in hook_menu that is why it is working.