Edit records CodeIgniter - mysql

I'm developing a basic crud application using PHP Codeigniter 3 with MySQL database.
I have done add and list method successfully but now I want to edit the record and have included an edit button in the records table in view. when I click on the button it will go to my edit record view but it shows some errors. I checked everything but I fail to resolve it.
This is my controller
<?php
class User extends CI_controller
{
public function index()
{
$this->load->model('User_model');
$users = $this->User_model->getUsers();
// print_r($users);
$data = array();
$data['users'] = $users;
$this->load->view('users/list',$data);
}
public function create()
{
//load model here
$this->load->model('User_model');
//load library
$this->load->library('form_validation');
$this->load->library('ckeditor');
$this->load->library('ckfinder');
//set rules
$this->form_validation->set_rules('name', 'Name', 'required');
$this->form_validation->set_rules('projectname', 'Projectname', 'required');
$this->form_validation->set_rules('projecttype', 'Projecttype', 'required');
$this->form_validation->set_rules('phone', 'Phone', 'required');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
$this->form_validation->set_rules('address', 'Address', 'required');
$this->form_validation->set_rules('projectdescription', 'Projectdescription', 'required');
// $this->form_validation->set_rules('termname', 'Termname', 'required');
// $this->form_validation->set_rules('termdescription', 'Termdescription', 'required');
$this->form_validation->set_rules('article_description', 'Article_description', 'required');
if ($this->form_validation->run() == true) {
// print_r($_POST);
// Array ( [name] => muhammad zawish [projectname] => test [projecttype] => Hardware [phone] => 03206270391 [email] => muhammadzawish#gmail.com [address] => Gondal Road, Sialkot, Punjab, Pakistan [projectdescription] => aaaaaaaaaa [termname] => aaaaaa [termdescription] => aaaaaaaa )
$name = $this->input->post('name');
$projectname = $this->input->post('projectname');
$projecttype = $this->input->post('projecttype');
$phone = $this->input->post('phone');
$email = $this->input->post('email');
$address = $this->input->post('address');
$projectdescription = $this->input->post('projectdescription');
// $termname = $this->input->post('termname');
// $termdescription = $this->input->post('termdescription');
$article_description = $this->input->post('article_description');
// $formData = array('name' => $name, 'projectname' => $projectname, 'projecttype' => $projecttype, 'phone' => $phone, 'email' => $email, 'address' => $address, 'projectdescription' => $projectdescription, 'termname' => $termname, 'termdescription' => $termdescription,);
$formData = array('name' => $name, 'projectname' => $projectname, 'projecttype' => $projecttype, 'phone' => $phone, 'email' => $email, 'address' => $address, 'projectdescription' => $projectdescription, 'article_description' => $article_description);
//ck editor files
$this->ckeditor->basePath = base_url() . 'asset/ckeditor/';
$this->ckeditor->config['toolbar'] = array(
array('Source', '-', 'Bold', 'Italic', 'Underline', '-', 'Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo', '-', 'NumberedList', 'BulletedList')
);
$this->ckeditor->config['language'] = 'it';
$this->ckeditor->config['width'] = '730px';
$this->ckeditor->config['height'] = '300px';
//Add Ckfinder to Ckeditor
$this->ckfinder->SetupCKEditor($this->ckeditor, '../../asset/ckfinder/');
$this->User_model->add_user($formData);
$this->session->set_flashdata('message', 'Record has been added successfully');
redirect(base_url('user/index'));
} else {
$this->load->view('users/create');
}
}
function edit($id){
$this->load->model('User_model');
$row = $this->User_model->getUser($id);
$data1 = array();
$data1['row'] = $row;
$this->load->view('users/edit', $data1);
}
}
this is my model
<?php
class User_model extends CI_Model{
public function add_user($formArray){
// $this->load->library('session');
$this->db->insert('users', $formArray);
}
//for view data fetch from database
public function getUsers(){
$users = $this->db->get('users')->result_array();
return $users;
}
//for edit record
function getUser($id){
$this->db->where('id', $id);
$row = $this->db->get('users')->row_array();
return $row;
}
}
?>
when I access my edit.php view
404 Page Not Found
The page you requested was not found.

Related

Laravel Slug Duplicate

when i trying to create post with the same slug it create post normally also in update the same problem
in this case i'v duplicate slugs for post
i search a lot about this problem but i didn't get any answers
any idea to solve this problem ?
Model
protected $fillable = [
'title', 'slug', 'body',
];
Controller
public function slug($string, $separator = '-') {
if (is_null($string)) {
return "";
}
$string = trim($string);
$string = mb_strtolower($string, "UTF-8");;
$string = preg_replace("/[^a-z0-9_\sءاأإآؤئبتثجحخدذرزسشصضطظعغفقكلمنهويةى]#u/", "", $string);
$string = preg_replace("/[\s-]+/", " ", $string);
$string = preg_replace("/[\s_]/", $separator, $string);
return $string;
}
public function store(Request $request)
{
$this->validate($request, array(
'title' => 'required|max:255',
'slug' => 'required|min:3|max:255|unique:posts',
'body' => 'required',
));
$post = new Post;
$post->title = $request->input('title');
$post->slug = $this->slug($request->slug);
$post->body = $request->input('body');
$post->save();
return redirect('admin/posts')->with('success', 'post is successfully saved');
}
public function update(Request $request, $id)
{
if ($request->isMethod('get'))
return view('content.admin.post.index', ['url' => Post::find($id)]);
else {
$rules = [
'title' => 'required|max:255',
'slug' => 'required|min:3|max:255|unique:posts,slug,{$post->slug},slug',
'body' => 'required',
];
$this->validate($request, $rules);
$post = Post::find($id);
$post->title = $request->title;
$post->slug = $this->slug($request->slug);
$post->body = $request->body;
$post->save();
return redirect('/admin/posts');
}
}
Preform your transformations on the slug field before passing it to the validator.
public function store(Request $request)
{
$request->slug = $this->slug($request->slug);
$this->validate($request, array(
'title' => 'required|max:255',
'slug' => 'required|min:3|max:255|unique:posts',
'body' => 'required',
));
$post = new Post;
$post->title = $request->input('title');
$post->slug = $request->input('slug');
$post->body = $request->input('body');
$post->save();
return redirect('admin/posts')->with('success', 'post is successfully saved');
}
Why not just set slug column as unique in database migration?
Like this:
$table->string('slug')->unique();

How to update multiple images in kartik Upload widget?

Here i can only able preview the images on update the model. I want to load the images properly so user can remove one r more file and update will work accordingly Here is my controller
public function actionUpdate($id)
{
$model = $this->findModel($id);
$session_data = \common\models\Customer::find()->where(['user_id' => $model->customer_user_id])->one();
$towing = \common\models\TowingRequest::find()->where(['id' => $model->towing_request_id])->one();
$images_old = \common\models\Images::find()->where(['=', 'vehicle_id', $model->id])->all();
$images = \common\models\Images::find()->where(['=', 'vehicle_id', $model->id])->one();
if (!$images) {
$images = new \common\models\Images();
}
if ($images_old) {
foreach ($images_old as $image) {
$baseurl = \Yii::$app->request->BaseUrl;
$image_url = $baseurl . '../backend/uploads/' . $image->thumbnail;
$all_images[] = Html::img("$image_url", ['class' => 'file-preview-image']);
}
} else {
$all_images = '';
}
$vehiclefeatures = new \common\models\VehicleFeatures();
$vehiclecondition = new \common\models\VehicleCondition();
$featuredata = \common\models\VehicleFeatures::find()->where(['=', 'vehicle_id', $model->id])->all();
$conditiondata = \common\models\VehicleCondition::find()->where(['=', 'vehicle_id', $model->id])->all();
$features = \common\models\Features::find()->all();
// $vf = Yii::$app->db->createCommand('SELECT * FROM features f left join vehicle_features vf on vf.features_id=f.id;')->queryAll();
$condition = \common\models\Condition::find()->all();
if ($model->load(Yii::$app->request->post()) && $towing->load(Yii::$app->request->post()) && $vehiclefeatures->load(Yii::$app->request->post()) && $vehiclecondition->load(Yii::$app->request->post()) && $images->load(Yii::$app->request->post())) {
$towing->save();
if (!$model->save()) {
$result = [];
// The code below comes from ActiveForm::validate(). We do not need to validate the model
// again, as it was already validated by save(). Just collect the messages.
foreach ($model->getErrors() as $attribute => $errors) {
$result[Html::getInputId($model, $attribute)] = $errors;
}
return $this->asJson(['validation' => $result]);
// Yii::$app->response->statusCode = 422;
}
//delet vehicle features and add new features
$command = Yii::$app->db->createCommand()
->delete('vehicle_features', 'vehicle_id = ' . $model->id)
->execute();
if ($vehiclefeatures->value) {
$vehicle_feature = \common\models\VehicleFeatures::inert_vehicle_feature($model, $vehiclefeatures->value);
}
//delete vehicle condition and add new features
$command = Yii::$app->db->createCommand()
->delete('vehicle_condition', 'vehicle_id = ' . $model->id)
->execute();
if ($vehiclecondition->value) {
$vehicle_condition = \common\models\VehicleCondition::inert_vehicle_condition($model, $vehiclecondition->value);
}
$photo = UploadedFile::getInstances($images, 'name');
if ($photo) {
$command = Yii::$app->db->createCommand()
->delete('images', 'vehicle_id = ' . $model->id)
->execute();
$save_images = \common\models\Images::save_container_images($model->id, $photo);
}
return $this->redirect(['view', 'id' => $model->id]);
}
return $this->render('update', [
'model' => $model,
'towing' => $towing,
'images' => $images,
'features' => $features,
'condition' => $condition,
'vehiclefeatures' => $vehiclefeatures,
'vehiclecondition' => $vehiclecondition,
'all_images' => $all_images,
'featuredata' => $featuredata,
'conditiondata' => $conditiondata,
'session_data' => $session_data,
]);
}
And here is my form where I have an issue on update the images. I know here I am just previewing the image by adding it in $all_images[] in the controller and initialPreview => $all_images in form to just show it on upload. Now I want exactly is to load the images properly so I can remove any image and can able to add more images. I just want here is how to load all the images properly in the upload widget on update After uploading it properly on update i can process it on the controller that i will delete and unlink all images and uploading the updating files
Here is my form with model images
<?=
$form->field($images, 'name[]')->widget(FileInput::classname(), [
'options' => ['accept' => 'image/*', 'multiple' => true],
'pluginOptions' => [
'previewFileType' => 'image',
'allowedFileExtensions' => ['jpg', 'gif', 'png', 'bmp','jpeg'],
'showUpload' => true,
'initialPreview' => $all_images,
'overwriteInitial' => true,
],
]);
?>
Yii2 Fileinput Upload Multiple Images, AJAX based Images Previews and Delete Images.
Please Refer For Multiple Images : https://stackoverflow.com/a/53832224/2218492
Table : products_images
id (Primary)
product_id (FK)
image
Table : product
id (Primary)
Name
ect
Here View Forms...
<?php
use yii\helpers\Html;
use yii\helpers\Url;
use kartik\widgets\FileInput;
?>
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
<?php echo '<label class="control-label">Choose an Image file(.png, .jpg)</label>'; ?>
<?php
//For Update Form : Fetch Uploaded Images and create Array to preview
$imagesList = array();
$imagesListId = array();
foreach ($model->productsImages as $img) {
$imagesList[] = Url::base(TRUE) . '/' . $img->image;
$imagesListId[]['key'] = $img->id;
}
?>
<?php
$empty_image = Url::base(TRUE) . "/uploads/image-upload-empty.png";
echo FileInput::widget([
'model' => $model,
'attribute' => 'products_image[]',
'name' => 'products_image[]',
'options' => ['multiple' => true, 'accept' => 'image/*', 'id' => 'products_image_id'],
'pluginOptions' => [
'initialPreview' => $imagesList,
'initialPreviewConfig' => $imagesListId,
'deleteUrl' => Url::to(['products/delete-image']),
'showCaption' => false,
'showRemove' => false,
'showUpload' => false,
'browseClass' => 'btn btn-primary col-lg-6 col-md-8 col-sm-8 col-xs-6',
'browseIcon' => '<i class="glyphicon glyphicon-plus-sign"></i> ',
'browseLabel' => 'Upload Image',
'allowedFileExtensions' => ['jpg', 'png'],
'previewFileType' => ['jpg', 'png'],
'initialPreviewAsData' => true,
'overwriteInitial' => false,
"uploadUrl" => Url::to(['products/upload']),
'uploadExtraData' => ['products_id' => $model->id, 'is_post' => $model->isNewRecord ? 'new' : 'update'],
'msgUploadBegin' => Yii::t('app', 'Please wait, system is uploading the files'),
//'msgUploadThreshold' => Yii::t('app', 'Please wait, system is uploading the files'),
//'msgUploadEnd' => Yii::t('app', 'Done'),
'msgFilesTooMany' => 'Maximum 15 products Images are allowed to be uploaded.',
'dropZoneClickTitle' => '',
"uploadAsync" => true,
"browseOnZoneClick" => true,
"dropZoneTitle" => '<img src=' . $empty_image . ' />',
'fileActionSettings' => [
'showZoom' => true,
'showRemove' => true,
'showUpload' => false,
],
'validateInitialCount' => true,
'maxFileCount' => 15,
'maxFileSize' => 5120, //5mb
'msgPlaceholder' => 'Select attachments',
],
'pluginEvents' => [
'filebatchselected' => 'function(event, files) {
$(this).fileinput("upload");
}',
/* 'uploadExtraData' => 'function() {
var out = {}, key, i = 0;
$(".kv-input:visible").each(function() {
$el = $(this);
key = $el.hasClass("kv-new") ? "new_" + i : "init_" + i;
out[key] = $el.val();
i++;
});
return out;
}', */
'filepredelete' => 'function(event, files) {
//var abort = true;
var index = uploaded_images.indexOf(files);
if (index !== -1) uploaded_images.splice(index, 1);
console.log(uploaded_images);
$("#productsmaster-images_array").val(uploaded_images);
//return abort;
}',
'fileuploaded' => 'function(event, data, previewId, index){
//alert( data.response.initialPreviewConfig[0].key);
uploaded_images.push(data.response.initialPreviewConfig[0].key);
console.log(uploaded_images);
$("#productsmaster-images_array").val(uploaded_images);
}',
/* 'filepreupload' => 'function(event, data, previewId, index){
var form = data.form, files = data.files, extra = data.extra,
response = data.response, reader = data.reader;
console.log(data.jqXHR);
console.log("File pre upload triggered");
}', */
],
]);
?>
<?= $form->field($model, 'images_array')->hiddenInput()->label(false) ?>
<?php echo '<br>' ?>
<?= Html::submitButton('<i class="glyphicon glyphicon-save-file"></i> UPLOAD FILE', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary'], ['students/create']) ?>
<?php ActiveForm::end(); ?>
<?php
$script = <<< JS
// initialize array
var uploaded_images = [];
JS;
$this->registerJs($script);
?>
Here Controller file:
<?php
/*
* Post products Images Upload Action Via FileInput Yii2 Extention.
*/
public function actionUpload() {
$files = array();
$allwoedFiles = ['jpg', 'png'];
if ($_POST['is_post'] == 'update') {
$products_id = $_POST['products_id'];
if ($_FILES) {
$tmpname = $_FILES['ProductsMaster']['tmp_name']['products_image'][0];
$fname = $_FILES['ProductsMaster']['name']['products_image'][0];
//Get the temp file path
$tmpFilePath = $tmpname;
//Make sure we have a filepath
if ($tmpFilePath != "") {
//save the filename
$shortname = $fname;
$size = $_FILES['ProductsMaster']['size']['products_image'][0];
$ext = substr(strrchr($shortname, '.'), 1);
if (in_array($ext, $allwoedFiles)) {
//save the url and the file
$newFileName = Yii::$app->security->generateRandomString(40) . "." . $ext;
//Upload the file into the temp dir
if (move_uploaded_file($tmpFilePath, 'uploads/products/' . $newFileName)) {
$productsImages = new productsImages();
$productsImages->products_id = $products_id;
$productsImages->image_for = 'products';
$productsImages->image = 'uploads/products/' . $newFileName;
$productsImages->created_at = time();
$productsImages->save();
$files['initialPreview'] = Url::base(TRUE) . '/uploads/products/' . $newFileName;
$files['initialPreviewAsData'] = true;
$files['initialPreviewConfig'][]['key'] = $productsImages->id;
return json_encode($files);
}
}
}
} /* else {
return json_encode(['error' => 'No files found for pload.']);
} */
return json_encode($files);
} else {
if (isset($_POST)) {
if ($_FILES) {
$files = ProductsMaster::SaveTempAttachments($_FILES);
return json_encode($files);
$result = ['files' => $files];
Yii::$app->response->format = trim(Response::FORMAT_JSON);
return $result;
} /* else {
echo json_encode(['error' => 'No files found for pload.']);
} */
}
}
}
/**
* Uploaded Images Delete Action on Update Forms Action
* #return boolean
*/
public function actionDeleteImage() {
$key = $_POST['key'];
if (is_numeric($key)) {
$products_image = ProductsImages::find()->where(['id' => $key])->one();
unlink(Yii::getAlias('#webroot') . '/' . $products_image->image);
$products_image->delete();
return true;
} else {
unlink(Yii::getAlias('#webroot') . '/uploads/products/temp/' . $key);
return true;
}
}
/**
** Create Products
**/
public function actionCreate() {
//Products Images
// temp store image moved and save to database.. with generated forms..
if (count($model->images_array) > 0) {
$images_array = explode(',', $model->images_array);
if (!empty($images_array) && $model->images_array != '') {
foreach ($images_array as $image) {
$file = Yii::$app->basePath . '/uploads/products/temp/' . $image;
$rename_file = Yii::$app->basePath . '/uploads/products/' . $image;
rename($file, $rename_file);
$productsImages = new productsImages();
$productsImages->products_id = $model->id;
$productsImages->image_for = 'products';
$productsImages->image = 'uploads/products/' . $image;
$productsImages->created_at = time();
$productsImages->save();
}
}
}
}
?>
Here Model
I added a load function to the attachment model.
<?php
/*
* Save Temp Images
*/
public static function SaveTempAttachments($attachments) {
$files = "";
$allwoedFiles = ['jpg', 'png'];
if ($_FILES) {
$tmpname = $_FILES['ProductsMaster']['tmp_name']['products_image'];
$fname = $_FILES['ProductsMaster']['name']['products_image'];
if (!empty($attachments)) {
if (count($fname) > 0) {
//Loop through each file
for ($i = 0; $i < count($fname); $i++) {
//Get the temp file path
$tmpFilePath = $tmpname[$i];
//Make sure we have a filepath
if ($tmpFilePath != "") {
//save the filename
$shortname = $fname[$i];
$size = $attachments['ProductsMaster']['size']['products_image'][$i];
$ext = substr(strrchr($shortname, '.'), 1);
if (in_array($ext, $allwoedFiles)) {
//save the url and the file
$newFileName = Yii::$app->security->generateRandomString(40) . "." . $ext;
//Upload the file into the temp dir
if (move_uploaded_file($tmpFilePath, 'uploads/products/temp/' . $newFileName)) {
$files['initialPreview'] = Url::base(TRUE) . '/uploads/products/temp/' . $newFileName;
$files['initialPreviewAsData'] = true;
// $files['uploadExtraData'][]['is_post'] = 'new';
$files['initialPreviewConfig'][]['key'] = $newFileName;
}
}
}
}
}
}
}
return $files;
}
?>

Selected Value is not showing in Kartik Select2 multiple select

This is my view file:
<?php
$data = array();
echo '<label class="control-label">Attribute Group Name</label>';
echo Select2::widget([
'name' => 'attribute_grp_name',
'data' => $attribute_group_name, // initial value
'options' => ['placeholder' => 'Please Enter Attribute Group Name', 'multiple' => true],
'pluginOptions' => [
'attribute_grp_name' => true,
'maximumInputLength' => 100,
],
]);
?>
In my view here selected data is not showing.
This is my controller for create and update function:
public function actionCreate()
{
$model = new AttributeSet();
$attribute_group = AttributeGroupLang::find()->select('*')->all();
$attribute_group_name = ArrayHelper::map($attribute_group, 'id_attribute_group', 'name');
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$post_array = Yii::$app->request->post();
foreach ($post_array['attribute_grp_name'] as $key => $value) {
$attribute_set_group_combination = new AttributeSetGroupCombination();
$attribute_set_group_combination->id_attribute_set = $model->id_attribute_set;
$attribute_set_group_combination->id_attribute_group = $value;
$attribute_set_group_combination->save(false);
}
return $this->redirect(['view', 'id' => $model->id_attribute_set]);
} else {
return $this->render('create', [
'model' => $model,
'attribute_group_name' => $attribute_group_name,
]);
}
}
This is update function:
public function actionUpdate($id)
{
$model = $this->findModel($id);
$attribute_set_group_combination = AttributeSetGroupCombination::find()->where(['id_attribute_set' => $id])->all();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$post_array = Yii::$app->request->post();
if(!empty($post_array['attribute_grp_name'])){
AttributeSetGroupCombination::deleteAll('id_attribute_set = '.$id);
foreach ($post_array['attribute_grp_name'] as $key => $value) {
$attribute_set_group_combination = new AttributeSetGroupCombination();
$attribute_set_group_combination->id_attribute_set = $model->id_attribute_set;
$attribute_set_group_combination->id_attribute_group = $value;
$attribute_set_group_combination->save(false);
}
}
return $this->redirect(['view', 'id' => $model->id_attribute_set]);
} else {
return $this->render('update', [
'model' => $model,
'attribute_set_group_combination' => $attribute_set_group_combination,
'attribute_group_name' => $this->getExistAttrSet($id),
]);
}
}
public function getExistAttrSet($id){
$query = new Query;
$query->select(['attribute_group_lang.name AS attribute_group_name','attribute_group_lang.id_attribute_group'])
->from('attribute_set_group_combination')
->join('LEFT OUTER JOIN', 'attribute_set', 'attribute_set.id_attribute_set =attribute_set_group_combination.id_attribute_set')
->join('LEFT OUTER JOIN', 'attribute_group_lang', 'attribute_group_lang.id_attribute_group =attribute_set_group_combination.id_attribute_group')
->where('attribute_set.id_attribute_set='.$id)
->all();
$command = $query->createCommand();
$model = $command->queryAll();
$data = array();
foreach ($model as $attrsetlist[]) {
$data = ArrayHelper::map($attrsetlist, 'id_attribute_group', 'attribute_group_name');
}
return $data;
}
Can anyone help me that how can i show the selected value in the multiple select field.
You just need to pass in model value:
<?php
echo kartik\select2\Select2::widget([
'name' => 'some_field_name',
// ----------------------
'value' => 'a',
//'value' => ['a', 'b'],
//'value' => $model->some_value,
// ----------------------
'data' => ['a'=>'a', 'b'=>'b', 'c'=>'c'],
'options' => ['placeholder' => 'Select menu items ...', ],
]);
?>

cant import data csv to database in yii2

I am very new to web development.
I'm newbie in here, my first question in stackoverflow..
i am confused what error on code, Code will be store data array csv to a database,
sorry my bad english.
Controller
public function actionUpload()
{
$model = new Skt();
//error_reporting(E_ALL);
//ini_set('display_error', 1);
if ($model->load(Yii::$app->request->post())) {
$file = UploadedFile::getInstance($model, 'file');
$filename = 'Data.' . $file->extension;
$upload = $file->saveAs('uploads/' . $filename);
if ($upload) {
define('CSV_PATH', 'uploads/');
$csv_file = CSV_PATH . $filename;
$filecsv = file($csv_file);
foreach ($filecsv as $data) {
$modelnew = new Skt();
$hasil = explode(",", $data);
$no_surat= $hasil[0];
$posisi= $hasil[1];
$nama= $hasil[2];
$tgl_permanen= $hasil[3];
$grade= $hasil[4];
$tgl_surat= $hasil[5];
$from_date = $hasil[6];
$to_date = $hasil[7];
$modelnew->no_surat = $no_surat;
$modelnew->posisi = $posisi;
$modelnew->nama = $nama;
$modelnew->tgl_permanen = $tgl_permanen;
$modelnew->grade = $grade;
$modelnew->tgl_surat = $tgl_surat;
$modelnew->from_date = $from_date;
$modelnew->to_date = $to_date;
$modelnew->save();
//print_r($modelnew->validate());exit;
}
unlink('uploads/'.$filename);
return $this->redirect(['site/index']);
}
}else{
return $this->render('upload',['model'=>$model]);
}
return $this->redirect(['upload']);
}
Model
class Skt extends \yii\db\ActiveRecord
{
public static function tableName()
{
return 'skt';
}
public $file;
public function rules()
{
return [
[['file'], 'required'],
[['file'], 'file', 'extensions' => 'csv', 'maxSize' => 1024*1024*5],
[['no_surat'], 'required'],
[['tgl_surat', 'from_date', 'to_date'], 'string'],
[['no_surat', 'posisi', 'nama', 'tgl_permanen', 'grade'], 'string', 'max' => 255],
];
}
public function attributeLabels()
{
return [
'no_surat' => 'No Surat',
'posisi' => 'Posisi',
'nama' => 'Nama',
'tgl_permanen' => 'Tgl Permanen',
'grade' => 'Grade',
'tgl_surat' => 'Tgl Surat',
'from_date' => 'From Date',
'to_date' => 'To Date',
'file' => 'Select File'
];
}
}
thanks for helping..
change your code to the following to output the errors which could happen when you try to save. Errors could occur depending on your model rules.
if (!$modelnew->save()) {
var_dump($modelnew->getErrors());
}
getErrors() from Api
A better approach is to use exceptions to throw and catch errors on your import. Depends if you want to skip csv lines on errors or not.
finally it working with change this $hasil = explode(";", $data);

PhalconPHP & ACL: guests were able to access restricted content

I don't want to allow guest phones/new. They should have access for phones/index and one other thing only. But guests were able to access all actions of Phones controller. I need your help to find out the mistake I did.
Here is the ACL plugin
<?php
use Phalcon\Acl;
use Phalcon\Acl\Role;
use Phalcon\Acl\Resource;
use Phalcon\Events\Event;
use Phalcon\Mvc\User\Plugin;
use Phalcon\Mvc\Dispatcher;
use Phalcon\Acl\Adapter\Memory as AclList;
/**
* SecurityPlugin
*
* This is the security plugin which controls that users only have access to the modules they're assigned to
*/
class SecurityPlugin extends Plugin
{
/**
* Returns an existing or new access control list
*
* #returns AclList
*/
public function getAcl()
{
if (!isset($this->persistent->acl)) {
$acl = new AclList();
$acl->setDefaultAction(Acl::DENY);
//Register roles
$roles = array(
'admin' => new Role('Admin'),
'editor' => new Role('Editor'),
'guests' => new Role('Guests')
);
foreach ($roles as $role) {
$acl->addRole($role);
}
//Admin area resources
$adminResources = array(
'dashboard' => array('index'),
'phones' => array('index', 'all', 'new', 'edit', 'save', 'create', 'delete', 'search'),
'users' => array('index', 'search', 'new', 'edit', 'save', 'create', 'delete', 'saveProfile', 'profile'),
);
foreach ($adminResources as $resource => $actions) {
$acl->addResource(new Resource($resource), $actions);
}
//Editor area resources
$editorResources = array(
'dashboard' => array('index'),
'phones' => array('index', 'all', 'new', 'edit', 'save', 'create', 'search'),
'users' => array('saveProfile', 'profile'),
);
foreach ($editorResources as $resource => $actions) {
$acl->addResource(new Resource($resource), $actions);
}
//Public area resources
$publicResources = array(
'index' => array('index'),
'about' => array('index'),
'login' => array('index', 'check', 'logout'),
'errors' => array('show404', 'show500'),
'contact' => array('index', 'send'),
'phones' => array('index', 'search'),
);
foreach ($publicResources as $resource => $actions) {
$acl->addResource(new Resource($resource), $actions);
}
//Grant access to public areas to both users and guests
foreach ($roles as $role) {
foreach ($publicResources as $resource => $actions) {
$acl->allow($role->getName(), $resource, '*');
}
}
//Grant access to private area to role Admin
foreach ($adminResources as $resource => $actions) {
foreach ($actions as $action) {
$acl->allow('Admin', $resource, $action);
}
}
//Grant access to private area to role Admin
foreach ($editorResources as $resource => $actions) {
foreach ($actions as $action) {
$acl->allow('Editor', $resource, $action);
}
}
//The acl is stored in session, APC would be useful here too
$this->persistent->acl = $acl;
}
return $this->persistent->acl;
}
/*
* This action is executed before execute any action in the application
*
* #param Event $event
* #param Dispatcher $dispatcher
*/
public function beforeDispatch(Event $event, Dispatcher $dispatcher)
{
$auth = $this->session->get('auth');
if (!$auth) {
$role = 'Guests';
} else {
switch ($auth['role']) {
case 1:
$role = "Admin";
break;
case 2:
$role = "Editor";
break;
default:
$role = "Guests";
break;
}
}
$controller = $dispatcher->getControllerName();
$action = $dispatcher->getActionName();
$acl = $this->getAcl();
$allowed = $acl->isAllowed($role, $controller, $action);
if ($allowed != Acl::ALLOW) {
$dispatcher->forward(array(
'controller' => 'errors',
'action' => 'show401'
));
return false;
}
}
}
I fixed the issue by changing wildcard to specific action. I actually copied code from invo and overlooked the thing.
//Grant access to public areas to both users and guests
foreach ($roles as $role) {
foreach ($publicResources as $resource => $actions) {
$acl->allow($role->getName(), $resource, $actions);
}
}