CodeIgniter: I can’t to insert file_name image in database - codeigniter

That's code is in my controller… i can`t to insert name of image in database, except to upload in directory /uploads/
code for insertion file_name of image is below: $data[‘file_name’] = $_POST[‘file_name’];
please help me because needed for quickly.. thank you very much
public function edit ($id = NULL)
{
// Fetch a article or set a new one
if ($id) {
$this->data[‘article’] = $this->article_m->get($id);
count($this->data[‘article’]) || $this->data[‘errors’][] = ‘article could not be found’;
}
else {
$this->data[‘article’] = $this->article_m->get_new();
}
// Set up the form
$rules = $this->article_m->rules;
$this->form_validation->set_rules($rules);
// Process the form
if ($this->form_validation->run() == TRUE) {
$data = $this->article_m->array_from_post(array(
‘cat_id’,
‘title’,
‘url’,
‘body’,
‘pubdate’
));
/*
* upload
*/
$config[‘upload_path’] = ‘c:/wamp/www/uploads/’;
$config[‘allowed_types’] = ‘gif|jpg|png’;
$config[‘max_size’] = ‘1000’;
$config[‘max_width’] = ‘10240’;
$config[‘max_height’] = ‘7680’;
$field_name = “file_name”;
$this->load->library(‘upload’, $config);
if( $this->upload->do_upload($field_name)){
print “uploaded”;
die(“uploaded”);
} else {
$error = array(‘error’ => $this->upload->display_errors());
print_r($error);
die();
}
//end of upload
//insert file_name
$data[‘file_name’] = $_POST[‘file_name’];
$this->article_m->save($data, $id);
}
// Load the view
$this->data[‘subview’] = ‘admin/article/edit’;
$this->load->view(‘admin/_layout_main’, $this->data);
}

You may try something like this
if( $this->upload->do_upload($field_name) )
{
// get upload data
$upload_data = $this->upload->data();
$data[‘file_name’] = $upload_data['file_name'];
$this->article_m->save($data, $id);
//...
}
else
{
//...
}

Related

How to use save() method inside a loop in laravel

My current situation is: I must use save() method to save multiple records using loop. I know insert() will fix my problem but to maintain my code clean I have to use the same code and save() method to insert the record. I create new instance inside the loop but always only last record is being inserted. My code looks like:
public static function save($data)
{
$settings = Settings::instance();
$data['sender_address'] = urldecode($data['sender_address']);
$data['sender_address'] = json_decode($data['sender_address'], true);
extract($data);
$customerFields = ['name', 'mobile', 'alt_mobile', 'district_id', 'area_id', 'address'];
$customerObj = $customer = Customer::where('mobile', $mobile);
if ($customerObj->count()) {
$customer = $customer->first();
} else {
$customer = new Customer;
}
foreach ($customerFields as $customerField) {
if (!empty($$customerField)) {
$customer->$customerField = $$customerField;
}
}
($customerObj->count()) ? $customer->update() : $customer->save();
$order = (isset($order_id) && !empty($order_id) )? Order::find($order_id) : new Order;
$order->sender_address = $sender_address;
$order->branch_id = self::getBranchIdByAreaId($sender_address['area']);
$order->responsible_by = self::getBranchManagerIdByBranchId($order->branch_id);
$order->client_id = $client_id;
$order->customer_id = $customer->id;
$order->delivery_time = $delivery_time;
$deliveryChargeParams = [
'district_id' => $district_id,
'delivery_time' => $delivery_time,
'product_weight' => $product_weight,
'merchant_id' => $client_id,
];
$order->delivery_charge = Utility::getDeliveryCharge($deliveryChargeParams);
$order->vat = Utility::getVat($order->delivery_charge);
if (empty($order_id)) {
$order->status_id = ($role_id == Employee::CLIENT) ?
$settings['tracking']['default_status'] : Order::PACKAGINGDONE;
if (($role_id != Employee::CLIENT)) {
$order->requested = Order::PACKAGINGDONE;
}
}
$order->cash_amount = $cash_amount;
$order->cod_charge = Utility::getCodCharge($cash_amount);
$order->product_weight = $product_weight;
$order->client_reference = $client_reference;
if (empty($order_id)) {
$order->save();
$loggedInUserId = isset($data['fromApp'])?
$data['client_id'] : Auth::getUser()->id;
$order->number = self::orderNumber($order,$loggedInUserId);
$order->update();
} else {
$order->update();
}
if (($role_id != Employee::CLIENT)) {
self::updateDeliveryWithin($order);
}
PaymentAction::update($order);
}
The following method calls this save() method:
function onSave(){
$data = post();
$client_id = (Auth::getUser()->role_id == Employee::CLIENT) ? Auth::getUser()->id : $data['client_id'];
$sender_address = $data['sender_address'];
$file = Input::file('bulk_order');
$filename = time().'-'.rand(2000,99999999).'-'.$file->getClientOriginalName();
$result = $file->move('tempFiles',$filename);
$uploadedFilePath = 'tempFiles/'.$filename;
$contents = $this->csvToArray($uploadedFilePath);
// dd($contents); //exit;
unlink($uploadedFilePath);
$keys = array();
if(count($contents)){
$keys = array_keys($contents[0]);
}else{
throw new ApplicationException('Your Csv file is not in proper Format OR Empty!');
}
$fields = array('client_reference','customer_mobile','customer_alternative_mobile','customer_name','customer_district','customer_area','customer_address','product_weight_in_kg','delivery_time_in_hour','cash_collection');
$diff = array_diff($keys,$fields);
//dd($diff); exit;
if(count($diff)!=0){
throw new ApplicationException('Your Csv file is not in proper Format');
}
// dd($contents); exit;
foreach($contents as $row){
$data['name'] = $row['customer_name'];
$data['mobile'] = $row['customer_mobile'];
if(strlen($data['mobile']) == 10 ){
$data['mobile'] = '0'.$data['mobile'];
}
$data['alt_mobile'] = $row['customer_alternative_mobile'];
if(strlen($data['alt_mobile']) == 10 ){
$data['alt_mobile'] = '0'.$data['alt_mobile'];
}
$data['district_id'] = Utility::getDistrictIdByName($row['customer_district']);
$data['area_id'] = Utility::getAreaIdByName($row['customer_area']);
$data['address'] = $row['customer_address'];
$data['delivery_time'] = $row['delivery_time_in_hour'];
$data['product_weight'] = $row['product_weight_in_kg'];
$data['client_id'] = $client_id;
$data['sender_address'] = $sender_address;
$data['cash_amount'] = $row['cash_collection'];
$data['client_reference'] = $row['client_reference'];
$data['role_id'] = Auth::getUser()->role_id;
OrderAction::save($data);
}
\Flash::success('Bulk Order uploaded Successfully');
return Redirect::to('dashboard/shipments');
}
Is it possible to save multiple records with my approach? Thanks in advance.

How to skip blank rows in a csv file during import in Laravel

During the import of a CSV file, my import function creates a database record for every row of the import file. This means that if a user has left a blank row in the file then the import process creates a blank record in the database. How does one develop it so that the importer identifies blank/null rows in the CSV file, skips those blank/null rows, and only creates a record and imports a row if the row contains data?
Here is the Controller for the Import function:
public function process(Request $request)
{
$filename = $request->input('filename', false);
$path = storage_path('app/csv_import/'.$filename);
$hasHeader = $request->input('hasHeader', false);
$isAddingNewReligiousBackground = $request->input('is_adding_new_religious_background', false);
$fields = $request->input('fields', false);
$fields = array_flip(array_filter($fields));
$modelName = $request->input('modelName', false);
$model = 'App\\'.$modelName;
$reader = new SpreadsheetReader($path);
$insert = [];
$update = [];
$tags = [];
$team_id = $request->input('church_id');
$custom_fields = CustomField::where('created_by_team_id', $team_id)->get();
foreach ($reader as $key => $row) {
if ($hasHeader && $key == 0) {
continue;
}
$tmp = [];
$meta = [];
foreach ($fields as $header => $k) {
$tmp[$header] = $row[$k];
}
$tmp['created_by_id'] = auth()->user()->id;
$tmp['created_by_team_id'] = $team_id;
$tmp['created_at'] = now();
if ($modelName == 'Interest') {
$this->translateReligiousBackgroud($tmp, $isAddingNewReligiousBackground);
$meta = $this->processInterestMeta($tmp, $custom_fields);
$existing = Interest::matchingInterest((object) $tmp, $request->input('church_id'));
if ($existing) {
$update[] = $existing;
$tagsArr = array_filter((array) $request->input('interest_tags'));
foreach (\DB::table('interest_tag')->where('interest_id', $existing->id)->get() as $tag) {
$tagsArr[] = $tag->tag_id;
}
$existing->interest_tags()->sync(array_filter($tagsArr));
if (! empty($meta)) {
$existing->syncMeta($meta);
}
} else {
$tmp['meta'] = $meta;
$insert[] = $tmp;
}
} else {
$insert[] = $tmp;
}
}
$for_insert = array_chunk($insert, 10000); // this was 100, but the chunking was causing the system to only import the first 100 records, even though the success message said it imported all of them - LW 1/25/2019
foreach ($for_insert as $insert_item) {
if ($modelName == 'Interest') {
foreach ($insert_item as $item) {
$interest = new $model;
foreach ($item as $field => $value) {
if ($field != 'meta') {
$interest->$field = $value;
}
}
$interest->created_by_id = auth()->user()->id;
$interest->created_by_team_id = $request->input('church_id');
$interest->save();
// For some reason, created_by_team_id was null on initial save, do it again
$interest->created_by_team_id = $request->input('church_id');
$interest->save();
// deal with tags
$interest->interest_tags()->sync(array_filter((array) $request->input('interest_tags')));
// deal with custom fields
if (! empty($item['meta'])) {
$interest->syncMeta($item['meta']);
}
}
} else {
$model::insert($insert_item);
}
}
$rows = count($insert);
$updates = count($update);
$table = Str::plural($modelName);
File::delete($path);
$redirect = $request->input('redirect', false);
return redirect()->to($redirect)->with('message', trans(($updates > 0 ? 'global.app_imported_rows_to_table_with_updates' : 'global.app_imported_rows_to_table'),
['rows' => $rows, 'updates' => $updates, 'table' => $table]
));
}
I do not believe this is the proper way and I hope someone comes along and gives the proper answer but this here is my dirty hack. In my dataset, I have a column for lastname and all the records to have any functional purpose must have a last name so I put an -if- statement if (!empty($interest['lastname'])) checking that the 'lastname' not be empty before save.
$for_insert = array_chunk($insert, 10000); // this was 100, but the chunking was causing the system to only import the first 100 records, even though the success message said it imported all of them - LW 1/25/2019
foreach ($for_insert as $insert_item) {
if ($modelName == 'Interest') {
foreach ($insert_item as $item) {
$interest = new $model;
foreach ($item as $field => $value) {
if ($field != 'meta') {
$interest->$field = $value;
}
}
$interest->created_by_id = auth()->user()->id;
$interest->created_by_team_id = $request->input('church_id');
if (!empty($interest['lastname']))
{
$interest->save();
}
// For some reason, created_by_team_id was null on initial save, do it again
$interest->created_by_team_id = $request->input('church_id');
if (!empty($interest['lastname']))
{
$interest->save();
}
So in this manner, the system goes through the process of importing all the rows in the csv whether they have data or not but it only saves those records that have a lastname value. This accomplishes what I need but I know there must be a cleaner way to do it.
I believe there should be a method of doing this in which a record should be skipped only if all the values in a row/record is empty. So if one value is in place it will insert and create an entry but if all the values in a row are empty it will skip entry. Hopefully, someone will come along sometime and provide that more eloquent solution.

Picture not uploading to database but saving in folder

public function array_from_post($fields) {
$data = array();
foreach ($fields as $field) {
$data[$field] = $this->input->post($field);
$data['category_id'] = $this->input->post('category');
public function save($data, $id = NULL) {
// Set timestamps
if ($this->_timestamps == TRUE) {
$now = date('Y-m-d H:i:s');
$id || $data['created'] = $now;
$data['modified'] = $now;
}
// Insert
if ($id === NULL) {
!isset($data[$this->_primary_key]) || $data[$this->_primary_key] = NULL;
$this->db->set($data);
$this->db->insert($this->_table_name);
$id = $this->db->insert_id();
}
// Update
else {
$filter = $this->_primary_filter;
$id = $filter($id);
$this->db->set($data);
$this->db->where($this->_primary_key, $id);
$this->db->update($this->_table_name);
}
return $id;
}
On save this code returns column picture cannot be null. When i do the direct method without using the method array_from_post(), data is saved in the database but i can not save a post to be published at a future date.

Receive function fails to get image

I am working on multiple file upload code is not showing any error
public function imagenewAction()
{
$form = new ImageNewForm();
$form->get('submit')->setValue('Submit');
$request = $this->getRequest();
// die('checko');
if($request->isPost())
{
// die('checko');
$nonFile = $request->getPost()->toArray();
$File = $this->params()->fromFiles('file');
$data = array_merge_recursive($request->getPost()->toArray(), $request->getFiles()->toArray());
$form->setData($data);
if ($form->isValid())
{
//New Code
$dataNew=array('','image','image1');
for($i=1;$i<=2;$i++)
{
$addressProof = $data[$dataNew[$i]]['name'];
$addressProofextension = pathinfo($addressProof, PATHINFO_EXTENSION);
// $addressProofimg = $addressProof . $i . "." . $addressProofextension;
$addressProofimg = $addressProof;
//$verificationdocuments->setdocphotocopy($addressProofimg);
$adapter = new \Zend\File\Transfer\Adapter\Http();
$adapter->setDestination('public/img/upload');
$adapter->addFilter(new \Zend\Filter\File\Rename(array(
'target' => 'public/img/upload',
'overwrite' => true
)), null, $addressProofimg);
if(!$adapter->receive($addressProofimg))
{
print_r ( $adapter->getMessages (), 1 );
}
else
{
echo "Image Uploaded";
}
}
}
}
return array('form' => $form);
}
It is giving blank error messages and not uploading images please help me to get away with this I am stuck from last 2 days

Why does this webform uploaded file via ajax throw an error in Drupal 7?

I have a webform and mymodule which alters it. The webform has a field stelle which gets populated based on the url query. For instance, if ?stelle=10 the field gets populated by the title of node with nid 10. If the query ?stelle is non-existant or followed by a nid which does not exist (is not of a certain content type) or does not contain a certain string the form will be redirecting to mynode?stelle=initiativ. The form has 2 fields to upload files via ajax, works good so far. Here is my code:
<?php
/**
* Altering the form! this will add class to the file upload/ remove buttons
*/
function mymodule_form_alter(&$form, &$form_state, $form_id) {
$conf = mymodule_defaults();
if ($form_id == 'webform_client_form_' . $conf['nid']) {
if (isset($form['submitted']['field1'])) {
$form['submitted']['field1']['#process'] = array('mymodule_my_file_element_process');
}
if (isset($form['submitted']['field2'])) {
$form['submitted']['field2']['#process'] = array('mymodule_my_file_element_process');
}
$nid = $form['#node']->nid;
$form['actions']['submit']['#ajax'] = array(
'callback' => 'mymodule_webform_js_submit',
'wrapper' => 'webform-client-form-' . $nid,
'method' => 'replace',
'effect' => 'fade',
);
$redirect_form = false;
$maintenance = false;
if (isset($form['submitted']['stelle']['#default_value']) && $form['submitted']['stelle']['#default_value'] !== '') {
$hide_components = array(
'einleitung_standard',
'einleitung_initiativ',
);
$unhide_components = array();
if ($form['submitted']['stelle']['#default_value'] == '') {
$redirect_form = true;
}
elseif (is_numeric($form['submitted']['stelle']['#default_value'])) {
$nid = $form['submitted']['stelle']['#default_value'];
$node = node_load($nid);
if ($node === false || (isset($node->type) && $node->type !== 'job')) {
$redirect_form = true;
}
else {
$type = $node->type;
if ($type == 'job') {
$form['submitted']['stelle']['#default_value'] = $node->title;
$form['submitted']['stelle']['#attributes']['disabled'] = 'disabled';
$form['submitted']['related']['#value'] = $nid;
$unhide_components = array(
'einleitung_standard'
);
}
}
}
elseif ($form['submitted']['stelle']['#default_value'] == 'initiativ') {
// unset($form['submitted']['stelle']);
$form['submitted']['related']['#value'] = 'initiativ';
$unhide_components = array(
'einleitung_initiativ'
);
}
}
else {
// $redirect_form = true;
// this causes an error
}
This is the weird part:
$redirect_form = false;
$maintenance = false;
if (isset($form['submitted']['stelle']['#default_value']) && $form['submitted']['stelle']['#default_value'] !== '') {
...
else {
// $redirect_form = true;
// this causes an error
}
When I active the line to redirect the form when the if condition is false, the button to upload a file via ajax throws an error alert on click (see bottom for error). To me, this looks like the form alter hook is being called again when the file upload button is clicked without having my field stelle available - is that right? How to fix this?
And now the rest of the module, basically just alterings:
else {
// $redirect_form = true;
// this causes an error
}
foreach ($unhide_components as $key => $component) {
if (is_array($component)) {
foreach ($component as $_key => $_component) {
$index = array_search($_component, $hide_components[$key]);
if ($index !== false) {
unset($hide_components[$key][$index]);
}
}
}
else {
$index = array_search($component, $hide_components);
if ($index !== false) {
unset($hide_components[$index]);
}
}
}
// hide
foreach ($hide_components as $k=>$hc1){
if (is_array($hc1)) {
foreach ($hc1 as $hc2) unset($form['submitted'][$k][$hc2]);
} else {
unset($form['submitted'][$hc1]);
}
}
if ($redirect_form) drupal_goto('node/'.$conf['nid'], array('query'=>array('stelle'=>'initiativ')), 301);
}
}
function mymodule_my_file_element_process($element, &$form_state, $form) {
$element = file_managed_file_process($element, $form_state, $form);
$element['upload_button']['#attributes'] = array('class' => array('button'));
$prefix = '<label class="browse-slave">';
$prefix .= '<span class="button">' . t('Choose a file') . '</span>';
$element['upload']['#prefix'] = $prefix;
$element['upload_button']['#prefix'] = '</label>';
$element['remove_button']['#attributes'] = array('class' => array('button'));
$element['remove_button']['#prefix'] = '</label>';
return $element;
}
function mymodule_webform_js_submit($form, $form_state) {
// define the $sid variable (submission id from webform)
$sid = $form_state['values']['details']['sid'];
// if we have a sid then we know the form was properly submitted, otherwise, we'll just return the existing $form array
if ($sid) {
// first we have to load up the webform node object
$node = node_load($form_state['values']['details']['nid']);
// create an array up with the confirmation message, retreived from the webform node
$confirmation = array(
'#type' => 'markup',
'#markup' => check_markup($node->webform['confirmation'], $node->webform['confirmation_format'], '', TRUE),
);
// return the confirmation message
return $confirmation;
}
else {
// return the form
return $form;
}
}
The AJAX error is something like described here. Changing server/php settings didnt help it.
Thanks!
The form builder (and any hook alters) will be run when a form is validated, which happens on #ajax actions.
I like to throw static custom data in $form['#someProperty'] so that it's available in the build, validate, and submit functions. Something like this should help you:
function mymodule_form_alter(&$form, &$form_state, $form_id) {
// ...
if (isset($_GET['stelle'])) {
$form['#stelle'] = $_GET['stelle']; // This will always be there.
}
// ...
}
Another option would be to throw the $node that you load in the form, like $form['#stelle_node'] = node_load(...) and obviously only do that when the nid is actually available to you, so that you don't overwrite it with empty data when the form builder runs again in the future.
When i was working with ajax in drupal 6 the hash symbol in url or request caused an error everytime..... so i replaced url with this
data.url.replace(/%2523/, '%23');

Resources