S
S
Svetlana Galenko2018-12-02 11:12:44
Yii
Svetlana Galenko, 2018-12-02 11:12:44

Undefined method call: app\models\forms\ShopPromoItemBuyForm::promo()?

Good afternoon, I get the following error when I try to call a query on a table:

PHP Fatal Error – yii\base\ErrorException
Call to undefined method app\models\forms\ShopPromoItemBuyForm::promo()

Calling unknown method: app\models\forms\ShopPromoItemBuyForm::promo()

    1. in /var/www/u0598324/public_html/webstels.com/vendor/yiisoft/yii2/base/Component.php at line 300

                             */
        public function __call($name, $params)
        {
            $this->ensureBehaviors();
            foreach ($this->_behaviors as $object) {
                if ($object->hasMethod($name)) {
                    return call_user_func_array([$object, $name], $params);
                }
            }
            throw new UnknownMethodException('Calling unknown method: ' . get_class($this) . "::$name()");
        }
     
        /**
         * This method is called after the object is created by cloning an existing one.
         * It removes all behaviors because they are attached to the old object.
         */
        public function __clone()
        {
            $this->_events = [];
                    

    2. in /var/www/u0598324/public_html/webstels.com/controllers/user/main/services/PromoController.php at line 47 – yii\base\Component::__call('promo', [])
    41424344454647484950515253

                         
            // if (!\Yii::$app->user->isGuest)
            //     return $this->redirect(['/promo/namesite']);
     
            $shop = new ShopPromoItemBuyForm();
            if ($shop->load(\Yii::$app->request->post())) {
                if ($shop->promo() === true) {
                    return $this->render('success', [
                        'shop' => $shop,
                    ]);
                }
            }
     
                    

    3. in /var/www/u0598324/public_html/webstels.com/controllers/user/main/services/PromoController.php at line 47 – app\models\forms\ShopPromoItemBuyForm::promo()
    41424344454647484950515253

                         
            // if (!\Yii::$app->user->isGuest)
            //     return $this->redirect(['/promo/namesite']);
     
            $shop = new ShopPromoItemBuyForm();
            if ($shop->load(\Yii::$app->request->post())) {
                if ($shop->promo() === true) {
                    return $this->render('success', [
                        'shop' => $shop,
                    ]);
                }
            }

Here is the ShopPromoItemBuyForm.php model:
<?php
namespace app\models\forms;

use app\helpers\BalanceHelper;
use app\helpers\RefererHelper;
use app\helpers\SettingHelper;
use app\models\ShopPromoItem;
use app\models\User;
use app\models\UserPromo;
use app\models\UserBalance;
use app\models\UserOperation;
use yii\validators\IpValidator;

class ShopPromoItemBuyForm extends UserPromo
{
    public $item_id;

    public function rules()
    {
        return [
            ['item_id', 'required'],
            ['item_id', 'integer'],
            ['item_id', 'exist',
                'targetClass' => '\app\models\ShopItem',
                'targetAttribute' => 'id',
                'filter' => ['status' => ShopPromoItem::STATUS_ENABLED]
            ],

            ['name', 'multProtect']
        ];
    }

    public function scenarios()
    {
        return [
            self::SCENARIO_DEFAULT => ['name']
        ];
    }

    public function multProtect()
    {
        return;

        // disable for debug mode
        if (YII_DEBUG)
            return;

        // check evercookie
        if (isset($_COOKIE['was_promo']) && $_COOKIE['was_promo'] == "true") {
            $this->addError('name', \Yii::t('app', 'Вы уже заказывали сайт с таким названием на проекте, повторный заказ сайта с таким именем запрещён'));
        }
        $validator = new IpValidator();
        if ($validator->validate(\Yii::$app->request->userPromoIP)) {
            $ip = \Yii::$app->request->userPromoIP;
            $userPromo = UserPromo::find()->where(['id' => $ip])->limit(1)->one();
            if ($userPromo !== null) {
                $this->addError('name', \Yii::t('app', 'Вы уже заказывали сайт с таким названием на проекте, повторный заказ сайта с таким именем запрещён'));
            }
        } else {
            $this->addError('name', \Yii::t('app', 'Вы уже заказывали сайт с таким названием на проекте, повторный заказ сайта с таким именем запрещён'));
        }
    }

    public function buy(User $user)
    {
        if (!$this->validate()) {
            \Yii::$app->getSession()->setFlash('warning', implode('<br />', $this->getFirstErrors()));
            return false;
        }

        if (\Yii::$app->mutex->acquire('balance_' . $user->id)) {
            \Yii::$app->db->transaction(function() use ($user) {
                $item = ShopPromoItem::get($this->item_id);
                $prices = $item->getPriceArray();

                // check balance
                foreach ($prices as $currency => $price) {
                    if (!$user->balance->has($currency, BalanceHelper::convertToDigits($price))) {
                        \Yii::$app->getSession()->setFlash('warning', \Yii::t('app', 'Недостаточно средств на балансе'));
                        return false;
                    }
                }

                // decrease balance
                foreach ($prices as $currency => $price) {
                    $user->balance->decrease($currency, BalanceHelper::convertToDigits($price));
                    $user->operation->create(UserOperation::OPERATION_SHOP_PROMO_BUY, $currency, BalanceHelper::convertToDigits($price), [
                        'ShopItem_id' => $this->item_id
                    ]);
                }

                $item->giveTo($user);

                // give reward to referer
                RefererHelper::giveReward($user, UserBalance::CURRENCY_USD, BalanceHelper::convertToDigits($prices['usd']));

                $message = '';
                foreach ($prices as $currency => $price) {
                    $message .= \Yii::t('app', '{sum} долларов', ['sum' => BalanceHelper::convertToDigits($price)]);
                }

                \Yii::$app->getSession()->setFlash('success', \Yii::t('app', 'Вы купили «{title}»', ['title' => \Yii::t('app', $item->getTitle())]) .
                    '<br />' . \Yii::t('app', 'Потрачено {price}', ['price' => $message]));

                return true;
            });
        }
    }
}

Here is the UserPromo.php model:
<?php
namespace app\models;

use yii\db\ActiveRecord;
use yii\helpers\Html;

class UserPromo extends ActiveRecord
{
    const STATUS_ENABLED = 'enabled';
    const STATUS_DISABLED = 'disabled';
    const STATUS_DELETED = 'deleted';

    public static function tableName()
    {
        return '{{%user_promo}}';
    }

    public function rules()
    {
        return [
            ['id', 'exist'],
            ['user_id', 'integer'],

            ['name', 'required'],
            ['name', 'filter', 'filter' => 'trim'],
            ['name', 'match', 'pattern' => '#^[\w_-]+$#i'],
            ['name', 'unique', 'targetClass' => self::className(), 'message' => \Yii::t('app', 'Указанное название для вашего сайта уже занято')],
            ['name', 'string', 'min' => 2, 'max' => 255],
        ];
    }

    public function attributeLabels()
    {
        return [
            'status' => 'Статус',
            'name' => \Yii::t('app', 'Название'),
        ];
    }

    public static function findIdentity($id)
    {
        $identity = static::findOne(['id' => $id]);
        return $identity;
    }

    public static function findByName($name)
    {
        return static::findOne(['name' => $name]);
    }

    public function getName()
    {
        return Html::encode($this->name);
    }

    public function getPromo()
    {
        return $this->hasOne(Promo::className(), ['id' => 'promo_id']);
    }

    public function getUser()
    {
        return $this->hasOne(User::className(), ['id' => 'user_id']);
    }

    public function getTitle()
    {
        return $this->promo->getTitle();
    }

    public function getType()
    {
        return $this->promo->getType();
    }

    public function getProfit($type)
    {
        return $this->promo->{$type . '_profit'};
    }
}

Here is my view, where the user requests the condition to the database:
<?= FlashWidget::widget(); ?>

            <?php foreach ($items as $item) { ?>
                                        
                <?= $item->getPriceString(); ?>

                    <h4 class="title">Выберите название для своего сайта</h4>
                     <?= Html::beginForm('', 'post', ['data-pjax' => true]); ?>
                     <div class="form-container">
                            <div class="form-group">
                                 <?= Html::activeHiddenInput($model, 'item_id', ['value' => $item->id]) ?>
                            </div>
                            <?= Html::submitButton(\Yii::t('app', 'Купить'), ['class' => 'btn btn-upper btn-primary']) ?>
                          </div><!-- /.form-container -->
                          <?= Html::endForm(); ?>
                          <?php } ?>

                         <form role="form" class="form-inline form-cnt">
                         <div class="form-group">
                        <label>&nbsp;</label>
                        <span class="text col-md-offset-3" style="margin-left: -2%;">Проверить не занято ли данное название</span>
                       </div>

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question