I'm trying to save data from my form to db. But when I click "submit" button nothing happened(page is refresh but my db table is blank) what I did wrong?
I'm create model which extend ActiveRecord:
class EntryForm extends \yii\db\ActiveRecord
{
public $id;
public $name;
public $email;
public $age;
public $height;
public $weight;
public $city;
public $checkboxList;
public $checkboxList1;
public $imageFiles;
public function rules()
{
return [
[['name', 'email','age','height','weight','city','checkboxList','checkboxList1'], 'required'],
[['imageFiles'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg','maxFiles' => 5],
['email', 'email'],
];
}
public static function tableName()
{
return 'form';
}
public function attributeLabels()
{
return [
'id' => 'ID',
'name' => 'name',
'email' => 'e-mail',
'age' => 'age',
'height' => 'height',
'weight' => 'weight',
'city' => 'city',
'checkboxList' => 'technies',
'checkboxList1' => 'english_level',
'imageFiles[0]' => 'photo_1',
'imageFiles[1]' => 'photo_2',
'imageFiles[2]' => 'photo_3',
'imageFiles[3]' => 'photo_4',
'imageFiles[4]' => 'photo_5'
];
}
public function insertFormData()
{
$entryForm = new EntryForm();
$entryForm->name = $this->name;
$entryForm->email = $this->email;
$entryForm->age = $this->age;
$entryForm->height = $this->height;
$entryForm->weight = $this->weight;
$entryForm->city = $this->city;
$entryForm->checkboxList = $this->checkboxList;
$entryForm->checkboxList1 = $this->checkboxList1;
$entryForm->imageFiles = $this->imageFiles;
return $form->save();
}
public function contact($email)
{
if ($this->validate()) {
Yii::$app->mailer->compose()
->setTo($email)
->setFrom('prozrostl#gmail.com')
->setSubject('Email from test app')
->setTextBody($this->name + $this->age + $this->height + $this->width + $this->city + $this->checkboxList + $this->checkboxList1 + $this->imageFiles)
->send();
return true;
} else {
return false;
}
}
}
then I update my view file to show the form, view it's just easy few fields and upload files button(but all information doesn't save)
<?php $form = ActiveForm::begin([
'id' => 'my-form',
'options' => ['enctype' => 'multipart/form-data']
]); ?>
<div class="row">
<div class="col-lg-6">
<?= $form->field($entryForm, 'name')->textInput(['class'=>'name_class'])->input('name',['placeholder' => "Имя"])->label(false); ?>
</div>
<div class="col-lg-6">
<?= $form->field($entryForm, 'email')->textInput()->input('email',['placeholder' => "E-mail"])->label(false); ?>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<?= $form->field($entryForm, 'age')->textInput()->input('age',['placeholder' => "Возраст(полных лет)"])->label(false); ?>
</div>
<div class="col-lg-6">
<?= $form->field($entryForm, 'height')->textInput()->input('height',['placeholder' => "Рост"])->label(false); ?>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<?= $form->field($entryForm, 'weight')->textInput()->input('weight',['placeholder' => "Вес"])->label(false); ?>
</div>
<div class="col-lg-6">
<?= $form->field($entryForm, 'city')->textInput()->input('city',['placeholder' => "Город проживания"])->label(false); ?>
</div>
</div>
<div class="row">
<div class="col-lg-3">
<p><img class="describe_images" src="computer.png"></img>Нужна ли техника в аренду</p>
</div>
<?= $form->field($entryForm, 'checkboxList')->checkboxList(['no'=>'Нет', 'yes_camera'=>'Да,только камера', 'yes_both'=>'да,компьютер и камера'])->label(false) ?>
</div>
<div class="row">
<div class="col-lg-3">
<p><img class="describe_images" src="English.png"></img>Знание английского</p>
</div>
<?= $form->field($entryForm, 'checkboxList1')->checkboxList(['starter'=>'Без знания', 'elementary'=>'Базовый', 'intermediate'=>'Средний','up-intermediate'=>'Высокий','advanced'=>'Превосходный'])->label(false) ?>
</div>
<div class="row">
<div class="col-lg-6">
<div class="col-lg-6">
<p class="add_photo"><img class="describe_images" src="photo.png"></img>Добавить фото(до 5 штук)</p>
</div>
<div class="col-lg-6">
<?= $form->field($entryForm, 'imageFiles[]')->fileInput(['multiple' => true, 'accept' => 'image/*','id'=>'gallery-photo-add'])->label(false) ?>
</div>
</div>
<div class="col-lg-6 pixels-line">
<div class="preview"></div>
</div>
</div>
<div class="form-group">
<?= Html::submitButton('Отправить', ['class' => 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end() ?>
and then I add that code to my controller. I created new action ActionForm and put into that code:
public function actionForm()
{
$entryForm = new EntryForm();
if ($entryForm->load(Yii::$app->request->post()) && $entryForm->insertFormData()) {
}
}
Why do you redeclare the variables in the database? you're basically telling yii to ignore the attributes on the table.
public $id;
public $name;
public $email;
public $age;
public $height;
public $weight;
public $city;
public $checkboxList;
public $checkboxList1;
public $imageFiles;
Remove the public declarations and see if it works.
Your code looks ok, so probably you have some validation errors.
In the insertFormData() method add the following to get the validation errors:
if (!$entryForm->validate()){
var_dump($entryForm->getErrors());
}
Later edit:
Your insertFormData method is basically useless because the $entryForm->load loads the data from POST.
The second problem is probably with the file upload. To get the uploaded files use UploadedFile::getInstance($model, 'imageFile'). More info here
I suggest you to create a crud using Gii (the crud generator) and then implement the file upload according to the documentation mentioned above. And in this case you will see the validation errors too.
Related
so I'm making a crud function in codeigniter 4, it's just that I can't edit the data because of an error, namely controller or method not found
Here's the error :
enter image description here
Here My Routes:
$routes->get('/', 'Admin\Dashboard::index');
$routes->get('/produk', 'Admin\Produk::index');
$routes->get('/produk/kategori', 'Admin\Produk::kategori');
$routes->get('/produk/create', 'Admin\Produk::create');
$routes->post('/produk/save', 'Admin\Produk::save');
$routes->get('/produk/edit/(:segment)', 'Admin\Produk::edit/$1');
$routes->post('/produk/update_data', 'Admin\Produk::update_data');
$routes->delete('/produk/(:num)', 'Admin\Produk::delete/$1');
My controller :
<?php
namespace App\Controllers\Admin;
use App\Controllers\BaseController;
use \App\Models\KategoriModel;
class Produk extends BaseController
{
protected $kategoriModel;
public function __construct()
{
$this->kategoriModel = new KategoriModel();
}
public function index()
{
$data = [
'title' => 'Daftar Produk',
];
return view('admin/produk/index', $data);
}
public function kategori()
{
$data = [
'title' => 'Kategori Produk',
'kategori' => $this->kategoriModel->findAll(),
];
return view('admin/produk/kategori', $data);
}
public function create()
{
$data = [
'title' => 'Add Kategori',
'validation' => \Config\Services::validation()
];
return view('admin/produk/create', $data);
}
public function save()
{
//validasi input
if (!$this->validate([
'nama' => [
'rules' => 'required|is_unique[kategori_produk.nama]',
'errors' => [
'required' => '{field} nama harus diisi.',
'is_unique' => '{field} nama sudah ada.'
]
]
])) {
return redirect()->back()->
with('pesan', 'Data berhasil ditambahkan.');
}
$slug = url_title($this->request->getVar('nama'), '-', true);
$this->kategoriModel->save([
'nama' => $this->request->getVar('nama'),
'slug' => $slug,
]);
return redirect()->to('admin/produk/kategori');
}
public function delete($id)
{
//delete berdasarkan id
$this->kategoriModel->delete($id);
return redirect()->to('admin/produk/kategori');
}
public function edit($slug)
{
$data = [
'title' => 'Edit data',
'validation' => \Config\Services::validation(),
'kategori' => $this->kategoriModel->getKategori($slug)
];
return view('admin/produk/edit', $data);
}
public function update_data($id)
{
//validasi input
$kategoriLama = $this->kategoriModel->getKategori($this->request->getVar('slug'));
if ($kategoriLama['nama'] == $this->request->getVar('nama')) {
$rules_judul = 'required';
} else {
$rules_judul = 'required|is_unique[kategori_produk.nama]';
}
if (!$this->validate([
'nama' => [
'rules' => $rules_judul,
'errors' => [
'required' => '{field} nama harus diisi.',
'is_unique' => '{field} nama sudah ada.'
]
]
])) {
return redirect()->back()->with('pesan', 'Data berhasil diedit.');
}
$slug = url_title($this->request->getVar('nama'), '-', true);
$this->kategoriModel->save([
'id' => $id,
'nama' => $this->request->getVar('nama'),
'slug' => $slug,
]);
session()->setFlashdata('pesan', 'Data berhasil diupdate');
return redirect()->to('produk/kategori');
}
}
My views(edit.php):
<?= $this->extend('layout/templates'); ?>
<?= $this->section('content'); ?>
<div id="layoutSidenav_content">
<main>
<div class="container-fluid px-4">
<h1 class="mt-4">Edit Data</h1>
<ol class="breadcrumb mb-4">
<li class="breadcrumb-item">Dashboard</li>
<li class="breadcrumb-item active">Static Navigation</li>
</ol>
<div class="card mb-4">
<div class="card-body">
<div class="card mb-4">
<div class="card-header">
<i class="fas fa-table me-1"></i>
Kategori Produk
</div>
<div class="card-body">
<div class="container">
<div class="row">
<div class="col-8">
<h2 class="my-3">Form Edit Komik</h2>
<form action="/produk/update_data/<?= $kategori['id']; ?>" method="POST" enctype="multipart/form-data">
<?= csrf_field(); ?>
<input type="hidden" name="slug" value="<?= $kategori['slug']; ?>">
<div class="form-group row">
<label for="nama" class="col-sm-2 col-form-label">Nama</label>
<div class="col-sm-10">
<input type="text" class="form-control <?= ($validation->hasError('nama')) ? 'is-invalid' : ''; ?>" id="nama" name="nama" autofocus value="<?= (old('nama')) ? old('nama') : $kategori['nama'] ?>">
<div id="validationServer03Feedback" class="invalid-feedback">
<?= $validation->getError('nama'); ?>
</div>
</div>
</div>
<div class="form-group row">
<div class="col-sm-10">
<button type="submit" class="btn btn-primary">Edit</button>
</div>
</div>
</form>
<br><br>
Kembali ke kategori
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</main>
<?= $this->endSection(); ?>
My Controllers folder are :
enter image description here
My Views folder are :
enter image description here
can anyone help me?
Thank you
Even though save and delete data work very well, except updating data.I try many times changing the routes or the controller but the error is still the same. I hope someone can help me.
I am trying to integrate TinyMCE editor with CodeIgniter 4 application. However the data from the tinyMCE textarea is not getting submitted to database even when i click on submit button but with normal textarea the data is submitted to database easily.
Also when i edit & update the submitted data, it gets updated in the database but the text formatting from tinyMCE is erased and data is saved as normal text in the database.
Here is my code below
Add page controller
public function addPage() {
if(!session()->has('logged_staff')) {
return redirect()->to(base_url(). "/team");
}
$data = [];
$data['validation'] = null;
$suid = session()->get('logged_staff');
$data['staffdata'] = $this->adminModel->getLoggedStaffData($suid);
$data['memrole'] = $this->adminModel->getMemberRole($suid);
$data['permission'] = $this->adminModel->getPermission($suid);
$checkPermission = $this->adminModel->checkPermission($suid);
$memrank = $this->adminModel->getMemberRank($suid);
if(is_array($memrank)) {
if($memrank['rank'] == 'Super Admin') {
}
elseif(isset($checkPermission)) {
if($checkPermission['pages'] == 'Not Allowed') {
return redirect()->back();
}
}
}
if($this->request->getMethod() == 'post') {
$rules = [
'p_name' => [
'rules' => 'required|min_length[3]|max_length[250]',
'errors' => [
'required' => 'You cannot leave this field empty',
'min_length' => 'Title is short',
'max_length' => 'Title is too long',
]
],
'p_description' => [
'rules' => 'required',
'errors' => [
'required' => 'You cannot leave this field empty',
]
],
];
if($this->validate($rules)) {
$addContent = [
'p_name' => $this->request->getVar('p_name', FILTER_SANITIZE_STRING),
'p_description' => htmlentities($this->request->getVar('p_description', FILTER_SANITIZE_STRING)),
'p_date' => date("Y-m-d h:i:s"),
'p_slug' => strtolower(url_title($this->request->getVar('p_name'))),
];
if($this->pageModel->insertContent($addContent)) {
$this->session->setTempdata('success', 'Page updated successfully', 3);
return redirect()->to(base_url()."/admin/pages");
} else {
$this->session->setTempdata('error', 'Oops! could not update the page', 3);
return redirect()->to(current_url());
}
} else {
$data['validation'] = $this->validator;
}
}
echo view("team/Templates/header_panel");
echo view("team/navigation", $data);
echo view("team/sidebar", $data);
echo view("team/addpage", $data);
echo view("team/Templates/footer_panel");
}
Edit Page Controller
public function editPage($id=null) {
if(!session()->has('logged_staff')) {
return redirect()->to(base_url(). "/team");
}
$data = [];
$data['validation'] = null;
$suid = session()->get('logged_staff');
$data['staffdata'] = $this->adminModel->getLoggedStaffData($suid);
$data['memrole'] = $this->adminModel->getMemberRole($suid);
$data['permission'] = $this->adminModel->getPermission($suid);
$checkPermission = $this->adminModel->checkPermission($suid);
$memrank = $this->adminModel->getMemberRank($suid);
if(is_array($memrank)) {
if($memrank['rank'] == 'Super Admin') {
}
elseif(isset($checkPermission)) {
if($checkPermission['pages'] == 'Not Allowed') {
return redirect()->back();
}
}
}
$data['p_data'] = $this->db->table('tblpages')
->select('*')
->where(["id" => $id])
->get()
->getRow();
if($this->request->getMethod() == 'post') {
$rules = [
'p_name' => [
'rules' => 'required|min_length[3]|max_length[250]',
'errors' => [
'required' => 'You cannot leave this field empty',
'min_length' => 'Title is short',
'max_length' => 'Title is too long',
]
],
'p_description' => [
'rules' => 'required',
'errors' => [
'required' => 'You cannot leave this field empty',
]
],
];
if($this->validate($rules)) {
$pageContent = [
'p_name' => $this->request->getVar('p_name', FILTER_SANITIZE_STRING),
'p_description' => htmlentities($this->request->getVar('p_description', FILTER_SANITIZE_STRING)),
'p_slug' => strtolower(url_title($this->request->getVar('p_name'))),
];
if($this->pageModel->updateContent($pageContent, $id)) {
$this->session->setTempdata('success', 'Page updated successfully', 3);
return redirect()->to(base_url()."/admin/pages");
} else {
$this->session->setTempdata('error', 'Oops! could not update the page', 3);
return redirect()->to(current_url());
}
} else {
$data['validation'] = $this->validator;
}
}
echo view("team/Templates/header_panel");
echo view("team/navigation", $data);
echo view("team/sidebar", $data);
echo view("team/editpage", $data);
echo view("team/Templates/footer_panel");
}
Edit - Create Page View File
<?php
$page_session = \Config\Services::session();
?>
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<div class="container-fluid">
<div class="row mb-2">
<div class="col-sm-6">
<h1>Add New Page</h1>
</div>
<div class="col-sm-6">
<ol class="breadcrumb float-sm-right">
<li class="breadcrumb-item">Home</li>
<li class="breadcrumb-item">Page List</li>
<li class="breadcrumb-item active">Add New Page</li>
</ol>
</div>
</div>
</div><!-- /.container-fluid -->
</section>
<section class="content">
<div class="container-fluid">
<div class="row">
<div class="col-lg-12">
<div class="contact__form__title">
<?php if($page_session->getTempdata('success', 3)) : ?>
<div class="alert alert-success">
<?= $page_session->getTempdata('success', 3); ?>
</div>
<?php endif; ?>
<?php if($page_session->getTempdata('error', 3)) : ?>
<div class="alert alert-danger">
<?= $page_session->getTempdata('error', 3); ?>
</div>
<?php endif; ?>
</div>
</div>
</div>
</div>
</section>
<!-- Main content -->
<section class="content">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<div class="card card-primary">
<ul class="nav nav-tabs nav-pills nav-fill">
<li class="nav-item">
Add Page
</li>
</ul>
<div class="card-body">
<div class="tab-content">
<div id="details" class="tab-pane active">
<?= form_open('admin/addPage/'); ?>
<div class="form-group row">
<div class="col-sm-12">
<?= csrf_field(); ?>
</div>
</div>
<div class="form-group row">
<div class="col-sm-12">
<label for="pTitle">Edit Title</label>
<input type="text" name="p_name" value="<?= set_value('p_name'); ?>" class="form-control" id="pTitle" placeholder="Page Name or Page Title" required>
<span class="text-danger"><?= display_errors($validation, 'p_name'); ?></span>
</div>
</div>
<div class="form-group row">
<div class="col-sm-12">
<label for="pContent">Edit Page Content</label>
<textarea id="editor" name="p_description" class="form-control" id="pContent" cols="10" rows="10" placeholder="Write something here.." required><?= set_value('p_description'); ?></textarea>
<span class="text-danger"><?= display_errors($validation, 'p_description'); ?></span>
</div>
</div>
<div class="form-group row">
<div class="col-sm-12">
<button type="submit" class="btn btn-primary">Create Page</button>
Cancel
</div>
</div>
<?= form_close(); ?>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<!-- /.content -->
</div>
<!-- /.content-wrapper -->
init.js file - TinyMCE code to initiate the editor
tinymce.init({
selector: '#editor',
valid_elements : '*[*]',
});
Edited the addPage controller code - Still doesn't work
if(!$this->validate([
'p_name' => 'required|min_length[3]|max_length[250]',
'p_description' => 'required',
])){
echo view("team/Templates/header_panel");
echo view("team/navigation", $data);
echo view("team/sidebar", $data);
echo view("team/addpage", $data);
echo view("team/Templates/footer_panel");
}
else {
if($this->pageModel->save) {(
[
'p_name' => $this->request->getVar('p_name', FILTER_SANITIZE_STRING),
'p_description' => $this->request->getVar('p_description'),
'p_date' => date("Y-m-d h:i:s"),
'p_slug' => strtolower(url_title($this->request->getVar('p_name'))),
]
);
$this->session->setTempdata('success', 'Page Created successfully', 3);
return redirect()->to(base_url()."/admin/pages");
}
else {
$this->session->setTempdata('error', 'Unable to create page', 3);
return redirect()->to(current_url());
}
}
Model for this entire code
namespace App\Models;
use CodeIgniter\Model;
class PageModel extends Model {
protected $table = 'tblpages';
protected $allowedFields = ['p_name', 'p_description', 'p_date', 'p_slug'];
public function getPages($slug = null) {
if(!$slug) {
return $this->findAll();
}
return $this->asArray()
->where(['p_slug' => $slug])
->first();
}
public function updateContent($pageContent, $id) {
$builder = $this->db->table('tblpages');
$builder->where('id', $id);
$result = $builder->update($pageContent);
if($this->db->affectedRows() > 0) {
return true;
} else {
return false;
}
}
// Delete Page
public function deletePage($id) {
$builder = $this->db->table('tblpages');
$builder->where('id', $id);
$builder->delete();
}
}
Please help me on this one. Thanks everyone in advance!
I believe this is the culprit in both controllers
'p_description' => htmlentities($this->request->getVar('p_description', FILTER_SANITIZE_STRING))
According to PHP manual, FILTER_SANITIZE_STRING:
Strip tags and HTML-encode double and single quotes, optionally strip or encode special characters.
Since you want to keep the HTML markup, simply remove the FILTER_SANITIZE_STRINGS filter and you should be good to go.
Another problem with your view file is that your text editor has two id's: editor1 and pContent`
<textarea id="editor" name="p_description" class="form-control" id="pContent" cols="10" rows="10" placeholder="Write something here.." required><?= set_value('p_description'); ?></textarea>
Remove the extra id, and everything should be fine.
Edit about the create code not working
In your addPage controller, I noticed this:
if($this->pageModel->save) {([
'p_description' => ...,
])
}
Note that that's not the same as
if($this->pageModel->save([
'p_description' => '...',
])) {
// ...
}
I am using live wire and when I try to validate the form it say
Method Livewire\Redirector::withInput does not exist.
and this is my code
Posts.php
<?php
namespace App\Http\Livewire;
use Livewire\Component;
use App\Models\Post;
class Posts extends Component
{
public $title;
public $content;
public function hydrate(){
$this->validate([
'title' => 'required',
'content' => 'required'
]);
}
public function save(){
$data = [
'title' => $this->title,
'content' => $this->content,
'user_id' => Auth()->user()->id
];
Post::create($data);
$this->cleanVars();
}
private function cleanVars(){
$this->title = null;
$this->content = null;
}
public function render()
{
return view('livewire.posts');
}
}
livewire view
<div>
<label>Title</label>
<input wire:model="title" type="text" class="form-control" />
#error('title')
<p class="text-danger">{{ $message }}</p>
#enderror
<label>Content</label>
<textarea wire:model="content" type="text" class="form-control"></textarea>
#error('content')
<p class="text-danger">{{ $message }}</p>
#enderror
<br />
<button wire:click="save" class="btn btn-primary">Save</button>
</div>
also I putted this view in home.blade.php
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">{{ __('Dashboard') }}</div>
<div class="card-body">
#livewire('posts')
</div>
</div>
</div>
</div>
</div>
#endsection
Really you need to fix the header of this question, is repeating the same and you're missing something there to the community. I see in your code this and I dislike this use
public function hydrate(){
$this->validate([
'title' => 'required',
'content' => 'required'
]);
}
I mean, this validation running on every hydration isn't a good approach of this. Instead, declare the rules
protected $rules = [// rules here];
//or
public function rules()
{
return [
//rules here
];
}
then you can validate the entries, for example on real-time validation using the validateOnly method inside the updated()
public function updated($propertyName)
{
$this->validateOnly($propertyName, $this->rules());
}
or just use it in the save method
public function save()
{
$this->validate(); // in the protected $rules property
// or
Post::create($this->validate());
}
I am trying to render two models in the actionView method, but without result. Checked some answers on previous questions and it seems my method is OK, but still do not work.
This is what a made for method view:
public function actionView($id)
{
$postModel = Post::find()->where(['post_id' => $id])->one();
$currUser = BlogUser::find()->where(['id' => $postModel->user_id])->one();
return $this->render('view', [
'model' => $this->findModel($id),
'author' => $currUser
]);
}
and my view page:
<?php
use yii\helpers\Html;
use yii\widgets\DetailView;
/* #var $this yii\web\View */
/* #var $model app\models\Post */
//$this->title = $model->title;
//$this->params['breadcrumbs'][] = ['label' => 'Posts', 'url' => ['index']];
//$this->params['breadcrumbs'][] = $this->title;
?>
<div class="post-view">
<div class="content">
<div class="row">
<div class="col-md-3">
<?= $model->content;
$author->username;
?>
</div>
</div>
</div>
</div>
It tells that the author variable is undefined but cannot realize why when i render it in the action. Will appreciate every advice! Thank you!
Try using:
<div class="post-view">
<div class="content">
<div class="row">
<div class="col-md-3">
<?= $model->content; ?>
<?= $author->username; ?>
</div>
</div>
</div>
</div>
I am currently doing a project in PHP Yii framework.
I have a form with file input field called company_logo.For the field I have added the following rule in the model [['company_logo'],'file','skipOnEmpty'=>false]
When I upload file, it shows
Please upload a file.
even if I uploaded a file.
When I remove the
skipOnEmpty
it is uploading the file.I have researched several places for the issue.But couldn't find a solution.
The controller, view and model are given below
View - add_company.php
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/*Assigning the parameters to be accessible by layouts*/
foreach($layout_params as $layout_param => $value) {
$this->params[$layout_param] = $value;
}
?>
<div class="form-group">
</div>
<div class="col-md-12">
<div class="box box-primary">
<div class="box-header">
<h3 class="box-title">Add Company</h3>
</div><!-- /.box-header -->
<!-- form start -->
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
<div class="box-body">
<?php if(isset($message)&&sizeof($message)): ?>
<div class="form-group">
<div class="callout callout-info alert-dismissible">
<h4><?php if(isset($message['title']))echo $message['title'];?></h4>
<p>
<?php if(isset($message['body']))echo $message['body'];?>
</p>
</div>
</div>
<?php endif;?>
<div class="form-group">
<?= $form->field($model, 'company_name')->textInput(array('class'=>'form-control')); ?>
</div>
<div class="form-group">
<?= $form->field($model, 'company_address')->textArea(array('class'=>'form-control')); ?>
</textarea>
<div class="form-group">
<?= $form->field($model, 'company_logo')->fileInput(array('class'=>'form-control')); ?>
</div>
<div class="form-group">
<?= $form->field($model, 'admin_name')->textInput(array('class'=>'form-control')); ?>
</div>
<div class="form-group">
<?= $form->field($model, 'admin_email')->textInput(array('class'=>'form-control','type'=>'email')); ?>
</div>
<div class="form-group">
<?= $form->field($model, 'admin_phone_number')->textInput(array('class'=>'form-control')); ?>
</div>
<div class="form-group">
<?= $form->field($model, 'admin_password')->passwordInput(array('class'=>'form-control')); ?>
</div>
<div class="form-group">
<?= $form->field($model, 'retype_admin_password')->passwordInput(array('class'=>'form-control')); ?>
</div>
<div class="box-footer">
<?= Html::submitButton('Submit', ['class' => 'btn btn-primary']) ?>
</div>
</div><!-- /.box-body -->
<?php ActiveForm::end(); ?>
</div>
</div>
Controller - CompanyController.php
<?php
namespace app\controllers;
use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\filters\VerbFilter;
use app\models\CompanyModel;
use yii\web\UploadedFile;
global $username;
class CompanyController extends Controller
{
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['logout'],
'rules' => [
[
'actions' => ['logout'],
'allow' => true,
'roles' => ['#'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],
];
}
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
],
];
}
public function actionEntry()
{
}
public function actionAdd() {
$layout_params=array(
'username'=>'admin',
'sidebar_menu1_class' =>'active',
'sidebar_menu12_class' =>'active',
'dash_title' => 'Companies',
'dash_sub_title'=>'Add new company'
);
$message = array();
$model = new CompanyModel();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
echo "hello";
$model->company_logo = UploadedFile::getInstance($model, 'company_logo');
echo "world";
if ($model->company_logo && $model->validate()) {
$model->company_logo->saveAs('uploads/' . $model->company_logo->baseName . '.' . $model->company_logo->extension);
} else {
echo "Yo Yio ture";
exit;
}
$model->add_company();
$message['title'] = 'Wow !';
$message['body'] = 'Successfully added company '.$model->company_name;
}else {
$message = $model->getErrors();
// print_r( $message );
// exit;
}
return $this->render('add-company', ['model' => $model,
'layout_params'=>$layout_params,
'message' =>$message
]);
//return $this->render('add-company',$data);
}
public function actionSave() {
//print_r($_POST);
}
public function actionIndex()
{
$data = array(
'layout_params'=>array(
'username'=>'admin',
'sidebar_menu11_class' =>'active'
)
);//
}
public function actionLogout()
{
Yii::$app->user->logout();
return $this->goHome();
}
}
Model - CompanyModel.php
<?php
namespace app\models;
use yii;
use yii\db;
use yii\base\Model;
use yii\web\UploadedFile;
class CompanyModel extends Model
{
public $company_name;
public $company_address;
public $company_logo;
public $admin_email;
public $admin_name;
public $admin_password;
public $retype_admin_password;
public $admin_phone_number;
public function rules()
{
return [
[['company_name'], 'required'],
[['company_address'],'required'],
[['admin_name'],'required'],
[['admin_email'],'required'],
[['admin_password'],'required'],
[['retype_admin_password'],'required'],
[['admin_phone_number'],'required'],
[['company_logo'],'file','skipOnEmpty'=>false]
];
}
public function add_company() {
Yii::$app->db->close();
Yii::$app->db->open();
$comm = Yii::$app->db->createCommand("CALL create_company('".$this->company_name."','".$this->company_address."','".$this->admin_email."','".$this->admin_phone_number."',1)");
return $comm->execute() ;
}
}
<?php
namespace app\models;
use yii;
use yii\db;
use yii\base\Model;
use yii\web\UploadedFile;
class CompanyModel extends Model
{
public $company_name;
public $company_address;
public $company_logo;
public $admin_email;
public $admin_name;
public $admin_password;
public $retype_admin_password;
public $admin_phone_number;
public function rules()
{
return [
[['company_name'], 'required'],
[['company_address'],'required'],
[['admin_name'],'required'],
[['admin_email'],'required'],
[['admin_password'],'required'],
[['retype_admin_password'],'required'],
[['admin_phone_number'],'required'],
[['company_logo'],'file','skipOnEmpty'=>false],//here the comma is missing
];
}
public function add_company() {
Yii::$app->db->close();
Yii::$app->db->open();
$comm = Yii::$app->db->createCommand("CALL create_company('".$this->company_name."','".$this->company_address."','".$this->admin_email."','".$this->admin_phone_number."',1)");
return $comm->execute() ;
}
}