Search code examples
shopwareshopware5

Extends Shopware Models


I need to extend Shopware variants models in order to add some custom attributes such as the type of metal,the type of stone a jewel, which is the base article. These attributes will be used both in backend and frontend.

How can I do that? Thanks


Solution

  • Extending the Shopware core model itself is not possible at all. Depending on what specific model you are trying to extend there would be two different ways for some workaround:

    1. If its the article itself that you want to extend you could use the custom attribute fields as described here: http://community.shopware.com/Anlegen,-Anpassen-und-Ausgabe-von-Artikel-Attributen_detail_1208.html

    2. Another way would be to write a plugin where you create attribute fields by code on plugin install(). This is only possible on entities that do have an attribute table which belongs to the entity itself. For example s_order and s_order_attributes

    For the second way create a method in your plugin's Bootstrap.php like the following and call the method in the plugin's install() method:

    public function installOrderAttributes()
    {
        Shopware()->Models()->addAttribute(
            's_order_attributes', 
            'ordermod',
            'Random1',
            'DECIMAL(12,4)',
            false,
            0.0000);
        Shopware()->Models()->addAttribute(
            's_order_attributes',
            'ordermod',
            'Random2',
            'DECIMAL(12,4)',
            false,
            0.0000);
    
        $metaDataCacheDoctrine = Shopware()->Models()->getConfiguration()->getMetadataCacheImpl();
        $metaDataCacheDoctrine->deleteAll();
    
        Shopware()->Models()->generateAttributeModels(array('s_order_attributes'));
    }
    

    The addAttribute() function in /engine/Shopware/Components/Model/ModelManager.php has the following signature:

    /**
     * Shopware helper function to extend an attribute table.
     *
     * @param string $table Full table name. Example: "s_user_attributes"
     * @param string $prefix Column prefix. The prefix and column parameter will be the column name. Example: "swag".
     * @param string $column The column name
     * @param string $type Full type declaration. Example: "VARCHAR( 5 )" / "DECIMAL( 10, 2 )"
     * @param bool $nullable Allow null property
     * @param null $default Default value of the column
     * @throws \InvalidArgumentException
     */
    public function addAttribute($table, $prefix, $column, $type, $nullable = true, $default = null);
    

    Hope this will help.

    Kind regards!