Reputation: 449
I am trying to insert data into MySQL table in yii2 but it gives me errors.
I have a textbox in the view. It is meant to get the data the user inputs in the textbox with name=Topic[topic];
and insert it into the database.
When I try it a different way like $topic->topic = 'good things';
it works well, but when I try to change it like $topic->topic = $topic_data['topic'];.
I get this error:
Undefined index: topic`
This is the controller:
use Yii;
use common\models\LoginForm;
use common\models\Topic;
use frontend\models\ContactForm;
use frontend\models\PasswordResetRequestForm;
use frontend\models\ResetPasswordForm;
use frontend\models\SignupForm;;
use yii\base\InvalidParamException;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
public function actionCompose()
{
$topic= new Topic();
$topic_data = Yii::$app->request->post('Topic', []);
$topic->creator = Yii::$app->user->identity->email;
$topic->topic = $topic_data['topic'];
$topic->save();
return $this->render('compose');
}
And this is the view:
<?php
use yii\widgets\ListView;
use yii\data\ArrayDataProvider;
use app\models\MyProfile;
use app\models\LikeDiscussion;
use yii\widgets\ActiveForm;
use common\models\Topic;
use common\models\Comment;
use common\models\Users;
use common\models\Candidate;
use yii\widgets\Pjax;
use yii\helpers\Html;
use frontend\assets\AppAsset;
$this->title = 'My Yii Application';
?>
<?php $form = ActiveForm::begin(); ?>
<input type="name" class="form-control" required="true" name="Topic[topic]" id="topic" placeholder="topic">
<?= Html::submitButton('My Yii Application', ['class' => 'btn btn-primary', 'name' => 'login-button']) ?>
<?php ActiveForm::end(); ?>
How do I fix this or is their a better way to do it?
Upvotes: 1
Views: 5969
Reputation: 133360
Try using proper $model->load
$topic= new Topic();
$topic->load($_POST)
$topic->creator = Yii::$app->user->identity->email;
$topic->save();
return $this->render('compose');
Upvotes: 2