Created a simple miniCMS in a portal for content creation. The issue at first was in TinyMCE stripping of id attribute from html tag I've resolved that using valid_elements now the request is being sent to Model as is with no issues however in the Model level it's stripping the id again
Example
<div id="agreement">text ......... </div>
Being Saved in model as
<div>text ......... </div>
The controller code:
public function frontendContent(Request $request, $key)
{
$purifier = new \HTMLPurifier();
$valInputs = $request->except('_token', 'image_input', 'key', 'status', 'type');
foreach ($valInputs as $keyName => $input) {
if (gettype($input) == 'array') {
$inputContentValue[$keyName] = $input;
continue;
}
$inputContentValue[$keyName] = $purifier->purify($input);
}
$type = $request->type;
if (!$type) {
abort(404);
}
$imgJson = #getPageSections()->$key->$type->images;
$validation_rule = [];
$validation_message = [];
foreach ($request->except('_token', 'video') as $input_field => $val) {
if ($input_field == 'has_image' && $imgJson) {
foreach ($imgJson as $imgValKey => $imgJsonVal) {
$validation_rule['image_input.'.$imgValKey] = ['nullable','image','mimes:jpeg,jpg,png,svg'];
$validation_message['image_input.'.$imgValKey.'.image'] = inputTitle($imgValKey).' must be an image';
$validation_message['image_input.'.$imgValKey.'.mimes'] = inputTitle($imgValKey).' file type not supported';
}
continue;
}elseif($input_field == 'seo_image'){
$validation_rule['image_input'] = ['nullable', 'image', new FileTypeValidate(['jpeg', 'jpg', 'png'])];
continue;
}
$validation_rule[$input_field] = 'required';
}
$request->validate($validation_rule, $validation_message, ['image_input' => 'image']);
if ($request->id) {
$content = Frontend::findOrFail($request->id);
} else {
$content = Frontend::where('data_keys', $key . '.' . $request->type)->first();
if (!$content || $request->type == 'element') {
$content = Frontend::create(['data_keys' => $key . '.' . $request->type]);
}
}
if ($type == 'data') {
$inputContentValue['image'] = #$content->data_values->image;
if ($request->hasFile('image_input')) {
try {
$inputContentValue['image'] = uploadImage($request->image_input,imagePath()['seo']['path'], imagePath()['seo']['size'], #$content->data_values->image);
} catch (\Exception $exp) {
$notify[] = ['error', 'Could not upload the Image.'];
return back()->withNotify($notify);
}
}
}else{
if ($imgJson) {
foreach ($imgJson as $imgKey => $imgValue) {
$imgData = #$request->image_input[$imgKey];
if (is_file($imgData)) {
try {
$inputContentValue[$imgKey] = $this->storeImage($imgJson,$type,$key,$imgData,$imgKey,#$content->data_values->$imgKey);
} catch (\Exception $exp) {
$notify[] = ['error', 'Could not upload the Image.'];
return back()->withNotify($notify);
}
} else if (isset($content->data_values->$imgKey)) {
$inputContentValue[$imgKey] = $content->data_values->$imgKey;
}
}
}
}
$content->update(['data_values' => $inputContentValue]);
$notify[] = ['success', 'Content has been updated.'];
return back()->withNotify($notify);
}
When I dd the request
as dd($request) I can see the html tag in full
<div id="agreement">text ......... </div>
But when I dd the content
as dd($content) I can see that the id attribute is stripped
<div>text ......... </div>
The model part
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Frontend extends Model
{
protected $guarded = ['id'];
protected $table = "frontends";
protected $casts = [
'data_values' => 'object'
];
public static function scopeGetContent($data_keys)
{
return Frontend::where('data_keys', $data_keys);
}
}
Kindly asking for help, thank you!
While checking the forum here at SOF I found a solution with a remark from #FarhanIbnWahid thanks to him.
$config = HTMLPurifier_Config::createDefault();
$config->set('Attr.EnableID', true);
$purifier = new \HTMLPurifier($config);
This will resolve the issue.
Related
Hi i'm using a form to create a new product and send the info to the controller and save it into the database, the form does send the data because I can see it when I do a Log inside the controller and the info is there, I don't understand why it's not being saved into the database?
In this example the data I've added to the product is minimal but there could be more like prices and countries, along with the stuff inside the store function like tags and sizes.
This is the complete store function in the controller
public function store(ProductSaveRequest $request)
{
DB::beginTransaction();
$product = new Product;
$product->fill($request->all());
$file = $request->file('image');
if ($file) {
$file = $request->file('image');
$filename = Uuid::uuid() . '.' . $file->getClientOriginalExtension();
$file->move('img/products', $filename);
$product->image = 'img/products/' . $filename;
}
$product->save();
Log::info($product);
if (!empty($request->get('prices'))) {
$prices = array_map(function ($item) use ($product) {
$item['product_id'] = $product->id;
return $item;
}, $request->get('prices'));
CountryProduct::insert($prices);
}
if ($request->has('tags')) {
$product->tags()->sync($request->get('tags'));
}
if ($request->has('sizes')) {
$product->sizes()->sync($request->get('sizes'));
}
if ($request->has('categories')) {
$productCategories = [];
foreach ($request->get('categories') as $item) {
if (key_exists('category_name', $item)) {
$category = Category::where('name', $item['category_name'])
->first();
} else if (key_exists('category_id', $item)) {
$category = Category::findOrFail($item['category_id']);
}
if (empty($category)) {
$category = new Category;
$category->name = $item['category_name'];
}
$category->type = $item['type'];
$category->save();
if (!empty($item['fields'])) {
foreach ($item['fields'] as $fieldItem) {
if (key_exists('field_name', $fieldItem)) {
$field = Field::where('name', $fieldItem['field_name'])
->first();
} else if (key_exists('field_id', $fieldItem)) {
$field = Field::findOrFail($fieldItem['field_id']);
}
if (empty($field)) {
$field = new Field;
$field->name = $fieldItem['field_name'];
$field->category_id = $category->id;
}
$field->save();
$productCategories[] = [
"field_id" => $field->id,
"category_id" => $category->id,
"product_id" => $product->id,
"value" => $fieldItem['value']
];
}
}
if (count($productCategories) > 0) {
ProductField::insert($productCategories);
}
ExportationFactor::insert($product);
}
$product->save();
DB::commit();
return $product;
}
}
This is the Log.info
local.INFO: {"discount":"1","code":"123","sku":"123","description_spanish":"123","description_english":"123","brand_id":"2","id":591}
The current output is that I get a success action and it says it has been successfully added but when I go look it's not there.
Put your commit method outside the last if condition.
public function store(ProductSaveRequest $request)
{
DB::beginTransaction();
$product = new Product;
$product->fill($request->all());
$file = $request->file('image');
if ($file) {
$file = $request->file('image');
$filename = Uuid::uuid() . '.' . $file->getClientOriginalExtension();
$file->move('img/products', $filename);
$product->image = 'img/products/' . $filename;
}
$product->save();
Log::info($product);
if (!empty($request->get('prices'))) {
$prices = array_map(function ($item) use ($product) {
$item['product_id'] = $product->id;
return $item;
}, $request->get('prices'));
CountryProduct::insert($prices);
}
if ($request->has('tags')) {
$product->tags()->sync($request->get('tags'));
}
if ($request->has('sizes')) {
$product->sizes()->sync($request->get('sizes'));
}
if ($request->has('categories')) {
$productCategories = [];
foreach ($request->get('categories') as $item) {
if (key_exists('category_name', $item)) {
$category = Category::where('name', $item['category_name'])
->first();
} else if (key_exists('category_id', $item)) {
$category = Category::findOrFail($item['category_id']);
}
if (empty($category)) {
$category = new Category;
$category->name = $item['category_name'];
}
$category->type = $item['type'];
$category->save();
if (!empty($item['fields'])) {
foreach ($item['fields'] as $fieldItem) {
if (key_exists('field_name', $fieldItem)) {
$field = Field::where('name', $fieldItem['field_name'])
->first();
} else if (key_exists('field_id', $fieldItem)) {
$field = Field::findOrFail($fieldItem['field_id']);
}
if (empty($field)) {
$field = new Field;
$field->name = $fieldItem['field_name'];
$field->category_id = $category->id;
}
$field->save();
$productCategories[] = [
"field_id" => $field->id,
"category_id" => $category->id,
"product_id" => $product->id,
"value" => $fieldItem['value']
];
}
}
if (count($productCategories) > 0) {
ProductField::insert($productCategories);
}
ExportationFactor::insert($product);
}
}
DB::commit();
return $product;
}
In the first line of the method, you begin a database transaction.
But you only commit the database transaction
if ($request->has('categories')) {
One of my project needs code indentation, it has many of controller files looking like below code.
so basically I want to do is format code which should be done automatically without changing each file manually.
Controller code
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\URL;
use File;
use Html;
use DB;
use Illuminate\Validation\Rule;
use Illuminate\Support\Str;
use Validator;
use Datatables;
use AppHelper;
use LaraCore;
use Image;
use App\Models\Customer;
use App\Models\_List;
use Carbon;
class CustomerController extends Controller
{
public function validator(array $data, $id = NULL)
{
$email_Rules = explode(',',"required,email,unique");
$email_Rules['unique'] = Rule::unique('customers')->ignore($id);
if(($key = array_search('unique',$email_Rules)) !== false) {
unset($email_Rules[$key]);
}
return Validator::make($data, [
'secret_key' => 'required|min:6|max:10',
'email' => $email_Rules,
'first_name' => 'required|alpha_num',
'city' => 'required',
]
);
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return view('panel.customers.index');
}
public function create()
{
$data = array();
$EmployeeType = _List::where('list_name','=','EmployeeType')->pluck('item_name','id')->all();
$data['EmployeeType'] = $EmployeeType;
$Category = _List::where('list_name','=','Category')->pluck('item_name','id')->all();
$data['Category'] = $Category;
return view('panel.customers.create',$data);
}
public function edit($id,Request $request)
{
$data = array();
$Dates = array();
$customers = Customer::findOrFail($id);
$data['customers'] = $customers;
$EmployeeType = _List::where('list_name','=','EmployeeType')->pluck('item_name','id')->all();
$data['EmployeeType'] = $EmployeeType;
$preference= explode(',',$customers->preference);
$customers->preference = $preference;
$Category = _List::where('list_name','=','Category')->pluck('item_name','id')->all();
$data['Category'] = $Category;
if($customers->ready!=''){
$ready= explode(',',$customers->ready);
$customers->ready = $ready;
}
if($customers->approved!=''){
$approved= explode(',',$customers->approved);
$customers->approved = $approved;
}
$Name = explode(',','start_date,end_date');
$Dates[0] = new Carbon($customers->$Name[0]);
$Dates[1] = new Carbon($customers->$Name[1]);
$data['start_dateend_date'] = $Dates[0]->format('m/d/Y').' - '.$Dates[1]->format('m/d/Y') ;
return view('panel.customers.create',$data);
}
public function store(Request $request,$id="")
{
$this->validator($request->all(),$request->id)->validate();
if($request->id == null || $request->id == ""){
$inputs = $request->all();
if($request->has('secret_key')){
$secret_key = bcrypt($request->secret_key);
$inputs['secret_key'] = $secret_key;
}
if($request->has('preference')){
$preference = implode(',',$request->preference);
$inputs['preference'] = $preference;
}
if($request->has('ready')){
$ready = implode(',',$request->ready);
$inputs['ready'] = $ready;
}else{
$inputs['ready'] = "";
}
if($request->has('start_date,end_date')){
$Dates = explode('-',$request->input('start_date,end_date'));
$Name = explode(',','start_date,end_date');
$inputs[''.$Name[0]] = $Dates[0];
$Dates[0] = new Carbon($Dates[0]);
$Dates[1] = new Carbon($Dates[1]);
$inputs[''.$Name[0]] = $Dates[0]->format('Y-m-d');
$inputs[''.$Name[1]] = $Dates[1]->format('Y-m-d');
//dd($inputs);
}
foreach($request->files as $key_file => $value_file){
$nameArr = explode(',',$key_file);
$file = $value_file;
$destinationPath = 'public/uploads/customers';
\File::makeDirectory($destinationPath,0775,true,true);
$name = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
$encrypted_name = md5(uniqid().time()).".".$extension;
$file->move($destinationPath,$encrypted_name);
$inputs[''.$nameArr[0]] = $name;
$inputs[''.$nameArr[1]] = $encrypted_name;
}
Customer::create($inputs);
return redirect()->route('customers.index')->with('success',"Customer Saved successfully");
}
else{
$customers = Customer::where(['id'=>$request->input('id')])->first();
$inputs = $request->except('_token');
if($request->has('secret_key')){
$secret_key = bcrypt($request->secret_key);
$inputs['secret_key'] = $secret_key;
}
if($request->has('preference')){
$preference = implode(',',$request->preference);
$inputs['preference'] = $preference;
}
if($request->has('ready')){
$ready = implode(',',$request->ready);
$inputs['ready'] = $ready;
}
if($request->has('start_date,end_date')){
$Dates = explode('-',$request->input('start_date,end_date'));
$Name = explode(',','start_date,end_date');
$inputs[''.$Name[0]] = $Dates[0];
$Dates[0] = new Carbon($Dates[0]);
$Dates[1] = new Carbon($Dates[1]);
$inputs[''.$Name[0]] = $Dates[0]->format('Y-m-d');
$inputs[''.$Name[1]] = $Dates[1]->format('Y-m-d');
//dd($inputs);
}
foreach($request->files as $key_file => $value_file){
$destinationPath = 'public/uploads/customers';
\File::makeDirectory($destinationPath,0775,true,true);
$nameArr = explode(',',$key_file);
$OldFile = $customers->$nameArr[1];
if($OldFile!=''){
$OldFile = $destinationPath.'/'.$OldFile;
if(\File::exists($OldFile)){
\File::delete($OldFile);
}
}
$file = $value_file;
$name = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
$encrypted_name = md5(uniqid().time()).".".$extension;
$file->move($destinationPath,$encrypted_name);
$inputs[''.$nameArr[0]] = $name;
$inputs[''.$nameArr[1]] = $encrypted_name;
$SavedFile = $destinationPath.$encrypted_name;
}
$customers->update($inputs);
return redirect()->route('customers.index')->with('success',"Customer Saved successfully");
}
}
public function listCustomer(Request $request)
{
$customers = Customer::all();
$datatables = Datatables::of($customers)
->addColumn('actions', function($customers){
$html = '';
$html .= '<i class="fa fa-edit"></i>';
$html .= '<i class="fa fa-trash"></i>';
return $html;
})
->setRowId('id');
return $datatables->make();
}
public function destroy($id)
{
$customer = Customer::find($id);
$customer->delete();
return response()->json(array(
"status" => "success",
"message" => "Customer Deleted Successfully",
));
}
}
Maybe you could call a php beautifier on the file you created ? http://pear.php.net/package/PHP_Beautifier/
Note : you can call a command with exec
exec("php_beautifier $filename $filename");
It is hard to tell without more of your source but I imagine expressions like explode(',', $value["dbfield"] )[0] are catching some sort of tab character or importing blank fields that are somehow translated into spaces or tabs and causing the unwanted spacing.
#foreach($fields as $key => $value)
#if($value['dbfield'] == '')
#continue
#endif
#if($value['validation'])
#if(in_array('unique',explode(',',$value['validation'])))
'{{$value['dbfield']}}' => ${{$value['dbfield']}}_rules,
#else
#if(strpos($value["dbfield"],","))
'{{ explode(',', $value["dbfield"] )[0] }}' => '{{str_replace(',', '|', $value['validation'])}}',
#else
'{{$value['dbfield']}}' => '{{str_replace(',', '|', $value['validation'])}}',
#endif
#endif
#endif
#endforeach
I am trying to port my web app from laravel 4 to 5 but I am having issues in that one of my model classes is not found.
I have tried to utilize namespacing and have the following my Models which are located locally C:\xampp\htdocs\awsconfig\app\Models
the file which the error appears in looks like
<?php
use App\Models\SecurityGroup;
function from_camel_case($input)
{
preg_match_all('!([A-Z][A-Z0-9]*(?=$|[A-Z][a-z0-9])|[A-Za-z][a-z0-9]+)!', $input, $matches);
$ret = $matches[0];
foreach ($ret as &$match)
{
$match = $match == strtoupper($match) ? strtolower($match) : lcfirst($match);
}
return implode('_', $ret);
}
$resource_types = array();
$resource_types['AWS::EC2::Instance'] = 'EC2Instance';
$resource_types['AWS::EC2::NetworkInterface'] = 'EC2NetworkInterface';
$resource_types['AWS::EC2::VPC'] = 'VPC';
$resource_types['AWS::EC2::Volume'] = 'Volume';
$resource_types['AWS::EC2::SecurityGroup'] = 'SecurityGroup';
$resource_types['AWS::EC2::Subnet'] = 'Subnet';
$resource_types['AWS::EC2::RouteTable'] = 'RouteTable';
$resource_types['AWS::EC2::EIP'] = 'EIP';
$resource_types['AWS::EC2::NetworkAcl'] = 'NetworkAcl';
$resource_types['AWS::EC2::InternetGateway'] = 'InternetGateway';
$accounts = DB::table('aws_account')->get();
$account_list = array();
foreach(glob('../resources/sns messages/*.json') as $filename)
{
//echo $filename;
$data = file_get_contents($filename);
if($data!=null)
{
$decoded=json_decode($data,true);
if(isset($decoded["Message"]))
{
//echo "found message<br>";
$message= json_decode($decoded["Message"]);
if(isset($message->configurationItem))
{
// echo"found cfi<br>";
$insert_array = array();
$cfi = $message->configurationItem;
switch ($cfi->configurationItemStatus)
{
case "ResourceDiscovered":
//echo"found Resource Discovered<br>";
if (array_key_exists($cfi->resourceType,$resource_types))
{
//var_dump($cfi->resourceType);
$resource = new $resource_types[$cfi->resourceType];
foreach ($cfi->configuration as $key => $value)
{
if (in_array($key,$resource->fields))
{
$insert_array[from_camel_case($key)] = $value;
}
}
$resource->populate($insert_array);
if (!$resource->checkExists())
{
$resource->save();
if(isset($cfi->configuration->tags))
{
foreach ($cfi->configuration->tags as $t )
{
$tag= new Tag;
$tag->resource_type = "instance";
$tag->resource_id = $resource->id;
$tag->key = $t->key;
$tag->value = $t->value;
$tag->save();
/*if(isset($cfi->awsAccountId))
{
foreach ($accounts as $a)
{
$account_list = $a->account_id;
}
if (!in_array($account_id,$account_list))
{
$account_id = new Account;
$account_id->aws_account_id = $cfi->awsAccountId;
$account_list[] = $account_id;
$account_id->save();
}
} */
}
}
}
}
else
{
echo "Creating ".$cfi["resourceType"]." not yet supported<br>";
}
break;
case 'ResourceDeleted':
// echo"found Resource Deleted<br>";
//ITEM DELETED
if (array_key_exists($cfi->resourceType,$resource_types))
{
//var_dump($cfi->resourceType);
$resource = new $resource_types[$cfi->resourceType];
if ($resource->checkExists($cfi->resourceId))
{
$resource->delete();
if( isset($cfi->configuration->tags))
{
foreach ($cfi->configuration->tags as $t )
{
$tag= new Tag;
$tag->resource_type = "instance";
$tag->resource_id = $resource->id;
$tag->key = $t->key;
$tag->value = $t->value;
if ($tag->checkExists($cfi->configuration->tags))
{
$tag->delete();
}
}
}
}
}
else
{
echo "Deleting ".$cfi["resourceType"]." not yet supported<br>";
}
break;
case 'OK':
//echo"found Resource OK<br>";
//ITEM UPDATED
if (array_key_exists($cfi->resourceType, $resource_types))
{
//var_dump($cfi->resourceType);
$resource = new $resource_types[$cfi->resourceType];
if ($resource->checkExists($cfi->resourceId))
{
foreach ($cfi->configuration as $key => $value)
{
if (in_array($key,$resource->fields))
{
$update_array[from_camel_case($key)] = $value;
}
}
$resource->populate($update_array);
$resource->save();
}
}
else
{
echo "Updating ".$cfi["resourceType"]." not yet supported<br>";
}
break;
default:
echo "Status ".$cfi['configurationItemStatus']." not yet supported<br>";
break;
}
}
}
}
}
and the corresponding model whose class cannot be found looks like :
<?php namespace App\Models;
use Eloquent;
class SecurityGroup extends Eloquent
{
protected $table = 'security_group';
public $timestamps = false;
protected $guarded = array('id');
public $fields = array('groupId',
'groupName',
'description',
'ownerId'
);
public function checkExists()
{
return self::where('group_id', $this->group_id)->first();
}
public function populate($array)
{
foreach ($array as $k => $v)
{
$this->$k = $v;
}
}
}
I am lost as to what is causing the problem I don't see any typos but then again who knows as always thanks for any help given.
to solve the resource type needs the full namespace declaration
I am creating an application and handling common things in MY_Controller. I am using Message library to display common messages.
Here is MY_Controller.php:
<?php
class MY_Controller extends CI_Controller {
public $data = array();
public $view = TRUE;
public $theme = FALSE;
public $layout = 'default';
protected $redirect;
protected $models = array();
protected $controller_model;
protected $controller_class;
protected $controller_library;
protected $controller_name;
protected $partials = array(
'meta' => 'partials/meta',
'header' => 'partials/header',
'navigation' => 'partials/navigation',
'content' => 'partials/content',
'footer' => 'partials/footer'
);
public function __construct()
{
parent::__construct();
$this->output->enable_profiler(true);
$this->load->helper('inflector');
$this->load->helper('url');
$this->controller_class = $this->router->class;
if(count($this->models)>0)
{
foreach ($this->models as $model)
{
if (file_exists(APPPATH . 'models/' . $model . '.php'))
{
$this->controller_model = $model;
$this->load->model($model);
}
}
}else{
if (file_exists(APPPATH . 'models/' . $this->controller_model . '.php'))
{
$this->load->model($this->controller_model);
}
}
$this->controller_name = $this->router->fetch_class();
$this->action_name = $this->router->fetch_method();
}
public function _remap($method, $parameters)
{
if (method_exists($this, $method))
{
$this->run_filter('before', $parameters);
$return = call_user_func_array(array($this, $method),$parameters);
$this->run_filter('after', $parameters);
}else{
show_404();
}
if($this->theme === TRUE OR $this->theme === '')
{
$this->theme = 'default';
$this->template->set_theme($this->theme);
}else if(strlen($this->theme) > 0){
$this->template->set_theme($this->theme);
}else{
}
if($this->layout === TRUE OR $this->layout === '')
{
$this->layout = 'default';
$this->template->set_layout($this->layout);
}else if(strlen($this->layout) > 0){
$this->template->set_layout($this->layout);
}else{
}
if(isset($this->partials))
{
foreach($this->partials as $key => $value)
{
$this->template->set_partial($key,$value);
}
}
if(isset($this->data) AND count($this->data)>0)
{
foreach($this->data as $key => $value)
{
if(!is_object($value))
{
$this->template->set($key,$value);
}
}
}
if($this->view === TRUE OR $this->view === '')
{
if($this->parse == TRUE)
{
$parse_string = $this->template->build($this->router->method ,'' ,$this->parse);
echo $this->parse($parse_string);
}else{
$this->_call_content($this->router->method);
$this->template->build($this->router->method,array());
}
}else if(strlen($this->view) > 0){
if($this->parse == TRUE){
$parse_string = $this->template->build($this->router->method ,'' ,$this->parse);
echo $this->parse($parse_string);
}else{
$view = $this->view;
$this->_call_content($view);
$this->template->build($view,array());
}
}else{
$checkpoint = $this->session->flashdata('exit');
if($checkpoint){
exit();
}else{
$this->session->set_flashdata('exit',TRUE);
}
$this->redirect();
}
}
public function _call_content($view)
{
$value = $this->load->view($view,$this->data,TRUE);
$this->template->set('content',$value);
}
/* Common Controller Functions */
public function index()
{
$data[$this->controller_model] = $this->{$this->controller_model}->get_all();
$this->data = $data;
$this->view = TRUE;
if($this->input->is_ajax_request() || $this->session->flashdata('ajax')){
$this->layout = FALSE;
}else{
$this->layout = TRUE;
}
}
public function form()
{
if($this->input->is_ajax_request() OR !$this->input->is_ajax_request())
{
$this->load->helper('inflector');
$id = $this->uri->segment(4,0);
if($data = $this->input->post()){
$result = $this->{$this->controller_model}->validate($data);
if($result){
if($id > 0){
}else{
$this->{$this->controller_model}->insert($data);
}
$this->message->set('message','The page has been added successfully.');
$this->view = FALSE;
$this->layout = FALSE;
$this->redirect = "index";
}else{
$this->message->set('message','The Red fields are required');
}
}
$row = $this->{$this->controller_model}->where($id)->get();
$this->data[$module_name]= $row;
}
}
public function delete()
{
$id = $this->uri->segment(3,0);
if($id != 0){
$this->{$this->controller_model}->delete($id);
}
$this->view = FALSE;
$this->layout = FALSE;
}
public function redirect()
{
redirect($this->redirect);
}
public function call_post($data)
{
foreach($data as $key => $row){
$_POST[$key] = $row;
}
}
public function query()
{
echo $this->db->last_query();
}
public function go($data = '')
{
if(isset($data)){
echo '<pre>';
print_r($data);
}else{
echo '<pre>';
print_r($this->data);
}
}
}
/**/
As you can see i am using Phil Sturgeon's template library and i am handling the layout with Jamierumbelow's techniques.
When i set a message on form insertion failure its fine. I can display it in the _remap like this
echo $this->message->display();
In the controller its working finebut when i call it in the partial navigation it does not display the message. What can possibly be the problem. I have tried on the different places in the My_Controller. Its working fine but not in the partial or even i have tried it in the failed form i am loading again.
This is the message library i am using
https://github.com/jeroenvdgulik/codeigniter-message
Here i s my navigation partial
<nav>
<div id = "navigation">
<ul id="menubar">
<li>Home</li>
<li>Downloads</li>
<li>About Us</li>
</ul>
</div>
<div id="breadcrumb">
<div class="breadcrumbs">
<!-- Here i will pull breadcrumbs dynamically-->
</div>
<!--<h3>Dashboard</h3>-->
</div>
<br clear = "all"/>
<div id="message">
<?php
$data['message'] = $message ;
$this->load->view('messages/success',$data);?>
</div>
</nav>
The message library is using session might be flashdata so i think its loosing session data somehow. Although i am using sessions correctly autoloading it.
I have found the issue. It was very simple. I was using the base url in config file as empty
$config['base_url'] = '';
I have to change it like this
$config['base_url'] = 'http://localhost/myproject/';
I'm trying to add a final field to my project that contains a URL of the files that have been uploaded, if anyone could point me in the write direction for extending my model ?
I have included my codeIgniter Model & Controller code.
controller:
class Canvas extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->helper(array('form', 'url'));
}
function index() {
$vars = array();
//$this->load->library('ChromePhp');
//$this->ChromePhp->log('test');
//$this->ChromePhp->log($_SERVER);
// using labels
// foreach ($_SERVER as $key => $value) {
// $this->ChromePhp->log($key, $value);
// }
// warnings and errors
//$this->ChromePhp->warn('this is a warning');
//$this->ChromePhp->error('this is an error');
$this->load->library('FacebookConnect');
$facebook=$this->facebookconnect->connect();
$vars['facebook'] = $facebook;
$user = $vars['user'] = $facebook->getUser();
$this->load->model('Users_Model');
// user already set up. Show thank you page
if($user != 0 && sizeof($_POST)>0) {
$this->do_upload();
$this->iterate_profile ($vars['user'],false,$_POST);
$this->load->view('canvas',$vars);
} else {
// user not set, show welcome message
$this->load->view('canvas',$vars);
}
}
function do_upload()
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '20048';
$config['max_width'] = '10624';
$config['max_height'] = '10268';
$config['file_name'] = date("Y_m_d H:i:s");
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
}
else
{
$data = array('upload_data' => $this->upload->data());
$this->load->view('upload_success', $data);
}
}
function thank_you() {
$this->load->view('thank_you',$vars);
}
function remove() {
$vars = array();
$this->load->library('FacebookConnect');
$facebook=$this->facebookconnect->connect();
$vars['facebook'] = $facebook;
$vars['user'] = $facebook->getUser();
$this->load->model('Users_Model');
if($vars['user'] == 0) {
// user not set, redirect
redirect('/', 'refresh');
} else {
// user already set up. Remove
$this->load->model('Users_Model');
$this->Users_Model->remove($vars['user']);
}
$this->load->view('removed',$vars);
}
protected function iterate_profile ($user,$breadcrumb,$item) {
foreach($item as $key => $value) {
if(is_array($value)) {
$this->iterate_profile($user,$key,$value);
}
else {
if($breadcrumb) {
//echo '[' . $breadcrumb . '_' . $key . ']= ' . $value . ' <br />';
$key = $breadcrumb . '_' . $key;
}
if( ! $this->Users_Model->exists($user,$key)) {
// does not exist in the database, insert it
$this->Users_Model->add($user,$key,$value);
} else {
$this->Users_Model->update($user,$key,$value);
}
}
}
}
}
Model:
class Users_Model extends CI_Model {
protected $_name = 'users';
function add($id,$key,$value) {
$data = array(
'id' => $id,
'name' => $key,
'value' => $value
);
return $this->db->insert($this->_name, $data);
}
function update($id,$key,$value) {
$data = array(
'value' => $value
);
$this->db->where(array(
'id' => $id,
'name' => $key
));
return $this->db->update($this->_name, $data);
}
function exists($id,$key=null) {
if($key == null) {
$this->db->where(array(
'id' => $id
));
} else {
$this->db->where(array(
'id' => $id,
'name' => $key
));
}
$query = $this->db->get($this->_name);
if($query->num_rows() > 0) {
return true;
}
return false;
}
function remove($id) {
$data = array(
'id' => $id,
);
return $this->db->delete($this->_name, $data);
}
function all() {
$query = $this->db->get($this->_name);
$results = array();
if($query->num_rows() > 0) {
foreach($query->result() as $row) {
$results[]=$row;
}
}
return $results;
}
}
I don't think the question is very clear. But to me it seems you need to store the image path in the db. Otherwise you will need to perform a read directory on the upload path and then do something with the images.