Witam mam taka zagwozdkę.
Struktura tabeli w uproszczeniu.
item_type, item_type_id, ad_id
TypeImage, 1, 1
TypeImage, 2, 1
TypeDescription, 1, 1
Gdzie
item_type (enum) to Encja np ItemTypeImage, ItemTypeDescription
item_type_id to id encji
ad_id to id "właściciela" dla tych wpisów.
PRIMARY_KEY item_type, item_type_id
i teraz
kontroler
$items = $repository->getItems($entity, $this->container->get('templating'));
return $this->render('AppMainBundle:Ad:view.html.twig', [
'entity' => $entity,
'items' => $items
]);
repository
public function getItems(Ad $entity, TwigEngine $templating) {
$em = $this->getEntityManager();
$queryBuilder = $em->createQueryBuilder();
$queryBuilder->from('AppMainBundle:AdItem', 'ai');
$queryBuilder->select('ai');
$queryBuilder->where($queryBuilder->expr()->eq('ai.ad', $entity->getId()));
$queryBuilder->andWhere($queryBuilder->expr()->eq('ai.active', true));
$queryBuilder->orderBy('ai.weight', 'ASC');
foreach ($queryBuilder->getQuery()->getResult() as $adItem) {
try {
$typeRepository = $em->getRepository('AppMainBundle:' . $adItem->getItemType());
$typeEntity = $typeRepository->find($adItem->getItemTypeId());
if ($typeEntity) {
yield new AdItemModel($adItem, $typeEntity, $templating);
}
} catch (\Exception $exc) {
dump($exc->getMessage());
}
}
}
AdItemModel
class AdItemModel {
private $adItem;
private $typeEntity;
private $templating;
public final function __construct(AdItem $adItem, ItemTypeInterface $typeEntity, TwigEngine $templating) {
$this->adItem = $adItem;
$this->typeEntity = $typeEntity;
$this->templating = $templating;
}
public final function getAdItem() {
return $this->adItem;
}
public final function getTypeEntity() {
return $this->typeEntity;
}
public final function view() {
try {
return $this->templating->render('AppMainBundle:AdItemType:' . $this->getAdItem()->getItemType() . '.html.twig', [
'adItem' => $this->getAdItem(),
'typeEntity' => $this->getTypeEntity(),
]);
} catch (\Exception $exc) {
return $exc->getMessage() . PHP_EOL;
}
}
}
view.html.twig
{% for item in items %}
<div class="item {{ item.adItem.getItemTypeClass }}"> {{ item.view }}
{% endfor %}
Generalnie wykonując item.view chce wypluć templatkę encji i w przypadku gdy zdefiniuję nowy typ przechwycić to do wyjątku jeśli templatka nie istnieje lub opcjonalnie poślę tam templatkę domyślną ale wynik === nic, null, zero, czarna dziura
Natomiast w przypadku braku templatki wynik to
Kod
Unable to find template "AppMainBundle:AdItemType:ItemTypeText.html.twig" (looked into: C:\WTServer\WWW\projekt\app/Resources/views, C:\WTServer\WWW\projekt\vendor\symfony\symfony\src\Symfony\Bridge\Twig/Resources/views/Form, C:\WTServer\WWW\projekt\vendor\knplabs\knp-menu\src\Knp\Menu/Resources/views).
Dziwi mnie to że nie szuka w AppMainBundle to raz i nie wpadłem jak ten problem rozwiązać.
Do moderacji. Przepraszam temat do usunięcia znalazłem błąd chwile po dodaniu wpisu.
Ten post edytował mcmaroon 24.02.2017, 22:46:50