I have the below code in studentsController.php to add data to 2 tables from a form but im getting error. It is to add to students table, then add some data to the users table too. I feel i'm supposed to add something at the top via "use' keyword but I don't know.please help.
public function actionCreate() {
$model = new model();
$user = new Users();
if ($model->load(Yii::$app->request->post())) {
$model->id = Yii::$app->generateid->getGUID(); //this line caused the error
$model->save();
$studentId = $model->id;
if($user->load(Yii::$app->request->post()))
{
$user->id = $model->id;
$user->firstname = $model->firstname;
$user->lastname = $model->lastname;
$user->username = $model->phone;
$user->password = 'pass123'; //default password
$user->role = 'student';
$user->save(false);
}
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
'user' => $user,
]);
}
}
You seem to miss generateid in your web.php
It should be something like this
GenerateIDs.php inside #app/components folder
<?php
namespace app\components;
class GenerateIDs extends \yii\base\Component
{
public function getGUID()
{
//do your stuff here
}
//....
}
then in your #app/config/web.php you have something like
<?php
return [
'components' => [
'generateid' => [
'class'=>'app\components\GenerateIDs',
// other configurations for the component
],
],
];
then you can use it in your app as you wish
public function actionCreate() {
$model = new model();
$user = new Users();
if ($model->load(Yii::$app->request->post())) {
$model->id = Yii::$app->generateid->getGUID(); //this line caused the error
$model->save();
$studentId = $model->id;
if($user->load(Yii::$app->request->post()))
{
$user->id = $model->id;
$user->firstname = $model->firstname;
$user->lastname = $model->lastname;
$user->username = $model->phone;
$user->password = 'pass123'; //default password
$user->role = 'student';
$user->save(false);
}
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
'user' => $user,
]);
}
Please take a look at Yii2 guide on Components
Related
My Laravel insert function in my controller looks for a "created_by" column that I do not have.
Model
class HmsBbrCategory extends Model
{
public $timestamps = false;
protected $table = 'hms_bbr_category';
protected $fillable = ["id", "category_id", "category_name",
"category_description"];
}
Controller
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'category_name' => 'required|max:191',
'category_description' => 'required|max:191',
]);
if ($validator->fails()) {
return response()->json([
'status' => 400,
'errors' => $validator->messages(),
]);
} else {
$categoryId = HmsBbrCategory::orderByDesc('id')->first();
$autoIncId = $categoryId->id + 1;
$category = new HmsBbrCategory;
$category->category_name = $request->input('category_name');
$category->category_description = $request->input('category_description');
// Option tags
$category->config_view_type = $request->input('config_view_type');
$category->config_edit_type = $request->input('config_edit_type');
$category->bbrmode_view_type = $request->input('bbrmode_view_type');
$category->id = $autoIncId;
$category->category_id = $autoIncId;
$category->save();
return response()->json([
'status' => 200,
'message' => 'Category Added!'
]);
}
}
I have a feeling that I may have the issue here in my request: $validator = Validator::make($request->all(), [ I was thinking that by all() I was taking all columns that I added. But this line may be the one looking for created_by. So how do I make an exemption not to have my code look for created_by?
Appears like your created_by column is NOT NULL, change to NULL
As the title says, i have a little bit of trouble in this area of the application. So basically, in my UserController i hash the password & in the login page it's verified with the standard security tool. Everything from the form to the user is good, but the check fails to return true. I don't have any interactions with the password in beforeSave/beforeValidate. Any ideas?
UserController:
public function actionRegister()
{
$model = new User(['scenario' => 'register']);
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$model->password_usr = Yii::$app->security->generatePasswordHash($model->password_usr);
if ($model->save()) {
Yii::$app->session->setFlash('success', 'User created');
return $this->redirect('/site/login');
} else {
die(print_r($model->getErrors()));
}
}
return $this->render('register', [
'model' => $model,
]);
}
SiteController:
public function actionLogin()
{
if (!Yii::$app->user->isGuest) {
return $this->goHome();
}
$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$model->login();
return $this->goBack();
}
$model->password = '';
return $this->render('login', [
'model' => $model,
]);
}
User model:
public function validatePassword($password)
{
return Yii::$app->security->validatePassword($password, $this->password_usr);
}
Login form is the default as the yii2 generates
Maybe this is a problem
die(print_r($model->getErrors()));
login
public function actionLogin()
{
$this->layout = "login";
if (!Yii::$app->user->isGuest) {
return $this->goHome();
}
$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->login()) {
return $this->goBack();
} else {
$model->password = '';
}
return $this->render('login', [
'model' => $model,
]);
}
signup
public function actionSignup()
{
$this->layout = "login";
$model = new SignupForm();
if ($model->load(Yii::$app->request->post())) {
if ($user = $model->signup()) {
if (Yii::$app->getUser()->login($user)) {
return $this->goHome();
}
}
}
return $this->render('signup', [
'model' => $model,
]);
}
the problem was the password field in the database, it was varchar(30) whilst generatePasswordHash returns a 60 char string
This is a model Method
public function setTerritories($territories)
{
$t = Territory::find()->where(['id' => $territories])->all();
$this->populateRelation('territories', $t);
}
The controller is simple
public function actionUpdate($id)
{
$model = $this->findModel($id);
$model->scenario = 'update';
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
The relation is filled; if I var_dump($model->territories); it shows needed models, but after save they're not attached.
Why doesn't populateRelation save the data?
Tell me where I was wrong, everything is tried
my view file:
echo FileInput::widget([
'model' => $model,
'attribute' => 'files[]',
'options' => ['multiple' => true]
]);
Also i added
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]) ?>
enctype option to form element
Model:
i add two variables as property:
public $files; // files instance
public $serialize; // set string which store the files
in rules
serialize as string, and files:
[['files'], 'file', 'skipOnEmpty' => true, 'extensions' => 'gif, jpg, png, pdf, doc, docx', 'maxFiles' => 10],
and controller action:
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post())) {
$oldFiles = $model->serialize;
$files = UploadedFile::getInstance($model, 'files');
if($files === false){
$model->serialize = $oldFiles;
} else {
$serialize = [];
if($model->validate()){
foreach($files as $file){
$ext = end((explode(".", $file)));
$filename = Yii::$app->security->generateRandomString().".{$ext}";
$serialize[] = $filename;
$file->saveAs(Yii::$app->basePath . '/web/image/' . $filename);
}
} else {
}
//print_r($model->getErrors()); die();
$model->serialize = serialize($serialize);
}
$model->save();
return $this->redirect(['view', 'id' => $model->news_id]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
So, $files is empty, why?
also i get a "4" code error in $_FILES array
It should be getInstances for multiple files.
$files = UploadedFile::getInstances($model, 'files');
I am trying to fetch my category model in zend form for working out with select element with zend framework 2.
after lot of code searching I found I can either inject or pull dependencies.
Following code I did in my module.php
I want categoryTable.php(model) file in my CategoryForm.php
public function getServiceConfig()
{
return array(
'factories' => array(
'Category\Model\CategoryTable' => function($sm) {
$tableGateway = $sm->get('CategoryTableGateway');
$table = new CategoryTable($tableGateway);
//echo "<pre>";print_r($table);echo "</pre>";
return $table;
},
'CategoryTableGateway' => function ($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Category());
return new TableGateway('Of_Restaurants_Category', $dbAdapter, null, $resultSetPrototype);
},
'Category\Form\CategoryForm' => function ($sm) {
$service = $sm->get('Category\Model\CategoryTable');
$form = new Form;
$form->setService($service);
return $form;
}
),
);
}
then I put following code in my controller.
$form = $this->getServiceLocator()->get("Category\Form\CategoryForm");
Then I Put following code in my CategoryForm.php
public function getCategoryTable()
{
if (!$this->categoryTable) {
$sm = $this->getServiceLocator();
$this->categoryTable = $sm->get('Category\Model\CategoryTable');
}
return $this->categoryTable;
}
And then I call it in same file like this way
public function __construct($name = null)
{
parent::__construct('category');
echo "<pre>";print_r($this->getCategoryTable());die;
.... other code
I found this error
Fatal error: Call to undefined method Category\Form\CategoryForm::getServiceLocator() in D:\wamp\www\zendapp\module\Category\src\Category\Form\CategoryForm.php on line 120
please help. and am I missing something?
I found the solution
Step :1
Here is my module.php code
public function getServiceConfig()
{
return array(
'invokables' => array(
'Category\Form\CategoryForm' => 'Category\Form\CategoryForm',
),
'factories' => array(
'Category\Model\CategoryTable' => function($sm) {
$tableGateway = $sm->get('CategoryTableGateway');
$table = new CategoryTable($tableGateway);
//echo "<pre>";print_r($table);echo "</pre>";
return $table;
},
'CategoryTableGateway' => function ($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Category());
return new TableGateway('Of_Restaurants_Category', $dbAdapter, null, $resultSetPrototype);
},
),
);
}
Step :2
Then in controller I made this change
// $form = new CategoryForm();
// Service locator now injected
$form = $this->getServiceLocator()->get('Category\Form\CategoryForm');
Step :3
Then In my categoryForm.php I made below changes
use Zend\ServiceManager\ServiceManager;
use Zend\ServiceManager\ServiceManagerAwareInterface;
protected $serviceManager;
public function getCategoryTable()
{
if (!$this->categoryTable) {
$sm = $this->getServiceManager();
$this->categoryTable = $sm->get('Category\Model\CategoryTable');
}
return $this->categoryTable;
}
protected function getCatList()
{
$groups = $this->getCategoryTable()->fetchAll();
return $groups;
}
public function getServiceManager()
{
if ( is_null($this->serviceManager) ) {
throw new Exception('The ServiceManager has not been set.');
}
return $this->serviceManager;
}
public function setServiceManager(ServiceManager $serviceManager)
{
$this->serviceManager = $serviceManager;
// Call the init function of the form once the service manager is set
$this->init();
return $this;
}
public function __construct($name = null) // constructor I finished immediately
{
parent::__construct('category');
}
I add INIT() function to fetch servicemanager
public function init()
{
$this->setAttribute('method', 'post');
$options = array();
foreach ($this->getCatList() as $cat) {
$options[$cat->id] = $cat->title;
}
$this->add(array(
'type' => 'Zend\Form\Element\Select',
'name' => 'parent_id',
'options' => array(
'label' => 'Parent Category',
'empty_option' => 'Please choose Parent Category',
'value_options' => $options,
),
));
}
Hope this will help who are new ZF2.