Great! Let’s go step-by-step and build those components using Yii2 ActiveForm and proper form models, integrating nicely with your session and cart management setup.
1) AddToCartForm + Controller Action
Purpose: Handle the add-to-cart form where users select a product and quantity to add. Supports validation and clean form handling.
AddToCartForm model
namespace app\models;
use yii\base\Model;
class AddToCartForm extends Model
{
public $productId;
public $quantity = 1;
public function rules()
{
return [
[['productId', 'quantity'], 'required'],
['productId', 'integer'],
['quantity', 'integer', 'min' => 1],
['productId', 'exist', 'targetClass' => Product::class, 'targetAttribute' => ['productId' => 'id']],
];
}
public function attributeLabels()
{
return [
'productId' => 'Product',
'quantity' => 'Quantity',
];
}
}
Controller action (CartController::actionAdd())
use app\models\AddToCartForm;
use Yii;
public function actionAdd()
{
$model = new AddToCartForm();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
// Access your session cart and add product
$sessionManager = new SessionManager();
$sessionUser = new SessionUser($sessionManager);
$sessionCart = new SessionCart($sessionUser);
$added = $sessionCart->addToCartProduct($model->productId, $model->quantity);
if ($added) {
Yii::$app->session->setFlash('success', 'Product added to cart.');
return $this->redirect(['cart/index']);
} else {
Yii::$app->session->setFlash('error', 'Failed to add product to cart.');
}
}
// Get product list or details for dropdown/select box
$products = Product::find()->select(['name', 'id'])->indexBy('id')->column();
return $this->render('add', [
'model' => $model,
'products' => $products,
]);
}
View for add-to-cart (views/cart/add.php)
use yii\widgets\ActiveForm;
use yii\helpers\Html;
$this->title = 'Add Product to Cart';
$form = ActiveForm::begin();
echo $form->field($model, 'productId')->dropDownList($products, ['prompt' => 'Select product']);
echo $form->field($model, 'quantity')->input('number', ['min' => 1]);
echo Html::submitButton('Add to Cart', ['class' => 'btn btn-success']);
ActiveForm::end();
2) CheckoutForm + Controller action
Purpose: Collect user info (name, email, address, payment details, etc.), validate input, and trigger checkout/order creation.
CheckoutForm model (simplified example)
namespace app\models;
use yii\base\Model;
class CheckoutForm extends Model
{
public $fullName;
public $email;
public $address;
public $paymentMethod;
public function rules()
{
return [
[['fullName', 'email', 'address', 'paymentMethod'], 'required'],
['email', 'email'],
['paymentMethod', 'in', 'range' => ['credit_card', 'paypal', 'cash_on_delivery']],
['fullName', 'string', 'max' => 255],
['address', 'string'],
];
}
public function attributeLabels()
{
return [
'fullName' => 'Full Name',
'email' => 'Email Address',
'address' => 'Shipping Address',
'paymentMethod' => 'Payment Method',
];
}
}
Controller action CartController::actionCheckout()
use app\models\CheckoutForm;
use Yii;
public function actionCheckout()
{
$model = new CheckoutForm();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$sessionManager = new SessionManager();
$sessionUser = new SessionUser($sessionManager);
$sessionCart = new SessionCart($sessionUser);
$items = $sessionCart->getCartSession();
if (empty($items)) {
Yii::$app->session->setFlash('error', 'Cart is empty.');
return $this->redirect(['cart/index']);
}
// Process order (pseudo-code)
$orderSuccess = $this->processOrder($model, $items);
if ($orderSuccess) {
$sessionCart->clearCart();
Yii::$app->session->setFlash('success', 'Order placed successfully!');
return $this->redirect(['site/index']);
} else {
Yii::$app->session->setFlash('error', 'Failed to process the order.');
}
}
return $this->render('checkout', ['model' => $model]);
}
// Example order processing method (replace with your own logic)
private function processOrder(CheckoutForm $checkoutForm, array $items): bool
{
// Persist order, charge payment, send email, etc.
// Return true if succeed, false otherwise.
return true;
}
Checkout view views/cart/checkout.php
use yii\widgets\ActiveForm;
use yii\helpers\Html;
$this->title = 'Checkout';
$form = ActiveForm::begin();
echo $form->field($model, 'fullName')->textInput();
echo $form->field($model, 'email')->input('email');
echo $form->field($model, 'address')->textarea(['rows' => 3]);
echo $form->field($model, 'paymentMethod')->dropDownList([
'credit_card' => 'Credit Card',
'paypal' => 'PayPal',
'cash_on_delivery' => 'Cash on Delivery',
], ['prompt' => 'Select Payment Method']);
echo Html::submitButton('Place Order', ['class' => 'btn btn-primary']);
ActiveForm::end();
3) Helper Methods for Rendering Product Info in Cart Table
Assuming your cart items only store product IDs and quantities, you’ll want to fetch product info (name, price) in the view or controller.
Two options:
a) Fetch in Controller and pass to view
$cartItems = $sessionCart->getCartSession(); // [productId => ['quantity'=>X]]
$productIds = array_keys($cartItems);
$products = Product::find()->where(['id' => $productIds])->indexBy('id')->all();
return $this->render('index', [
'cartItems' => $cartItems,
'products' => $products,
]);
Then in the view:
foreach ($cartItems as $productId => $item) {
$product = $products[$productId];
echo Html::encode($product->name);
echo $item['quantity'];
echo Yii::$app->formatter->asCurrency($product->price * $item['quantity']);
}
b) Create helper method inside your SessionCart model for richer data
public function getFullCartItems(): array
{
$cartItems = $this->getCartSession();
if (empty($cartItems)) {
return [];
}
$productIds = array_keys($cartItems);
$products = Product::find()->where(['id' => $productIds])->indexBy('id')->all();
$fullItems = [];
foreach ($cartItems as $id => $data) {
if (isset($products[$id])) {
$product = $products[$id];
$fullItems[] = [
'product' => $product,
'quantity' => $data['quantity'],
'subtotal' => $product->price * $data['quantity'],
];
}
}
return $fullItems;
}
Then in controller:
$fullCartItems = $this->_sessionCart->getFullCartItems();
return $this->render('index', [
'cartItems' => $fullCartItems,
]);
And in the view:
foreach ($cartItems as $item) {
echo Html::encode($item['product']->name);
echo $item['quantity'];
echo Yii::$app->formatter->asCurrency($item['subtotal']);
}
Summary
- AddToCartForm: simple model to select a product and quantity, with validation, rendered with ActiveForm.
- Cart update (covered in previous message): better handled by a dedicated form model with array inputs.
- CheckoutForm: gathers order data, performs validation, and triggers order placement.
- Helper methods to enrich cart data with product names and prices for display.
If you want, I can also help with:
- Order model design
- Payment gateway integration stubs
- AJAX-based add-to-cart & update cart for better UX
Just say the word!