Coder Social home page Coder Social logo

yii2-cart's Introduction

Yii2 Shopping Cart Extension


This extension adds shopping cart for Yii framework 2.0

Latest Stable Version Total Downloads License Build Status Scrutinizer Code Quality

Support us

Does your business depend on our contributions? Reach out and support us on Patreon. All pledges will be dedicated to allocating workforce on maintenance and new awesome stuff.

Installation

The preferred way to install this extension is through composer.

Either run

php composer.phar require --prefer-dist yii2mod/yii2-cart "*"

or add

"yii2mod/yii2-cart": "*"

to the require section of your composer.json file.

Configuration

  1. Configure the cart component:
return [
    //....
    'components' => [
        'cart' => [
            'class' => 'yii2mod\cart\Cart',
            // you can change default storage class as following:
            'storageClass' => [
                'class' => 'yii2mod\cart\storage\DatabaseStorage',
                // you can also override some properties 
                'deleteIfEmpty' => true
            ]
        ],
    ]
];
  1. Create the Product Model that implements an CartItemInterface:
class ProductModel extends ActiveRecord implements CartItemInterface
{

    public function getPrice()
    {
        return $this->price;
    }

    public function getLabel()
    {
        return $this->name;
    }

    public function getUniqueId()
    {
        return $this->id;
    }
}

If you use the yii2mod\cart\storage\DatabaseStorage as storageClass then you need to apply the following migration:

php yii migrate --migrationPath=@vendor/yii2mod/yii2-cart/migrations

Using the shopping cart

Operations with the shopping cart are very straightforward when using a models that implement one of the two cart interfaces. The cart object can be accessed under \Yii::$app->cart and can be overridden in configuration if you need to customize it.

// access the cart from "cart" subcomponent
$cart = \Yii::$app->cart;

// Product is an AR model implementing CartProductInterface
$product = Product::findOne(1);

// add an item to the cart
$cart->add($product);

// returns the sum of all 'vat' attributes (or return values of getVat()) from all models in the cart.
$totalVat = $cart->getAttributeTotal('vat');

// clear the cart
$cart->clear();

View Cart Items

You can use the CartGrid widget for generate table with cart items as following:

<?php echo \yii2mod\cart\widgets\CartGrid::widget([
    // Some widget property maybe need to change. 
    'cartColumns' => [
        'id',
        'label',
        'price'
    ]
]); ?>

Items in the cart

Products/items that are added to the cart are serialized/unserialized when saving and loading data from cart storage. If you are using Active Record models as products/discounts, make sure that you are omitting any unnecessary references from the serialized data to keep it compact.

// get all items from the cart
$items = $cart->getItems();

// get only products
$items = $cart->getItems(Cart::ITEM_PRODUCT);

// loop through cart items
foreach ($items as $item) {
    // access any attribute/method from the model
    var_dump($item->getAttributes());

    // remove an item from the cart by its ID
    $cart->remove($item->uniqueId)
}

Get Number of Products in Cart

You can use the getCount to get count as this example:

// get count of all products in cart:
$items = $cart->getCount();

// get count of Specific Item Type:
$items = $cart->getCount(Cart::ITEM_PRODUCT);

yii2-cart's People

Contributors

dmitry-semenov avatar frankirox avatar imtiazmahbub avatar iridance avatar morontt avatar scrutinizer-auto-fixer avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

yii2-cart's Issues

how to add and retrive information from cart?

Hello. i have installed extension and also migration as well but widget shows empty data id , label and price. how to add product to cart? also in migration there is no any product table added to database.

Totals

I see I could specify itemType to get the total, but how do I set the itemtype ?

add the quantity

Hi,

Is there a method make me add the quantity to the cart and count the total by the quantity?

Thanks

Declaration of backend\models\Product::getPrice()...

I already have this error:

Declaration of backend\models\Product::getPrice() must be compatible with yii2mod\cart\models\CartItemInterface::getPrice(): int

I already implement the CartInterface and functions and got this error

Method Save Storage

How can I save the cart in this code?

/** @var $cart \yii2mod\cart\Cart */
$cart = app()->cart;

foreach ($products as $product) {
   $cart->add($product, false);
}

Solution:

    public function save()
    {
        $this->storage->save($this);
    }

    public function clear($save = true)
    {
        $this->items = [];
        $save && $this->save();
        return $this;
    }

    public function add(CartItemInterface $element, $save = true)
    {
        $this->addItem($element);
        $save && $this->save();
        return $this;
    }

    public function remove($uniqueId, $save = true)
    {
        if (!isset($this->items[$uniqueId])) {
            throw new InvalidParamException('Item not found');
        }
        unset($this->items[$uniqueId]);

        $save && $this->save();
        return $this;
    }

load from cart using the database storage

When you save to the table you use the user_id , but when you get back the products from the cart table you use the sessionId .
Please take a look on the below code i think is fixed now :

db = Yii::$app->get($this->dbComponent); if (isset($this->userComponent)) { $this->user = Yii::$app->get($this->userComponent); } if (!isset($this->table)) { throw new InvalidConfigException('Please specify "table" in cart configuration'); } } /** - @param Cart $cart * - @return mixed */ public function load(Cart $cart) { $query = new Query(); $identifier = $this->getIdentifier(Yii::$app->session->getId()); $query->select($this->dataField) ->from($this->table) ->where([$this->idField => $identifier]); $items = []; if ($data = $query->createCommand($this->db)->queryScalar()) { $items = unserialize($data); } return $items; } /** - @param string $default * - @return string */ protected function getIdentifier($default) { $id = $default; if ($this->user instanceof User && !$this->user->getIsGuest()) { $id = $this->user->getId(); } return $id; } /** - @param \yii2mod\cart\Cart $cart * - @return void */ public function save(Cart $cart) { $identifier = $this->getIdentifier(Yii::$app->session->getId()); $items = $cart->getItems(); $sessionData = serialize($items); $command = $this->db->createCommand(); if (empty($items) && true === $this->deleteIfEmpty) { $command->delete($this->table, [$this->idField => $identifier]); } else { $command->setSql(" REPLACE {{{$this->table}}} SET {{{$this->dataField}}} = :val, {{{$this->idField}}} = :id ")->bindValues([ ':id' => $identifier, ':val' => $sessionData, ]); } $command->execute(); } /** - @param $sourceId - @param $destinationId */ public function reassign($sourceId, $destinationId) { $command = $this->db->createCommand(); $command->delete($this->table, [$this->idField => $destinationId])->execute(); $command->setSql(" UPDATE {{{$this->table}}} SET {{{$this->idField}}} = :userId WHERE {{{$this->idField}}} = :sessionId ")->bindValues([ ':userId' => $destinationId, ':sessionId' => $sourceId ])->execute(); } }

table column 'cartData' can't save serialize() data

Returns a string containing a byte-stream representation of value that can be stored anywhere.

Note that this is a binary string which may include null bytes, and needs to be stored and handled as such. For example, serialize() output should generally be stored in a BLOB field in a database, rather than a CHAR or TEXT field.

reference php.net

The cartData column may change the type to blob or be processed to base64_encode/base64_decode before serialize/unserialize

I got problem with DataStorage

When I use this command, I got error:
$cart->add($item);
The problem is from DatabaseStorage::save() in this line
REPLACE {{{$this->table}}}
SET
{{{$this->dataField}}} = :val,
{{{$this->idField}}} = :id
The property $table you declare above is already in correct syntax ({{%cart}}), no need to add more double-curly braces

Bug in Design

There is a small bug in your design. You assume that the VAT is static on a product. However it is not. It depends on the location of the customer.
When I add a product, and then I supply my customer data the VAT could change based on the customers country

QTY ?

Is there a possiblity to add a product and order it 6 times ? I seem to be able to only add 1 product at a time, and that multiple qty show on different lines

migration error

system: windows 10 16299.64
database: PostgreSql9.1

in path\vendor\yiisoft\yii2\db\Schema.php:636

Error Info:
Array
(
[0] => 42601
[1] => 7
[2] => ERROR: syntax error at or near "" LINE 4: PRIMARY KEY (sessionId`)
^
)

I tried to modify this file after the success

$this->createTable('{{%Cart}}', [
'sessionId' => $this->string(),
'cartData' => $this->text(),
], $tableOptions);
$this->addPrimaryKey('cart_primary_key', '{{%Cart}}', 'sessionId');

Docs getUniqueId

Please explain that this is a Unique Id for the cartitem. not the product itself.
So if I have 1 product, 4 times added, there should be 4 different unique ID's

I am trying to help out, not to critisize your work.... hope you appreciate it

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax

Hello,

I'm trying to add a product to the cart using the $cart->add(Product::findOne($id) method, but it throws the following exception:

Error Info: Array ( [0] => 42000 [1] => 1064 [2] => You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '{{cart}} SET cartData = 'a:1:{i:1;O:18:\' at line 1 )

It seems to me that the "" character is not allowed in MySQL database.

I have the following setup, and your latest composer version of the cart (yii2mod/yii2-cart v1.4):

  • PHP: PHP 7.4.9 (cli) (built: Aug 7 2020 19:23:06) ( NTS )
  • Yii2: Version 2.0.34
  • Server version: Apache/2.4.41 (Unix)
  • Server built: Oct 1 2019 10:31:38

Is there anything that needs to be changed?

SQLSTATE[22007]: Invalid datetime format: 1292 Truncated incorrect DOUBLE value

First I want to mention that I'm on PHP 7.2.13, now the problem:

  • I have webstore that logged users and guest users are allowed to add items to cart. I'm using DatabaseStorage, when logged in user adds item in the cart, the module creates record in the cart table with sessionId : {logged_in_user_id} Ex: 1, and when Guest user adds item in the cart, the module creates record in the cart table with sessionId : {session_id} Ex: 77g9t9t5u5qdvrogoi4j0muiam , ONLY when both of these record types exists in the Cart Table, when you try to delete the last item in the cart from the LOGGED User (sessionId: 1), it throws the error:

SQLSTATE[22007]: Invalid datetime format: 1292 Truncated incorrect DOUBLE value: '77g9t9t5u5qdvrogoi4j0muiam'
The SQL being executed was: DELETE FROM cart WHERE sessionId=1

I resolve this by chaning this: (DatabaseStorage.php Line:132)
$command->delete($this->table, [$this->idField => $identifier]);

to this:
$command->delete($this->table, [$this->idField => (string)$identifier]);

Dynamic Price ( Price method POST )

How ,i can send parameter qty , price and packaging.
And Price is depends by packaging
Example.
$id = $model->id
$product = MBarang::findOne($id);
$price = $model->price
$packaging = $model->packaging
$qty = $model->qty

Table wrong reference

ase table or view not found: 1146 Table 'mxcom0_dev.cart' doesn't exist
The SQL being executed was: SELECT cartData FROM cart WHERE sessionId=1
Error Info: Array

It looks for a table named 'cart' however the migration creates the correct 'prefix_cart'
So I guess there is a missing prefix in the code somewhere

Difference between Product and Item

Hi,

Your extension looks a good alternative for my project but I cant understand the difference between a Product and an Item in the interface that are supposed to be implemented in my models.

I really look forward to test the conversion to order :)

Thanks

Unable to have a float/decimal value in Cart item price

The CartItemInterface.php uses int data type for price value:

public function getPrice(): int;

I believe that more correct would be to have this value float/double to support decimal values in prices. In version <1.4 it was originally untyped function, so it was no problem.

I propose changing the signature to float.

Problem migration back

Mac-mini-Dev:*** dev$ php yii migrate/redo 3
Yii Migration Tool (based on Yii v2.0.15.1)

Total 3 migrations to be redone:
        m161119_153348_alter_cart_data
        m161109_124936_rename_cart_table
        m160516_095943_init

Redo the above migrations? (yes|no) [no]:yes
*** reverting m161119_153348_alter_cart_data
Exception 'ReflectionException' with message 'Class m161119_153348_alter_cart_data does not exist'

Argument 1 passed to yii2mod\cart\Cart::add() must be an instance of yii2mod\cart\models\CartItemInterface

Hello,
I have this error:
Argument 1 passed to yii2mod\cart\Cart::add() must be an instance of yii2mod\cart\models\CartItemInterface

is in this method:
public function add(CartItemInterface $element, $save = true): self

I follow the doc and configured the extension in correct way:

'cart' => [
            'class' => 'yii2mod\cart\Cart',
            // you can change default storage class as following:
            'storageClass' => [
                'class' => 'yii2mod\cart\storage\DatabaseStorage',
                // you can also override some properties
                'deleteIfEmpty' => true
            ]
        ],

Then in my controller, just this simple code:

public function actionCart()
{
        $cart = \Yii::$app->cart;
        $cart->add(2); 
}

I tried to:

  1. Remove configuration in main.php and is not working because configuration are missing, so mean is correctly configurate
  2. implement CartItemInterface in controller
  3. implement add() method in model and call from controller
  4. I try to pass in method integer, array and string

Where I am wrong?
Thank you

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.