从函数中获取值后放入数组/会话

时间:2016-09-16 01:40:00

标签: php yii2

您好我有一个用户单击添加按钮然后将信息保存到数据库然后通过其他功能获取的过程。但我想要做的是跳过数据库保存,然后将其放入数组或会话(无论什么可能),然后使用它放入视图。这可能吗?

这是我目前的代码:

视图中的添加按钮:

    <p>
     <?= Html::a('<b>ADD</b>',
     ['site/addsubject', 'TrNo' => $subjects['TrNo'], 'clientid' => $_user],
     ['class' => 'btn-info btn-transparent btn-large', 'data-method' => 'post']) ?>
   </p>

然后是控制器中的功能:

 public function actionAddsubject($TrNo, $clientid){
      //echo $subjectid;
      //echo "Hello";
      $model = new ActiveSubject();
      //$var =  $model->AddSubject($subjectid);
      $model->AddSubject($TrNo, $clientid);
       $this->redirect(array('site/main'));

     // echo $var->subjectname;
     //echo $var['subjectname'];
    }

进行保存的模型

public static function AddSubject($TrNo, $clientid){
  $subject = ActiveCurriculum::find()
                                ->select('scstock.*')
                                ->joinWith('schead')
                                ->where(['schead.TrNo' => $TrNo])
                                ->one();

    $activesubject = new ActiveSubject();
    $activesubject->clientid = $clientid;
    $activesubject->TrNo = $subject->TrNo;
    $activesubject->subjectcode = $subject->subjectcode;
    $activesubject->schedday = $subject->schedday;
    $activesubject->schedtime = $subject->schedtime;
    //remember to use schead if the value is joined from another table.
    $activesubject->section = $subject->schead->section;
    $activesubject->roomcode = $subject->roomcode;
    $activesubject->units = $subject->units;
    $activesubject->save();
//reduces the slot of ccsubject by 1
     $subject->slots = $subject->slots - 1;
     //never forget the saving part
     $subject->save();

        return true;

}

是否可以将其存储在数组或会话中并使其在视图中可访问?我想把它放在变量中,但我如何处理添加按钮?

1 个答案:

答案 0 :(得分:0)

对于用户会话中的临时数据存储,您可以像

那样进行
$session = Yii::$app->session;

//check if session is active
if ($session->isActive)
{

     $session->set('subject', 'Maths');       

}

要检索会话中存储的数据,您可以这样做

 $session = Yii::$app->session;

 if ($session->isActive)
 {

     $subject = $session->get('subject');    

 }

使用此链接可了解有关yii2

中会话处理的更多信息

http://www.bsourcecode.com/yiiframework2/session-handling-in-yii-framework-2-0/

但是,如果您的目的只是临时存储数据,以便在下一个操作或视图中可用,您可以像

那样进行操作
public function  actionAddsubject($TrNo, $clientid)
{

   //just showing an example of a variable that holds some data
   $subject = "Maths";

   //redirect to action site/main and make the $subject data available there
   return $this->redirect(['site/main', 'subject' => $subject ]);


}

请注意,上面的代码将重定向到行动网站/主页,其中数据$主题可用。要访问site / main中的数据$ subject,您可以像

一样
public function actionMain($subject)
{
    //now you can do whatever with $subject
}