douou6696 2017-04-02 09:28
浏览 37
已采纳

自定义联系表单不起作用Yii2

I tried to redo the default contact form to form that sends a message and save it to database table. But something went wrong and i can't realize why.I already made same register form without problems and it is working good. Can you guys give me advance? Where is my mistake?

ContactForm model:

<?php

namespace app\models;

use Yii;
use yii\base\Model;
use yii\db\ActiveRecord;

/**
 * This is the model class for table 'users_messages'.
 *
 * @params int $message_id
 * @params string $message_title
 * @params string $message_content
 * @params string $message_author
 * @params int $user_id
 */
class ContactForm extends ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'users_messages';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['message_title', 'message_content', 'message_author'], 'required']
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
           'message_title' => 'Title',
           'message_author' => 'Author',
           'message_content' => 'Content'
        ];
    }
}

actionContact:

/**
     * Displays contact page.
     *
     * @return string
     */
    public function actionContact()
    {
        $model = new ContactForm();
        $message = new UsersMessages();

        if(isset($_POST['send_message']))
        {
            $model->attributes = $_POST['ContactForm'];

            if($model->validate())
            {
                $message->message_author = $model->message_author;
                $message->message_title = $model->message_title;
                $message->message_content = $model->message_content;

                $message->save();

                return $this->refresh();
            }
        }

        return $this->render('contact', [
            'model' => $model,
        ]);
    }

When i debug actionContact it shows me that there is not data in $model->message_author, title and content.

Thank you in advance!

EDIT: with the advices of Brizkey i've reached this point: actionContact:

public function actionContact()
    {
        $model = new UsersMessages();

        if($model->load($_POST) && $model->save())
        {
            return $this->redirect('contact');
        }

        return $this->render('contact', [
            'model' => $model,
        ]);
    }

and left only one model: UserMessages model:

<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "users_messages".
 *
 * @property int $message_id
 * @property string $message_title
 * @property string $message_content
 * @property string $message_author
 * @property int $user_id
 *
 * @property Users $user
 */
class UsersMessages extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'users_messages';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['message_title', 'message_content', 'message_author', 'user_id'], 'required'],
            [['message_content'], 'string'],
            [['user_id'], 'integer'],
            [['message_title'], 'string', 'max' => 100],
            [['message_author'], 'string', 'max' => 50],
            [['user_id'], 'exist', 'skipOnError' => true, 'targetClass' => Users::className(), 'targetAttribute' => ['user_id' => 'id']],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'message_id' => 'Message ID',
            'message_title' => 'Title:',
            'message_content' => 'Content:',
            'message_author' => 'Author:',
            'user_id' => 'User ID',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getUser()
    {
        return $this->hasOne(Users::className(), ['id' => 'user_id']);
    }
}

The problem is in the $model->save() part. It can't pass through it!

EDIT-2: I reached some success(if i can call it like that)! Gave the save() method param of false. Result of this action was: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (anthonyl_fbpj.comments, CONSTRAINT fk_comments_projects1 FOREIGN KEY (project_id) REFERENCES projects (id) ON DELETE NO ACTION ON UPDATE NO ACTION)

From this error i understood that the problem is with the foreign_key. So i removed it and all flows good now! (I removed it because i realized that i do not need it in my situation)

  • 写回答

1条回答 默认 最新

  • douhuang3833 2017-04-02 10:06
    关注

    There are some things here to correct / be explained.

    1. There is model called ContactForm that is the Active Record for users_messages table. So what is UsersMessages model and what does it do?
    2. If I guess correctly and these two models are doing the same thing just remove one ot at least extend ContactForm from UsersMessages.
    3. There is method load() that will take care of checking if $_POST is populated with data and on top of it will verify if data can be validated so only attributes with validation rules can be assigned - use it instead of assigning attributes directly with POST data.
    4. With only one model taking care of processing the data from the form you don't have to assign attributes again by hand which you are doing here - safer and less places to make mistake.
    5. I've seen this a lot on Stack Overflow - you guys don't check if save() is successful - WHY? This can go wrong, don't ever assume it's always true.

    Without knowing this other model I cannot say for sure what is going on here. Maybe validation of $message went wrong. You need to check it first.

    Hopefully with all the points above you can fix it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 fluent的在模拟压强时使用希望得到一些建议
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退