2014-09-19 96 views
0

我收到元数据封装器的错误。 我有一个字段测试=>实体引用多个这是一个选择列表。我得到以下错误EntityMetadataWrapperException:给出无效的数据值。确保它匹配所需的数据类型和格式。实体元数据封装器

$account = entity_load_single('user', $user->uid); 
    $acc_wrapper = entity_metadata_wrapper('user', $account); 
    $list = $acc_wrapper->test->value(); 
    $exists = FALSE; 
    if (!empty($list)) { 
    foreach ($list as $item) { 
     if ($item->nid == $form_state['storage']['node']->nid) { 
     $exists = TRUE; 
     break; 
     } 
    } 
    } 
    if (!$exists) { 
    if (!$list) { 
     $list = array(); 
     $list[] = $form_state['storage']['node']->nid; 
    } 

$acc_wrapper->test->set($list); 
$acc_wrapper->save(); 

回答

0

1RST快速提示

$account = entity_load_single('user', $user->uid); 
$acc_wrapper = entity_metadata_wrapper('user', $account); 

你不需要,除非你需要它加载后(或者它已经加载)来加载实体。所有你需要的是ID,并让entity_metadata_wrapper魔术运行。

$acc_wrapper = entity_metadata_wrapper('user', $user->uid); 

,我认为你的错误是在这里

if (!$list) { 
    $list = array(); 
    $list[] = $form_state['storage']['node']->nid; 
} 

$列表始终启动,因为 “$名单= $ acc_wrapper->测试 - >值();”,所以你永远fullfill条件,然后你试图将其设置回来并保存它(因为你缺少'}')...没有意义...

可以试试这个版本吗?

$acc_wrapper = entity_metadata_wrapper('user', $user->uid); 
$list = $acc_wrapper->test->value(); 
$exists = FALSE; 

if (!empty($list)) { 
    foreach ($list as $item) { 
    if ($item->nid == $form_state['storage']['node']->nid) { 
     $exists = TRUE; 
     break; 
    } 
    } 
} 
if (!$exists && !$list) { 
    $list = array($form_state['storage']['node']->nid); 

    $acc_wrapper->test = $list; 
    $acc_wrapper->save(); 
}