I have made a category and want to make sub category, how can I add dynamically? - eloquent

I made a form in which I have titlte, image, pdf, content and category and all are working fine, but I want to add submenu in my form and also want to make this dynamic so can show all sub-menu on my website.

You must have to intruduce a key parent_id with categories table.
And in category model do create the relation like this.
class Category extends Model
{
public $fillable = ['title','parent_id'];
/**
* Get the index name for the model.
*
* #return string
*/
public function childs() {
return $this->hasMany('App\Category','parent_id','id') ;
}
}
Here you can find the complete example..https://itsolutionstuff.com/post/laravel-5-category-treeview-hierarchical-structure-example-with-demoexample.html
Hopefully this could help you.

Related

how insert sys_categories with extbase

in a extbase extension i us sys_category. In list action there is no problem, all categories work as expected. But i want to write category entries with a custom database finisher from tx_form.
In the model all seems correct:
/**
* Sets the categories
*
* #param \TYPO3\CMS\Extbase\Persistence\ObjectStorage $categories
* #return void
*/
public function setCategories($categories)
{
$this->categories = $categories;
}
in my finisher:
$newAddress->setCategories($newCat);
$this->addressRepository->add($newAddress);
The form gives me only the uid of the category but for "setCategories" i need an \TYPO3\CMS\Extbase\Persistence\ObjectStorage.
How do i get a \TYPO3\CMS\Extbase\Persistence\ObjectStorage from the uid of the category?
Thanks!
You need a setter method for the categories like this:
public function addCategory($category)
{
$this->categories->attach($category);
}
This method will add one model to your object storage.
As you need the category model to be added, you need to get the corresponding model of the uid with $categoryRepository->findByUid($uid);

TYPO3 : How to determine child-objecttypes of specific parent domain-model?

I have some different domain-models, each being parent of different sub-models.
All of those domain-models extend themselves out of a basic model class and I want to write a general function in the base-model, that deals with subclasses of the current model. Therefore, I need to find a way, to dynamically get all child-model-classes of a given domain-model.
Can this be done somehow ? Perhaps via Object-Storage-Definitions or similar ?!
Update : as mentioned in the comment section, mny question had nothing to do with TYPO3, it was a general php-question .. solution for my question are reflection-classes.
I guess your question has nothing to do with TYPO3, so take a look at this general PHP question thread and possible solutions here.
You are talking about Database Relationships. Yes, this can be done in TYPO3.
Each model should be mapped to a table. So, let's take for example the Category domain model and parent property
class Category extends AbstractEntity
{
/**
* #var \TYPO3\CMS\Extbase\Domain\Model\Category
*/
protected $parent = null;
/**
* #return \TYPO3\CMS\Extbase\Domain\Model\Category
*/
public function getParent()
{
if ($this->parent instanceof \TYPO3\CMS\Extbase\Persistence\Generic\LazyLoadingProxy) {
$this->parent->_loadRealInstance();
}
return $this->parent;
}
/**
* #param \TYPO3\CMS\Extbase\Domain\Model\Category $parent
*/
public function setParent(\TYPO3\CMS\Extbase\Domain\Model\Category $parent)
{
$this->parent = $parent;
}
The parent property will return the parent category. The same logic is when you want to get the childs.

template for list view with system categories

I have an extbase extension (TYPO3 7) with a simple model of a contact person.
The person has a name and a picture.
So far this is clear.
But every Person has a category (e.g. where he works. Office, Marketing etc.)
Therefor i use the system categories, as described here:
https://wiki.typo3.org/TYPO3_6.0#Adding_categories_to_own_models_without_using_Extension_Builder
When creating a person via web > list, i can assign a category.
Now the question for templating:
If i debug my contact person, i get the output like screen below.
I want to have a list where every category (headline) is shown with it's contact persons.
How to do this?
Is the logic for this only in the template or also in the controller?
Has anybody an example for this?
Best regards
Markus
I guess the required logic you need is possible with Fluid with using the GroupedFor ViewHelper and many others. Because a person can have multiple categories this would become a huge nesting of Viewhelpers so I can not recommend to use Fluid for this even if its possible. This kind of logics belong to the controllers, models and repositories.
There are multiple ways to solve this logic. Here is an example how to realize this in the controller...
Controller:
/**
* #var \TYPO3\CMS\Extbase\Domain\Repository\CategoryRepository
* #inject
*/
protected $categoryRespoitory = NULL;
/**
* action list
* #return void
*/
public function listAction()
{
$allCategories = $this->categoryRespoitory->findAll();
$categoriesWithContacts = [];
/** #var \TYPO3\CMS\Extbase\Domain\Model\Category $category */
foreach($allCategories as $category) {
$contactsInCategory= $this->contactRepository->findByCategory($category);
if($contactsInCategory->count()>0) {
$categoriesWithContacts[] = [
'category' => $category,
'contacts' => $contactsInCategory
];
}
}
$this->view->assignMultiple([
'categoriesWithContacts' => $categoriesWithContacts
]);
}
Injecting the CategoryRespository will required clearing cache in install tool or reinstalling the extension.
Maybe you need this function in your ContactRepository:
/**
* #param \TYPO3\CMS\Extbase\Domain\Model\Category $category
* #return array|\TYPO3\CMS\Extbase\Persistence\QueryResultInterface
*/
public function findByCategory(\TYPO3\CMS\Extbase\Domain\Model\Category $category) {
$query = $this->createQuery();
return $query->matching($query->contains('categories', $category))->execute();
}
Then in Fluid you can do something like this:
<f:for each="{categoriesWithContacts}" as="categoryWithContact">
{categoryWithContact.category.title}
<f:for each="{categoryWithContact.contacts}" as="contact">
{contact.name}
</f:for>
</f:for>

Magento 2: Get Product Stock Quantity and Other Stock Information

Magento 2: Get Product Stock Quantity and Other Stock Information
How to get the product stock quantity and information in magento 2
If we look at the StockItemRepository class the get method wants parameter $stockItemId, not $productId. Reference:
https://github.com/magento/magento2/blob/develop/app/code/Magento/CatalogInventory/Model/Stock/StockItemRepository.php#L202
I've seen many sites where stock item id IS NOT the same as product id and we should not assume it's the same ID.
To get this working you could use \Magento\CatalogInventory\Model\Stock\Item class instead and load the model by product_id field instead. I am also aware of the website_id and stock_id fields, but as far as I know it's not used (yet) and also existed in M1.
It should look something like this (code not tested):
<?php
namespace Vendor\Module\Model;
use \Magento\CatalogInventory\Model\Stock\Item;
class Mymodel
{
/**
* #var Item
*/
protected $stockItem;
/**
* Mymodel constructor.
*
* #param Item $stockItem
*/
public function __construct(Item $stockItem)
{
$this->stockItem = $stockItem;
}
/**
* Description
*
* #param $productModel
*/
public function getStockQtyByProductId($productModel)
{
try {
$stockItem = $this->stockItem->load($productModel->getId(), 'product_id');
return $stockItem->getQty();
} catch (\Exception $e) {
echo 'Something went wrong and was not handled: ' . $e->getMessage();
exit;
}
}
}
if you have product object then just use following:
echo $_product->getExtensionAttributes()->getStockItem()->getQty();
conplete object can be find as follow:
var_dump($_product->getExtensionAttributes()->getStockItem()->getData());
Actually this operation should be performed using \Magento\CatalogInventory\Api\StockRegistryInterface and here we can obtain \Magento\CatalogInventory\Api\Data\StockItemInterface, by product id or sku and we can use bunch of usefull methods to get stock information - linked product. For general stock information I recommend explore other service contracts declared in Magento\CatalogInventory\Api
Example of usage:
<?php
namespace Test\Test\Model;
class Test
{
protected $_stockRegistry;
public function __construct(\Magento\CatalogInventory\Api\StockRegistryInterface $stockRegistry)
{
$this->_stockRegistry = $stockRegistry;
}
public function getStockItem($productId)
{
return $this->_stockRegistry->getStockItem($productId);
}
}
this code help you to get product quantity
<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$StockState = $objectManager->get('\Magento\CatalogInventory\Api\StockStateInterface');
echo $StockState->getStockQty($productId);
?>
If you have the product object and do not want to use the other classes, You can try in the following way.
// For phtml file
$prodObj = $_product->load($_product->getId()); // $_product object in list.phtml
$stockItem = $prodObj->getExtensionAttributes()->getStockItem();
$stockQty = $stockItem->getQty(); // $stockItemData = $stockItem->getData();
// For php class file
$stockItem = $prodObj->getExtensionAttributes()->getStockItem();
$stockQty = $stockItem->getQty(); // $stockItemData = $stockItem->getData();
Credits:
https://github.com/magento/magento2/issues/7057#issuecomment-256052729
Actually \Magento\CatalogInventory\Api\Data\StockStatusInterface
should answer to all your questions.
Long story short:
Magento has StockItem entity which represents amount (Qty) of specific product (productId) on a concrete stock (stockId).
StockItemInterface should be used when you would like to "write" data into the data storage (like update amount of products to sync up Magento with your ERP system or to make deduction of stock during the checkout process).
StockStatusInterface is opposite to it. It should be used to "read" data for representation (on front-end). Consider StockStatus as an index which contains aggregated stock data for each specific product.
So, if you would like to get product stock status (in stock, out of stock) by product_id.
You need using StockStatusRepositoryInterface::getList(StockStatusCriteriaInterface $searchCriteria);
get StockStatus entity for specified product
/** #var \Magento\CatalogInventory\Api\StockStatusCriteriaInterfaceFactory $stockStatusCriteriaFactory **/
$criteria = $stockStatusCriteriaFactory->create();
$criteria->setProductsFilter($productId);
/** #var \Magento\CatalogInventory\Api\Data\StockStatusRepositoryInterface $stockStatusRepository **/
$result = $stockStatusRepository->getList($criteria);
$stockStatus = current($result->getItems());
$stockStatus->getProductId(); // product id
$stockStatus->getQty(); // quantity of specified product
$stockStatus->getStockStatus(); // Could be
// Magento\CatalogInventory\Model\Stock\Status::STATUS_OUT_OF_STOCK = 0;
// or
// Magento\CatalogInventory\Model\Stock\Status::STATUS_IN_STOCK = 1;

Understanding Eloquent relationships

please i really want to understand Eloquent relationships because i am having a lot headaches in this app i am building, in the show catalogue styles section, what i want to achieve is to show two images of each style catalogue#styles on the page, that is if two images are uploaded (front) and (back) images but by default it will show the front view, the screenshot will help you understand better
SCREENSHOTS
This first image shows the styles listing with a default front view, but when viewed more it should show the font and back images in a slide.
This image is showing a particular style clicked to view more, with the front and back images sliding.
THE PROBLEM
I want to be able to show the front and back images when viewed more, but it is showing a different image from a different id.
EXISTING CODE
$catalogueStyles = DB::table('catalogueimages')
->select('catalogueimages.id',
'catalogueimages.user_id',
'catalogueimages.catalogue_style_id',
'catalogueimages.catalogue_style_view',
'catalogueimages.new_name',
'catalogueimages.image_path',
'cataloguestyles.id',
'cataloguestyles.user_id',
'cataloguestyles.catalogue_style_name',
'cataloguestyles.catalogue_style_description',
'cataloguestyles.catalogue_style_tags',
'cataloguestyles.catalogue_style_rating',
'cataloguestyles.catalogue_style_publisher_name',
'cataloguestyles.catalogue_style_publisher_url')
->join('cataloguestyles','cataloguestyles.id','=','catalogueimages.catalogue_style_id')
->where('catalogue_style_view',0)
->get();
i want to relate the cataloguestyles table with the catalogueimages table so as to combine them and pull the data from the db, i have tried this for a test
Cataloguestyle model
<?php
namespace App\Wasamar;
use Illuminate\Database\Eloquent\Model;
class Cataloguestyle extends Model
{
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'cataloguestyles';
function catalogueimage(){
return $this>hasMany('App\Wasamar\Catalogueimage','catalogue_style_id');
}
}
Catalogueimage model
<?php
namespace App\Wasamar;
use Illuminate\Database\Eloquent\Model;
class Catalogueimage extends Model
{
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'catalogueimages';
function cataloguestyle(){
return $this->belongsTo('App\Wasamar\Cataloguestyle','id');
}
}
When i try the hasMany function on the catalogue style and try to get the values, i get this error
FatalErrorException in routes.php line 246: Call to a member function catalogueimage() on null