2014-09-19 94 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(); 
}