Отсутствует связующее свойство у сущности типа node.

Главные вкладки

Аватар пользователя univerico univerico 11 июня 2018 в 19:08

На сайте после попытки создания импортера feeds появилась ошибка.
EntityMalformedException: Отсутствует связующее свойство у сущности типа node. в функции entity_extract_ids() (строка 8074 в файле .../includes/common.inc).
Похожая проблема была при работе с теримнами в этой теме .
У меня была работа с теримнами. но в тексте ошибки все же про ноды.
С чем может быть связана такая ошика?
Код строчки и соседней
throw new EntityMalformedException(t('Missing bundle property on entity of type entity_type.', array('entity_type' => $entity_type)));
Код всей функции

function entity_extract_ids($entity_type, $entity) {
  $info = entity_get_info($entity_type);

  // Objects being created might not have id/vid yet.
  $id = isset($entity->{$info['entity keys']['id']}) ? $entity->{$info['entity keys']['id']} : NULL;
  $vid = ($info['entity keys']['revision'] && isset($entity->{$info['entity keys']['revision']})) ? $entity->{$info['entity keys']['revision']} : NULL;

  if (!empty($info['entity keys']['bundle'])) {
    // Explicitly fail for malformed entities missing the bundle property.
    if (!isset($entity->{$info['entity keys']['bundle']}) || $entity->{$info['entity keys']['bundle']} === '') {
      throw new EntityMalformedException(t('Missing bundle property on entity of type entity_type.', array('entity_type' => $entity_type)));
    }
    $bundle = $entity->{$info['entity keys']['bundle']};
  }
  else {
    // The entity type provides no bundle key: assume a single bundle, named
    // after the entity type.
    $bundle = $entity_type;
  }

  return array($id, $vid, $bundle);
}

Лучший ответ

Аватар пользователя univerico univerico 29 июня 2018 в 21:07

Удалось временно наладить возможность создания новых импортеров обычным способом без клонирования после установки dev версии модуля
по рекомендации из этой темы о версии feeds с помощью команды drush dl feeds --dev

Комментарии

Аватар пользователя univerico univerico 11 июня 2018 в 22:01

Некоторые объяснения нашлись здесь https://drupal.stackexchange.com/questions/111610/how-to-debug-entitymal...
В качестве решения предлагают следующее
помстить var_dump(debug_backtrace()); or dd(debug_backtrace()); (при включенном Devel) " before the actual throw new EntityMalformedException on the affected line in common.inc".
Т.е. нужно в файл
common.inc"
перед строкой 8074 в моем случае поместить
var_dump(debug_backtrace())
Если у меня сейчас

 if (!empty($info['entity keys']['bundle'])) {
    // Explicitly fail for malformed entities missing the bundle property.
    if (!isset($entity->{$info['entity keys']['bundle']}) || $entity->{$info['entity keys']['bundle']} === '') {
      throw new EntityMalformedException(t('Missing bundle property on entity of type @entity_type.', array('@entity_type' => $entity_type)));
    }

То нужно в тело
{$info['entity keys']['bundle']} === '') {

перед
 throw new EntityMalformedException

Чтобы стало

{$info['entity keys']['bundle']} === '') {
     var_dump(debug_backtrace())
 throw new EntityMalformedException(t('Missing bundle property on entity of type @entity_type.', array('@entity_type' => $entity_type)));

Или куда?
Подробнее по этой ошибке там написано:
Note: Using dd() function from Devel will generate the debugging info to the file in your Drupal temp folder (temporary://drupal_debug.txt) with backtrace dump, otherwise could be too big and difficult to read when dumping on the screen. When using var_dump(), it's easier to call die(); after the call and check the dump in the view-source mode of the page.

Значение $info['entity keys']['bundle'] (для ноды это: type) не может быть найдено в $entity object ($node->type for the node)
И как причина
saving invalid entity such as:

missing type from the node object (e.g. wrongly generated by Devel Generate?);
orphaned nodes in node table;

invalid rows in field_data_field_xxx table;
having orphaned nodes, caused by:
search view having indexed nodes which aren't in the system;
other modules (like Feeds) removing nodes from Drupal improperly;
nodes having invalid/non-existing references; for term data this can be checked by:

drush sqlq "SELECT nid, title from node WHERE nid IN (select entity_id from field_data_field_some_ref WHERE field_some_ref_tid not IN (select tid from taxonomy_term_data));"
Where field_data_field_some_ref is data field of field_some_ref which is type of 'Term reference'.

See: DB records not deleted for Term Reference Fields after Term is Deleted

having orphaned taxonomy terms (so you may use Taxonomy Orphanage);

entity caching issue;
when using Rules Link module;
invalid custom code (human error) such as:

badly implemented Entity API,
badly implemented CTools/Form API,
!empty() test on the entity variable before calling field_get_items(),
rendering field by invalid calls,
triggering functions which shouldn't be triggered on certain pages (e.g. field_view_field()),

Аватар пользователя univerico univerico 14 июня 2018 в 0:00

В моем случае пробую применить patch, так как использую на сайте feeds, а это может быть одной из причин этой ошибки, добавить функцию не получилось.
Подробнее
Применение функции Функция var_dump(debug_backtrace()) не помогло
При попытках расположить ее в разных местах проблемной функции и перед ней либо ошибка 500, либо сохранение той же ошибки и вывод кода php с кучей массивов прямо на странице сайта.
Например <?php array(17) { [0]=> array(4) { ["file"]=> string(109"/home/handmad3/major-minor.info/sites/all/modules/entity_translation/includes/translation.handler_factory.inc" ["line"]=> int(112) ["function"]=> string(18"entity_extract_ids" ["args"]=> array(2) { [0]=> &string(4"node" [1]=> object(stdClass)#409 (11) { ["type"]=> NULL ["is_new"]=> bool(true) ["status"]=> int(1) ["promote"]=> int(1) ["sticky"]=> int(0) ["uid"]=> string(1) "1" ["created"]=> int(1528792808) ["revision"]=> bool(false) ["book"]=> array(12) { ["original_bid"]=> int?>
Но еще один возможный ответ нашелся на https://drupal.stackexchange.com/questions/111610/how-to-debug-entitymal...
having orphaned nodes, caused by:
• search view having indexed nodes which aren't in the system;
• other modules (like Feeds) removing nodes from Drupal improperly;

в этой теме, предлагают пэтч feeds-orphaned-feeds-item-1394320-45.patch.

пробую его применить.

Аватар пользователя univerico univerico 14 июня 2018 в 1:03

Пытаюсь применить пэтч через комнадную строку, но не получается
Как правильно через командную строку применить 45 пэтч отсюда https://www.drupal.org/project/feeds/issues/1394320

Я делаю, но не получается cd .../sites/all/modules/feeds
[... feeds]$ patch -p0 < feeds-orphaned-feeds-item-1394320-45.patch
(Stripping trailing CRs from patch.)

Получаю ответ
can't find file to patch at input line 5
Perhaps you used the wrong -p or --strip option?
The text leading up to this was:
--------------------------
|diff --git a/plugins/FeedsProcessor.inc b/plugins/FeedsProcessor.inc
|index 0644feb..6a1111e 100644
|--- a/plugins/FeedsProcessor.inc
|+++ b/plugins/FeedsProcessor.inc
--------------------------
File to patch: просто ввожу пару символов чтобы перейти на следующий шаг
(или нужно было праивильный файл указать? какой?)
No such file or directory
Skip this patch? [y] y (пропускаю)
Skipping patch.
6 out of 6 hunks ignored
(Stripping trailing CRs from patch.)
can't find file to patch at input line 167
Perhaps you used the wrong -p or --strip option?
The text leading up to this was:
--------------------------
|diff --git a/tests/feeds_processor_node.test b/tests/feeds_processor_node.test
|index 8c1893a..6b1da8e 100644
|--- a/tests/feeds_processor_node.test
|+++ b/tests/feeds_processor_node.test
--------------------------
File to patch: t
t: No such file or directory
Skip this patch? [y] y
Skipping patch.
patch unexpectedly ends in middle of line
1 out of 1 hunk ignored
[... feeds]$ ^C
[... feeds]$ patch -p0 < feeds-orphaned-feeds-item-1394320-45.patch
(Stripping trailing CRs from patch.)
can't find file to patch at input line 5
Perhaps you used the wrong -p or --strip option?
The text leading up to this was:
--------------------------
|diff --git a/plugins/FeedsProcessor.inc b/plugins/FeedsProcessor.inc
|index 0644feb..6a1111e 100644
|--- a/plugins/FeedsProcessor.inc
|+++ b/plugins/FeedsProcessor.inc
--------------------------
File to patch: f
f: No such file or directory
Skip this patch? [y] y
Skipping patch.
6 out of 6 hunks ignored
(Stripping trailing CRs from patch.)
can't find file to patch at input line 167
Perhaps you used the wrong -p or --strip option?
The text leading up to this was:
--------------------------
|diff --git a/tests/feeds_processor_node.test b/tests/feeds_processor_node.test
|index 8c1893a..6b1da8e 100644
|--- a/tests/feeds_processor_node.test
|+++ b/tests/feeds_processor_node.test
--------------------------
File to patch: xxx (просто ввожу символ чтобы перейти на слебущий шаг и посмотреть, что будет, нормальный файл не указываю, так как не заню какой)
g: No such file or directory
Skip this patch? [y] y
Skipping patch.
patch unexpectedly ends in middle of line
1 out of 1 hunk ignored

Когда для пробы ввожу с p1
[....feeds]$ patch –p1 < feeds-orphaned-feeds-item-1394320-45.patch
(Stripping trailing CRs from patch.)
patching file –p1
Hunk #1 FAILED at 32.
Hunk #2 FAILED at 116.
Hunk #3 FAILED at 131.
Hunk #4 FAILED at 236.
Hunk #5 FAILED at 250.
Hunk #6 FAILED at 411.
6 out of 6 hunks FAILED -- saving rejects to file –p1.rej
(Stripping trailing CRs from patch.)
patching file –p1
patch unexpectedly ends in middle of line
Hunk #1 FAILED at 721.
1 out of 1 hunk FAILED -- saving rejects to file –p1.rej

Аватар пользователя univerico univerico 14 июня 2018 в 20:23

В резлуьтате обсуждения в этой теме по пэтчу отчасти удалось применить пэтч
Но все равно ошибка сохранилась.
Еще уточнение что при устновке feeds были следующие предупреждения:
The following module is missing from the file system: commerce_kickstart_theme. For information
about how to fix this, see the documentation
page
. bootstrap.inc:1143
Unknown path for commerce_kickstart_theme module. [warning]
The following module is missing from the file system: commerce_kickstart_admin. For information
about how to fix this, see the documentation
page
. bootstrap.inc:1143
Unknown path for commerce_kickstart_admin module. [warning]

Аватар пользователя univerico univerico 14 июня 2018 в 21:15

Спасибо. Они вроде вручную не удалялись. Возможно с помощью drush. Но проверяю сейчас с помощью drush en -y пишет что включены. Деинсталировать через UI или drush dis?

Аватар пользователя univerico univerico 15 июня 2018 в 0:41

Спасибо. Предупреждение исчезло после устранения проблемы с commerce_kickstart_theme и admin, но путем их в ключения в папке profile.

После перемещения в sites/all/modules и
drush dis commerce_kickstart_admin -y
Сообщение
There were no extensions that could be disabled.

После перемещения их назад в /profiles/commerce_kickstart/themes
и включения ошибка при включении feeds исчезла.

Хотя возможно я не так все же что-то делаю.

Но на ошибку о связующем звене сущности это не повлияло.

Аватар пользователя sas@drupal.org sas@drupal.org 15 июня 2018 в 8:30
1

EntityMalformedException часто появляется при попытке использовать свойство объекта которого нет, например после node_load или entity_load и использования далее результата без проверки удачно ли прошла загрузка.

Аватар пользователя univerico univerico 15 июня 2018 в 11:58

Спасибо в принципе это было понятно, но после Вашего акцента пришла идея в голову, которая решила хотя бы на время эту проблему. У меня эта ошибка появилась после создания импортера и появляется только при попытке открыть теперь уже любой импортер (не только тогда созданный). Попытка удалить все новые ноды не помгла. Удаление этого импортера ликвидировало ошибку.
Имеющиеся импортеры открываются. Но создать новый не получается. Сразу после первого же шага (создание имени импортера и машинного имени) после сохранения снова появляется ошибка при попытке открыть этот импортер (другие пока открываются).
Пока времнно тогда буду просто клонировать имеющиеся импортеры и редактировать тогда.

Аватар пользователя univerico univerico 29 июня 2018 в 21:07

Удалось временно наладить возможность создания новых импортеров обычным способом без клонирования после установки dev версии модуля
по рекомендации из этой темы о версии feeds с помощью команды drush dl feeds --dev