http://www.yiiframework.com/doc-2.0/guide-input-tabular-input.html#collecting-tabular-input
i worked based on the above link but my data is not updating to the database
my table structure is
setting
id , name, value
My controller SettingsController.php
<?php
namespace backend\controllers;
use Yii;
use yii\base\Model;
use yii\web\Controller;
use backend\models\Setting;
class SettingsController extends Controller
{
public function actionIndex()
{
$settings = Setting::find()->indexBy('id')->all();
if (Model::loadMultiple($settings, Yii::$app->request->post()) && Model::validateMultiple($settings)) {
foreach ($settings as $setting) {
$setting->save(false);
}
return $this->redirect('update');
}
return $this->render('update', ['settings' => $settings]);
}
}
my model is Setting.php
<?php
namespace backend\models;
use Yii;
class Setting extends \yii\db\ActiveRecord
{
public static function tableName()
{
return 'setting';
}
}
view is under settings -- update.php
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
$form = ActiveForm::begin();
foreach ($settings as $index => $setting) {
echo $form->field($setting, "[$index]value")->label($setting->name);
}
?>
<div class="form-group">
<?= Html::submitButton('Update', ['class' => 'btn btn-primary']) ?>
</div>
<?php
ActiveForm::end();
my problem is updated data is not saving.but i'm not getting any errors.
You don't have any rules or safe attribute in your Setting Model then the values of this model are not available..
try adding the list of save attribute in rule for your model..
public function rules()
{
return [
[['field1', 'field2',,,,'fieldn'], 'safe'],
];
}
Related
I'm my api module's module.php file, i added this
/**
* {#inheritdoc}
*/
public function init()
{
parent::init();
// custom initialization code goes here
\Yii::configure($this, require __DIR__ . '/config/main.php');
}
in my controller i have this
public function actionIndex()
{
dd(Yii::$app->getModule('payment')->params['data']);
}
in my modules `main.php i have this
$params = ['data' => [ ... ]];
if (YII_ENV == 'dev') {
if (YII_ENV == 'dev') {
$params = array_merge(
require __DIR__ . '/../../../../common/config/params.php',
require __DIR__ . '/../../../../common/config/params-local.php',
require __DIR__ . '/params.php',
);
} else {
$params = array_merge(
require __DIR__ . '/../../../../common/config/params.php',
require __DIR__ . '/params.php',
);
}
return [
'params' => $params,
];
I'm getting this error Undefined array key "data" Any one know what im missing here, i'm trying to create a module config. Thank you.
There is not a main.php in module (there is in app/config).
in each module there is a Module.php class in modules/your_module scaffolding
If you need a specific $params array for the a module you should declare the params var
and assign your values or in declaration or in init() function
class Module extends \yii\base\Module
{
public $params = [];
.....
......
/**
* {#inheritdoc}
*/
public function init()
{
parent::init();
// custom initialization code goes here
$params['data'] = [......];
}
I'm trying to change the $id param in my controller methods on the fly using beforeAction and a behavior. FYI, I'm going to use HashIds and need to convert anywhere I have a $_GET['id'] that may be hashed back into an integer.
How can I use a behavior to automatically modify my $_GET['id'] on the fly using a behavior?
An example action in my controller:
public function actionView($id){
// run code to process $id here back to integer using a behavior
echo $id; //should be an integer
}
My sample url: http://mydomain/posts/view?id=3QhLp
(Alternatively, perhaps the better way to do this is to create a custom url rule?)
you should implement a class that extends from the \yii\base\Behavior like below
<?php
namespace backend\models;
use Yii;
use yii\base\Behavior;
use yii\web\Controller;
class Transformer extends Behavior
{
public $id = '';
public function events()
{
return [Controller::EVENT_BEFORE_ACTION => 'transform']; //mounting the handler to the 'beforeAction' event on the controller.
}
public function transform()
{
$_GET['id'] = $this->id . "transformed"; //mock method here
return true;
}
}
Then in your controller, adding the code as follow:
public function behaviors()
{
return [
'transformer' => [
'class' => \backend\models\Transformer::className(), //Modify the path to your real behavior class.
'id' => Yii::$app->request->get('id'),
],
];
}
then access the Yii::$app->request->get('id') in your action, you will see the transformed url param.
Good afternoon!
There is a question about the file upload to yii2. There are two folders in it that will store the original and thumbnail image. At me files are loaded but here the name of a file does not load in a database
Model
namespace app\models;
use yii\base\Model;
use yii\db\ActiveRecord;
use yii\web\UploadedFile;
use yii\imagine\Image;
use Imagine\Image\Box;
/**
* This is the model class for table "images".
*
* #property integer $id
* #property string $original_image
* #property string $prev_image
*/
class Images extends ActiveRecord
{
public $imageFile;
public $file_name;
/**
* #inheritdoc
*/
public static function tableName()
{
return 'images';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['prev_image'], 'string', 'max' => 255],
[['original_image'], 'string'],
[['imageFile'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg', 'maxSize' => 1024 * 1024 * 7],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'original_image' => 'Original Image',
'prev_image' => 'Prev Image',
];
}
public function upload()
{
$temp=substr(md5(microtime() . rand(0, 9999)), 0, 20);
if ($this->validate()) {
$this->imageFile->saveAs('uploads/original/'.$temp.$this->imageFile->baseName . '.' . $this->imageFile->extension);
$imagine = Image::getImagine();
$image = $imagine->open('uploads/original/' . $temp.$this->imageFile);
$image->resize(new Box(250, 150))->save('uploads/prev/' . $temp.$this
->imageFile->baseName . '.' . $this->imageFile->extension, ['quality' => 70]);
$this->file_name=$temp.$this->imageFile->baseName . '.' . $this->imageFile->extension;
return true;
} else {
return false;
}
}
}
Controller
namespace app\controllers;
use app\models\Images;
use Yii;
use yii\web\UploadedFile;
class ImageController extends \yii\web\Controller
{
public function actionUpload()
{
$model = new Images();
if ($model->load(Yii::$app->request->post())) {
$model->imageFile = UploadedFile::getInstance($model, 'imageFile');
$model->prev_image=$model->file_name;
$model->original_image=$model->file_name;
$model->save();
if ($model->upload()) {
return;
}
}
return $this->render('upload', ['model' => $model]);
}
}
A question how to save a file name in database? Thank you in advance
It's because save happens before uplaod action, but you only define file_name in upload function. Save is what saves it in to the database.
Controller should look like this:
namespace app\controllers;
use app\models\Images;
use Yii;
use yii\web\UploadedFile;
class ImageController extends \yii\web\Controller
{
public function actionUpload(){
$model = new Images();
if ($model->load(Yii::$app->request->post())) {
$uploadedFile = UploadedFile::getInstance($model, 'imageFile');
$model->imageFile = $uploadedFile;
$model->prev_image = $uploadedFile->name
$model->original_image = $uploadedFile->name
$model->save();
if ($model->upload()) {
return;
}
}
return $this->render('upload', ['model' => $model]);
}
}
I am creating a website of Hospital Management system. I have a Patients controller and a Medical Report controller. Every patient has an action of "View Report". When the user clicks on view report, he/she should be directed to the Medical Report and only that field pertaining to the Patient_id in Patients Controller should be displayed. How do I go about it?
Patients table:
<?php
namespace App\Model\Table;
use Search\Manager;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;
class PatientsTable extends Table
{
public function initialize(array $config)
{
parent::initialize($config);
$this->table('patients');
$this->displayField('Patient_ID');
$this->primaryKey('Patient_ID');
$this->addBehavior('Search.Search');
$this->searchManager()
->value('Patient_ID');
}
public function validationDefault(Validator $validator)
{
$validator
->allowEmpty('Patient_ID', 'create');
$validator
->requirePresence('Name', 'create')
->notEmpty('Name');
$validator
->requirePresence('Address', 'create')
->notEmpty('Address');
$validator
->date('DOB')
->requirePresence('DOB', 'create')
->notEmpty('DOB');
$validator
->allowEmpty('Contact');
$validator
->requirePresence('Gender', 'create')
->notEmpty('Gender');
$validator
->allowEmpty('Blood_Group');
return $validator;
}
}
MedicalReport table:
<?php
namespace App\Model\Table;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;
class MedicalReportTable extends Table
{
public function initialize(array $config)
{
parent::initialize($config);
$this->table('medical_report');
$this->displayField('Report_No');
$this->primaryKey('Report_No');
}
public function validationDefault(Validator $validator)
{
$validator
->requirePresence('Patient_ID', 'create')
->notEmpty('Patient_ID');
$validator
->requirePresence('Report_No', 'create');
$validator
->date('R_date')
->requirePresence('R_date', 'create')
->notEmpty('R_date');
$validator
->date('C_date')
->requirePresence('C_date');
$validator
->requirePresence('Room_No');
$validator
->allowEmpty('Diet');
$validator
->numeric('Payment')
->requirePresence('Payment');
return $validator;
}
}
You can use CakePHP's HtmlHelper to create an URL to view the Medical Report like so:
<?php
echo $this->Html->link(
'View Report',
['controller' => 'MedicalReports', 'action' => 'view', $MedicalReport->id],
['class' => 'button', 'target' => '_blank']);
This would create something like: View Report
General purpose method for creating HTML links. Use $options to
specify attributes for the element and whether or not the $title
should be escaped.
Read more about the HtmlHelper::link();
MedicalReportsController.php
In your controller you can create the view() function that defines the code for the action.
<?php // src/Controller/MedicalReportsController.php
class MedicalReportsController extends AppController {
public function view($id)
{
// Fetch the medical report from the database based on ID
$medicalReport = $this->MedicalReports->get($id);
// Pass it along to the view
$this->set('medical_report',$medicalReport);
} }
The set() function sends data to the View from the Controller.
The Controller::set() method is the main way to send data from your
controller to your view.
I'm trying to set a form field as the id of the current logged in user using Yii2.
This is my form:
<?php $form = ActiveForm::begin();?>
<?= Html::activeHiddenInput($model, 'id', array('value'=> $model->getId()));?>
<?= $form->field($model, 'offer_type_id') ?>
<?= $form->field($model, 'offer_description')->textArea(['rows' => 6]) ?>
<?= $form->field($model, 'start_date') ?>
<?= $form->field($model, 'end_date') ?>
<?= $form->field($model, 'store_id') ?>
<div class="form-group">
<?= Html::submitButton('Submit', ['class' => 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
and this is my model:
use Yii;
use yii\web\IdentityInterface;
/**
* This is the model class for table "tbl_offers".
*
* #property integer $offer_id
* #property integer $id
* #property integer $offer_type_id
* #property string $offer_description
* #property string $start_date
* #property string $end_date
* #property integer $store_id
*/
class TblOffers extends \yii\db\ActiveRecord implements IdentityInterface
{
public static function findIdentity($id)
{
return static::findOne($id);
}
public static function findIdentityByAccessToken($token, $type = null)
{
return static::findOne(['access_token' => $token]);
}
public function getId()
{
return $this->id;
}
public function getAuthKey()
{
return $this->authKey;
}
public function validateAuthKey($authKey)
{
return $this->authKey === $authKey;
}
/**
* #inheritdoc
*/
public static function tableName()
{
return 'tbl_offers';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[[ 'id', 'offer_type_id', 'offer_description', 'start_date', 'end_date', 'store_id'], 'required'],
[[ 'id', 'offer_type_id', 'store_id'], 'integer'],
[['start_date', 'end_date'], 'safe'],
[['offer_description'], 'string', 'max' => 8000]
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'offer_type_id' => 'Offer Type ID',
'offer_description' => 'Offer Description',
'start_date' => 'Start Date',
'end_date' => 'End Date',
'store_id' => 'Store ID',
];
}
public function getofferId()
{
return $this->getPrimaryKey();
}
}
Any ideas as to where I'm going wrong? When I try to save the form once I've filled in the rest, the form doesn't submit (and I'm guessing this is because the ID field hasn't been filled in) Any help would be appreciated!!
id is null since you are setting it to $this->id which has not been set anywhere.
You can get the currently logged in user using Yii::$app->user->id. As such there is no need for the hidden field or the rules for id. You can just set the id manually using ActiveRecord::beforeSave():
public function beforeSave($insert = true) {
if ($insert)
$this->id = Yii::$app->user->id;
return parent::beforeSave($insert);
}