I am new to yii2.0, and I'm currently creating a form po
and po_item, the problem is to update the form the modelPoItem is empty from database.
I thank those who can help me for this Home with dynamic form can be with an example. Thank you in advance
Po Controller
/**
* Updates an existing Po model.
* If update is successful, the browser will be redirected to the 'view' page.
* #param integer $id
* #return mixed
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);
$modelsPoItem = [new PoItem];
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('update', [
'model' => $model,
'modelsPoItem' => (empty($modelsPoItem)) ? [new PoItem] : $modelsPoItem
]);
}
}
View
<div class="po-form">
<?php $form = ActiveForm::begin(['id' => 'dynamic-form']); ?>
<?= $form->field($model, 'po_no')->textInput(['maxlength' => 10]) ?>
<?= $form->field($model, 'description')->textarea(['rows' => 6]) ?>
<div class="row">
<div class="panel panel-default">
<div class="panel-heading"><h4><i class="glyphicon glyphicon-envelope"></i> Po Items</h4></div>
<div class="panel-body">
<?php DynamicFormWidget::begin([
'widgetContainer' => 'dynamicform_wrapper', // required: only alphanumeric characters plus "_" [A-Za-z0-9_]
'widgetBody' => '.container-items', // required: css class selector
'widgetItem' => '.item', // required: css class
'limit' => 10, // the maximum times, an element can be cloned (default 999)
'min' => 1, // 0 or 1 (default 1)
'insertButton' => '.add-item', // css class
'deleteButton' => '.remove-item', // css class
'model' => $modelsPoItem[0],
'formId' => 'dynamic-form',
'formFields' => [
'po_item_no',
'quantity',
],
]); ?>
<div class="container-items"><!-- widgetContainer -->
<?php foreach ($modelsPoItem as $i => $modelPoItem): ?>
<div class="item panel panel-default"><!-- widgetBody -->
<div class="panel-heading">
<h3 class="panel-title pull-left">Po Item</h3>
<div class="pull-right">
<button type="button" class="add-item btn btn-success btn-xs"><i class="glyphicon glyphicon-plus"></i></button>
<button type="button" class="remove-item btn btn-danger btn-xs"><i class="glyphicon glyphicon-minus"></i></button>
</div>
<div class="clearfix"></div>
</div>
<div class="panel-body">
<?php
// necessary for update action.
if (! $modelPoItem->isNewRecord) {
echo Html::activeHiddenInput($modelPoItem, "[{$i}]id");
}
?>
<div class="row">
<div class="col-sm-6">
<?= $form->field($modelPoItem, "[{$i}]po_item_no")->textInput(['maxlength' => 128]) ?>
</div>
<div class="col-sm-6">
<?= $form->field($modelPoItem, "[{$i}]quantity")->textInput(['maxlength' => 128]) ?>
</div>
</div><!-- .row -->
</div>
</div>
<?php endforeach; ?>
</div>
<?php DynamicFormWidget::end(); ?>
</div>
</div>
</div>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
you should be change you update action like this:
public function actionUpdate($id)
{
$model = $this->findModel($id);
$modelsPoItem = $model->poItems;
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$oldIDs = ArrayHelper::map($modelsPoItem, 'id', 'id');
$modelsPoItem= Model::createMultiple(PoItem::className(),$modelsPoItem);
Model::loadMultiple($modelsPoItem, Yii::$app->request->post());
$deletedIDs = array_diff($oldIDs, array_filter(ArrayHelper::map($modelsPoItem, 'id', 'id')));
// ajax validation
if (Yii::$app->request->isAjax) {
Yii::$app->response->format = Response::FORMAT_JSON;
return ArrayHelper::merge(
ActiveForm::validateMultiple($modelsPoItem),
ActiveForm::validate($model)
);
}
// validate all models
$valid = $model->validate();
$valid = Model::validateMultiple($modelsPoItem) && $valid;
if ($valid) {
$transaction = \Yii::$app->db->beginTransaction();
try {
if ($flag = $model->save(false)) {
if (! empty($deletedIDs)) {
PoItem::deleteAll(['id' => $deletedIDs]);
}
foreach ($modelsPoItem as $modelPoItem) {
$modelPoItem->po_id = $model->id;
if (! ( $flag = $modelPoItem->save(false))) {
$transaction->rollBack();
break;
}
}
}
if ($flag) {
$transaction->commit();
return $this->redirect(['view', 'id' => $model->id]);
}
} catch (Exception $e) {
$transaction->rollBack();
}
}
} else {
return $this->render('update', [
'model' => $model,
'modelsPoItem' => (empty($modelsPoItem)) ? [new Model] : $modelsPoItem
]);
}
}
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 wbraganca
/
yii2-dynamicform. I am able to create a new record. There are two models that I am using to create records. The data is saved into both of the tables.
<?= $form->field($model, 't_name')->textInput(['maxlength' => true]) ?>
<div class="row">
<div class="panel panel-default">
<div class="panel-heading"><h4><i class="glyphicon glyphicon-flash"></i> Tariff Slabs</h4></div>
<div class="panel-body">
<?php DynamicFormWidget::begin([
'widgetContainer' => 'dynamicform_wrapper', // required: only alphanumeric characters plus "_" [A-Za-z0-9_]
'widgetBody' => '.container-items', // required: css class selector
'widgetItem' => '.item', // required: css class
'limit' => 10, // the maximum times, an element can be cloned (default 999)
'min' => 1, // 0 or 1 (default 1)
'insertButton' => '.js-add-filter', // css class
'deleteButton' => '.js-remove-filter', // css class
'model' => $modelsTariffSlabs[0],
'formId' => 'dynamic-form',
'formFields' => [
'slab_name',
'slab_start',
'slab_end',
'rate'
],
]); ?>
<div class="container-items"><!-- widgetContainer -->
<?php foreach ($modelsTariffSlabs as $i => $modelTariffSlabs): ?>
<div class="item panel panel-default"><!-- widgetBody -->
<div class="panel-heading">
<h3 class="panel-title pull-left">Slab</h3>
<div class="pull-right">
<button type="button" id="addBtn" class="js-add-filter btn btn-success btn-xs"><i class="glyphicon glyphicon-plus"></i></button>
<button type="button" id="remBtn" class="js-remove-filter btn btn-danger btn-xs"><i class="glyphicon glyphicon-minus"></i></button>
</div>
<div class="clearfix"></div>
</div>
<div class="panel-body">
<?php
// necessary for update action.
if (! $modelTariffSlabs->isNewRecord) {
echo Html::activeHiddenInput($modelTariffSlabs, "[{$i}]id");
}
?>
<div class="row">
<div class="col-sm-3">
<?= $form->field($modelTariffSlabs, "[{$i}]slab_name")->textInput(['maxlength' => 10,"class"=>"form-control js-slab-name"]) ?>
</div>
<div class="col-sm-3">
<?= $form->field($modelTariffSlabs, "[{$i}]slab_start")->textInput(['maxlength' => 10,"class"=>"form-control js-slab-start"]) ?>
</div>
<div class="col-sm-3">
<?= $form->field($modelTariffSlabs, "[{$i}]slab_end")->textInput(['maxlength' => 10,"class"=>"form-control js-slab-end"]) ?>
</div>
<div class="col-sm-3">
<?= $form->field($modelTariffSlabs, "[{$i}]rate")->textInput(['maxlength' => 10]) ?>
</div>
</div><!-- .row -->
</div>
</div>
<?php endforeach; ?>
</div>
<?php DynamicFormWidget::end(); ?>
</div>
</div>
</div>
Now when I try to update it I am not data of the second model.
Update.php
<div class="mdc-tariff-update">
<?= $this->render('_form', [
'model' => $model,
'modelsTariffSlabs' => $modelsTariffSlabs
]) ?>
</div>
Update controller
public function actionUpdate($id)
{
$model = $this->findModel($id);
$modelsTariffSlabs = [new MdcTariffSlabs()];
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$oldIDs = ArrayHelper::map($modelsTariffSlabs, 'id', 'id');
$modelsTariffSlabs = CustomtariffModel::createMultiple(MdcTariffSlabs::classname(), $modelsTariffSlabs);
CustomtariffModel::loadMultiple($modelsTariffSlabs, Yii::$app->request->post());
$deletedIDs = array_diff($oldIDs, array_filter(ArrayHelper::map($modelsTariffSlabs, 'id', 'id')));
// validate all models
$valid = $model->validate();
$valid = CustomtariffModel::validateMultiple($modelsTariffSlabs) && $valid;
if ($valid) {
$transaction = \Yii::$app->db->beginTransaction();
try {
if ($flag = $model->save(false)) {
if (! empty($deletedIDs)) {
MdcTariffSlabs::deleteAll(['id' => $deletedIDs]);
}
foreach ($modelsTariffSlabs as $modelTariffSlabs) {
$modelTariffSlabs->t_id = $model->id;
if (! ($flag = $modelTariffSlabs->save(false))) {
$transaction->rollBack();
break;
}
}
}
if ($flag) {
$transaction->commit();
return $this->redirect(['view', 'id' => $model->id]);
}
} catch (Exception $e) {
$transaction->rollBack();
}
}
return $this->redirect(['view', 'id' => $model->id]);
}
return $this->render('update', [
'model' => $model,
'modelsTariffSlabs' => (empty($modelsTariffSlabs)) ? [new MdcTariffSlabs()] : $modelsTariffSlabs
]);
}
How can I show the values of all fields in my update form ?
Any help would be highly appreaciated.
Or you can call relation like (when you are on update mode):
$modelsTariffSlabs = $model->mdcTariffSlabs
If mdcTariffSlabs is name of relation - it returns array if related models.
Or if you don't have relation, you can create it in main model:
public function getMdcTariffSlabs()
{
return $this->hasMany(MdcTariffSlabs::className(), ['t_id' => 'id']);
}
I assume that the issue is in this line
$modelsTariffSlabs = [new MdcTariffSlabs()];
It always create an empty model. You have to get all the records that are saved. Below code should work
Assuming that $modelTariffSlabs->t_id = $model->id; // t_id is id of your main table
protected function findModelSlabs($id)
{
if (($model = MdcTariffSlabs::find()->where(['t_id'=>$id])->all()) !== null) {
return $model;
}
throw new NotFoundHttpException(Yii::t('app', 'The requested page does not exist.'));
}
And then change
$modelsTariffSlabs = [new MdcTariffSlabs()];
TO
$modelsTariffSlabs = $this->findModelSlabs($model->id);
I hope this will help
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.
I am working client side validation in yii2 but it is not working for me.
View File
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\captcha\Captcha;
?>
<ul class="breadcrumb">
<li>Home</li>
<li>Pages</li>
<li class="active">Login</li>
</ul>
<!-- BEGIN SIDEBAR & CONTENT -->
<div class="row margin-bottom-40">
<!-- BEGIN SIDEBAR -->
<!--<div class="sidebar col-md-3 col-sm-3">
<ul class="list-group margin-bottom-25 sidebar-menu">
<li class="list-group-item clearfix"><i class="fa fa-angle-right"></i> Register</li>
<li class="list-group-item clearfix"><i class="fa fa-angle-right"></i> Restore Password</li>
<li class="list-group-item clearfix"><i class="fa fa-angle-right"></i> My account</li>
<li class="list-group-item clearfix"><i class="fa fa-angle-right"></i> Address book</li>
<li class="list-group-item clearfix"><i class="fa fa-angle-right"></i> Wish list</li>
<li class="list-group-item clearfix"><i class="fa fa-angle-right"></i> Returns</li>
<li class="list-group-item clearfix"><i class="fa fa-angle-right"></i> Newsletter</li>
</ul>
</div>-->
<!-- END SIDEBAR -->
<!-- BEGIN CONTENT -->
<div class="col-md-9 col-sm-9">
<h1>Login</h1>
<div class="content-form-page">
<div class="row">
<div class="col-md-7 col-sm-7">
<?php $form = ActiveForm::begin(['id' => 'login-form','class' => 'form-horizontal form-without-legend']); ?>
<?php echo $form->errorSummary($model); ?>
<div class="form-group">
<label for="email" class="col-lg-4 control-label">Email <span class="require">*</span></label>
<div class="col-lg-8">
<?= $form->field($model, 'username',['template' => "{input}"])->textInput(array('placeholder' => 'Username','class'=>'form-control validate[required]')); ?>
</div>
</div>
<div class="form-group">
<label for="password" class="col-lg-4 control-label">Password <span class="require">*</span></label>
<div class="col-lg-8">
<?= $form->field($model, 'password',['template' => "{input}"])->passwordInput(array('class'=>'form-control validate[required]','placeholder'=>'Password')); ?>
<!--<input type="text" class="form-control" id="password">-->
</div>
</div>
<div class="row">
<div class="col-lg-8 col-md-offset-4 padding-left-0">
Forget Password?
</div>
</div>
<div class="row">
<div class="col-lg-8 col-md-offset-4 padding-left-0 padding-top-20">
<?= Html::submitButton('Login', ['class' => 'btn btn-primary']) ?>
<!--<button type="submit" class="btn btn-primary">Login</button>-->
</div>
</div>
<div class="row">
<div class="col-lg-8 col-md-offset-4 padding-left-0 padding-top-10 padding-right-30">
<hr>
<div class="login-socio">
<p class="text-muted">or login using:</p>
<ul class="social-icons">
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
</div>
</div>
<?php ActiveForm::end(); ?>
<!--</form>-->
</div>
<!--<div class="col-md-4 col-sm-4 pull-right">
<div class="form-info">
<h2><em>Important</em> Information</h2>
<p>Duis autem vel eum iriure at dolor vulputate velit esse vel molestie at dolore.</p>
<button type="button" class="btn btn-default">More details</button>
</div>
</div>-->
</div>
</div>
</div>
<!-- END CONTENT -->
</div>
<!-- END SIDEBAR & CONTENT -->
Colntroller File
<?php
namespace frontend\controllers;
use frontend\models\Users;
use backend\models\SmsData;
use backend\models\SmsDataSearch;
use Yii;
use frontend\models\LoginForm;
use frontend\models\PasswordResetRequestForm;
use frontend\models\ResetPasswordForm;
use frontend\models\SignupForm;
use frontend\models\ContactForm;
use yii\base\InvalidParamException;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use yii\data\ArrayDataProvider;
/**
* Site controller
*/
class SiteController extends Controller
{
/**
* #inheritdoc
*/
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'actions' => ['login','index', 'error','register'],
'allow' => true,
],
[
'actions' => ['logout','report','create','delete'],
'allow' => true,
'roles' => ['#'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
// 'logout' => ['post'],
],
],
];
}
/**
* #inheritdoc
*/
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
],
];
}
public function actionIndex()
{
return $this->render('index');
}
public function actionRegister()
{
$model = new Users();
if($model->load(Yii::$app->request->post()))
{
$model->status='0';
$model->is_delete='0';
$model->created_by='1';
$model->password=md5($_POST['Users']['password']);
$model->created_date=date('Y-m-d h:i:s');
$model->role_type='1';
$model->save();
Yii::$app->session->setFlash('success', 'You Have Successfully Register');
return $this->redirect(array('login'));
}
return $this->render('register',['model'=>$model]);
}
public function actionLogin()
{
if (!\Yii::$app->user->isGuest) {
return $this->goHome();
}
$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->login()) {
$data=Yii::$app->db->createCommand("select * from `users` where user_id = '".Yii::$app->user->getId()."'")->queryAll();
if($data[0]['role_type'] == '1')
{
Yii::$app->session->setFlash('success', 'You Have Successfully LogIn');
return $this->redirect(array('report'));
}
elseif($data[0]['role_type'] =='0')
{
Yii::$app->session->setFlash('success', 'You Have Successfully LogIn');
$url=Yii::$app->urlManager->createUrl('users/index');
return $this->redirect($url);
}
} else {
return $this->render('login',[
'model' => $model,
]);
}
}
public function actionReport()
{
$model= new SmsData();
if($model->load(Yii::$app->request->post()))
{
$fromdate=date('Y-m-d',strtotime($_POST['SmsData']['fromDate']));
$todate = date('Y-m-d',strtotime($_POST['SmsData']['toDate']));
$query="SELECT s.*,r.description as ratingtext FROM sms_data s
INNER JOIN users u ON u.unique_id = s.client_id
LEFT JOIN rating r ON r.rating = s.rating
WHERE u.user_id = '".Yii::$app->user->getId()."' AND s.message_id != '9999' AND date(s.created_date) >= '".$fromdate."' AND date(s.created_date) <= '".$todate."'";
$data=Yii::$app->db->createCommand($query)->queryAll();
$provider = new ArrayDataProvider([
'allModels' => $data,
'pagination' => [
'pageSize' => 10,
],
]);
$model->fromDate=$_POST['SmsData']['fromDate'];
$model->toDate=$_POST['SmsData']['toDate'];
return $this->render('report',['dataProvider'=>$provider,'model'=>$model]);
}
else
{
$query="SELECT s.*,r.description as ratingtext FROM sms_data s
INNER JOIN users u ON u.unique_id = s.client_id
LEFT JOIN rating r ON r.rating = s.rating
WHERE u.user_id = '".Yii::$app->user->getId()."' AND s.message_id != '9999' ";
$data=Yii::$app->db->createCommand($query)->queryAll();
$provider = new ArrayDataProvider([
'allModels' => $data,
'pagination' => [
'pageSize' => 10,
],
]);
return $this->render('report',['dataProvider'=>$provider,'model'=>$model]);
}
}
public function actionCreate()
{
$model = new SmsData();
if($model->load(Yii::$app->request->post())) {
$clientID=\frontend\models\Users::findOne(Yii::$app->user->getId());
$model->created_by = Yii::$app->user->getId();
$model->created_date= date('Y-m-d',strtotime($_POST['SmsData']['created_date']));
$model->rating = $_POST['SmsData']['rating'];
$model->text = $_POST['SmsData']['text'];
$model->message_id = 9999;
$model->client_id = $clientID->unique_id;
$model->save();
Yii::$app->session->setFlash('success', 'Data Inserted Successfully');
return $this->redirect(array('create'));
} else {
$query="SELECT s.*,r.description as ratingtext FROM sms_data s
INNER JOIN users u ON u.unique_id = s.client_id
LEFT JOIN rating r ON r.rating = s.rating
WHERE u.user_id = '".Yii::$app->user->getId()."' AND message_id = 9999
AND s.is_delete = 0 AND s.status = 1";
$data=Yii::$app->db->createCommand($query)->queryAll();
$provider = new ArrayDataProvider([
'allModels' => $data,
'pagination' => [
'pageSize' => 10,
],
]);
return $this->render('create',['model'=>$model,'dataProvider'=>$provider]);
}
}
public function actionDelete($id) {
$model = new SmsData();
$command = Yii::$app->db->createCommand('UPDATE sms_data SET is_delete = 1 WHERE sms_id='.$id);
$command->execute();
Yii::$app->session->setFlash('success', 'Deleted Successfully ');
return $this->redirect(array('create'));
}
public function actionLogout()
{
Yii::$app->user->logout();
Yii::$app->session->setFlash('success', 'You Have Successfully Logout');
return $this->goHome();
}
public function actionContact()
{
$model = new ContactForm();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
if ($model->sendEmail(Yii::$app->params['adminEmail'])) {
Yii::$app->session->setFlash('success', 'Thank you for contacting us. We will respond to you as soon as possible.');
} else {
Yii::$app->session->setFlash('error', 'There was an error sending email.');
}
return $this->refresh();
} else {
return $this->render('contact', [
'model' => $model,
]);
}
}
public function actionAbout()
{
return $this->render('about');
}
public function actionSignup()
{
$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,
]);
}
public function actionRequestPasswordReset()
{
$model = new PasswordResetRequestForm();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
if ($model->sendEmail()) {
Yii::$app->getSession()->setFlash('success', 'Check your email for further instructions.');
return $this->goHome();
} else {
Yii::$app->getSession()->setFlash('error', 'Sorry, we are unable to reset password for email provided.');
}
}
return $this->render('requestPasswordResetToken', [
'model' => $model,
]);
}
public function actionResetPassword($token)
{
try {
$model = new ResetPasswordForm($token);
} catch (InvalidParamException $e) {
throw new BadRequestHttpException($e->getMessage());
}
if ($model->load(Yii::$app->request->post()) && $model->validate() && $model->resetPassword()) {
Yii::$app->getSession()->setFlash('success', 'New password was saved.');
return $this->goHome();
}
return $this->render('resetPassword', [
'model' => $model,
]);
}
}
Model :
<?php
namespace frontend\models;
use frontend\models\Users;
use Yii;
use yii\base\Model;
/**
* Login form
*/
class LoginForm extends Model
{
public $username;
public $password;
public $rememberMe = true;
private $_user = false;
private $_id = false;
private $_name;
/**
* #inheritdoc
*/
public function rules()
{
return [
// username and password are both required
[['username', 'password'], 'required'],
// rememberMe must be a boolean value
['rememberMe', 'boolean'],
// password is validated by validatePassword()
['password', 'validatePassword'],
];
}
/**
* Validates the password.
* This method serves as the inline validation for password.
*/
public function validatePassword()
{
if (!$this->hasErrors()) {
$user = $this->getUser();
if (!$user || !$user->validatePassword($this->password)) {
$this->addError('password', 'Incorrect username or password.');
}
}
}
/**
* Logs in a user using the provided username and password.
*
* #return boolean whether the user is logged in successfully
*/
public function login()
{
if ($this->validate()) {
return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0);
} else {
return false;
}
}
/**
* Finds user by [[username]]
*
* #return User|null
*/
public function getUser()
{
if ($this->_user === false) {
$this->_user = Users::findByUsername($this->username);
}
return $this->_user;
}
public function getId()
{
if ($this->_id === false) {
$this->_id = $this->user_id;
}
return $this->_id;
}
}
What i need to do for client side validation ? Server side validation is working for me.
This is not a bug! You have to use ActiveForm::validate() for send errors back the browser as it formats the attributes same as ActiveForm renders
if (Yii::$app->request->isAjax && $model->load($_POST))
{
Yii::$app->response->format = 'json';
return \yii\widgets\ActiveForm::validate($model);
}
To enable AJAX validation for the whole form, you have to set the
yii\widgets\ActiveForm::enableAjaxValidation
property to be true and specify id to be a unique form identifier:
$form = ActiveForm::begin([
'id' => 'register-form',
'enableClientValidation' => true,
'options' => [
'validateOnSubmit' => true,
'class' => 'form'
],
])
;