jeudi 23 juin 2016

insert into database in yii2?

i am trying to insert data to 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 commonmodelsLoginForm;
use commonmodelsTopic;
use frontendmodelsContactForm;
use frontendmodelsPasswordResetRequestForm;
use frontendmodelsResetPasswordForm;
use frontendmodelsSignupForm;;

use yiibaseInvalidParamException;
use yiifiltersAccessControl;
use yiifiltersVerbFilter;
use yiiwebBadRequestHttpException;
use yiiwebController;

    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');
    }  

this is the view

<?php

use yiiwidgetsListView;
use yiidataArrayDataProvider;
use appmodelsMyProfile;
use appmodelsLikeDiscussion;
use yiiwidgetsActiveForm;
use commonmodelsTopic;
use commonmodelsComment;
use commonmodelsUsers;
use commonmodelsCandidate;
use yiiwidgetsPjax;
use yiihelpersHtml;
use frontendassetsAppAsset;

$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

Aucun commentaire:

Enregistrer un commentaire