I am geeting the below error A necessary field "Summary" was empty. Please recheck your inputs.Can anyone suggest how to proceed.
I have mapped the summary column in import but still shows the error.
<?php
class Csv_importPlugin extends MantisPlugin
{
function register() {
$this->name = plugin_lang_get( 'title' );
$this->description = plugin_lang_get( 'description' );
$this->version = '2.0.0';
$this->requires = array( 'MantisCore' => '2.0.0' );
$this->author = 'Bug 4220 Team';
$this->contact = 'https://github.com/mantisbt-plugins/csv-import/';
$this->url = 'https://github.com/mantisbt-plugins/csv-import/';
$this->page = 'config';
}
function config() {
return array(
'import_issues_threshold' => MANAGER ,
);
}
function hooks() {
return array(
'EVENT_MENU_MANAGE' => 'csv_import_menu',
);
}
function csv_import_menu() {
return array(
'' . plugin_lang_get( 'manage_issues_link' ) . '',
);
}
}
Try this. No need of plugin
Let's say you have a CSV file with file columns
$file = $_FILES['csv_file']['tmp_name']; //get CSV file
$handle = fopen($file, "r"); //handle
while(($filesop = fgetcsv($handle, 1000, ",")) !== false){ //start while loop
$sname = $filesop[0];
$fname = $filesop[1];
$oname = $filesop[2];
$gender= $filesop[3];
$country= $filesop[4];
// Put your SQL code to insert before while loop ends
} //end while loop
Related
I want to call my function but when I call it I have a problem with curly Brackets at the end of my code and i have this error Error SYMFONY ( {} ) in my Controller.
I have no idea where to put them for my code to work. I have this problem when I add my function that allows me to retrieve the
history of the action. The mentioned function goes as this:
$this->logHistory->addHistoryConnection($project->getId(), $user->getId(), 'Delete Local Suf', $sf_code);
Function Supp Suf
/**
* #Route("/creation/suf/supp", name="suf_supp")
*/
public function suf(
Request $request,
ShapesRepository $shapesRepository
) {
$params = $this->requestStack->getSession();
$projet = $params->get('projet');
$modules = $params->get('modules');
$fonctionnalites = $params->get('fonctionnalites');
$user = $this->getUser()->getUserEntity();
$manager = $this->graceManager;
$mapManager = $this->mapManager;
$countElements = $mapManager->getCount();
$shapes = $shapesRepository->findBy(array('projet' => $projet->getId()));
$adresseWeb = $this->getParameter('adresse_web');
$carto = $params->get('paramCarto');
$centrage = $params->get('centrage');
$cableColor = $params->get('cableColor');
$sf_code = '';
if ($request->get('suf') != '') {
$sf_code = $request->get('suf');
}
$suf = $manager->getSuf($sf_code);
$success = '';
$error = '';
$warning = '';
if ($request->query->get('success')) {
$success = $request->query->get('success');
} elseif ($request->query->get('error')) {
$error = $request->query->get('error');
} elseif ($request->query->get('warning')) {
$warning = $request->query->get('warning');
}
if ($request->isMethod('POST')) {
if ($request->request->get('sf_code') != '') {
$sf_code = $request->request->get('sf_code');
}
if ($request->get('val') != '') {
$val = $request->get('val');
}
$dir = $this->getparameter('client_directory');
$dossier = str_replace(' ', '_', $projet->getProjet());
$dir = $dir . $dossier . '/documents/';
$cable = $val[0];
$chem = $val[1];
$t_suf = $this->graceCreator->supprimeSuf($sf_code, $cable, $chem);
if ($t_suf[0][0] == '00000') {
$this->logHistorique->addHistoryConnection($projet->getId(), $user->getId(), 'Suppression Suf Local', $sf_code);
// $creator->delDirObjet( $st_code, $dir );
$data = new JsonResponse(array("success" => "create!"));
return $data;
} else {
$data = new JsonResponse(array("error" => "Error : " . $t_suf));
return $data;
}
return $this->render('Modifications/supSuf.html.twig', array(
'user' => $user,
'paramCarto' => $carto,
'cableColor' => $cableColor,
'suf' => $suf,
'adresseWeb' => $adresseWeb,
'centrage' => $centrage,
'shapes' => $shapes,
'projet' => $projet,
'modules' => $modules,
'fonctionnalites' => $fonctionnalites,
'countElements' => $countElements
));
}
}
Your only return statement is inside of an if condition. If the code does not pass the condition, it has nothing to return. The code must return something in all possible cases. If you are not still used to these practices, an IDE might guide you until it becomes a routine. PHPStorm is my personal preference.
BTW, I recommend you to switch from the array() syntax to the more globally accepted [] although you must be in PHP 5.4 or higher.
I have csv with 4 columns. If i select make it shows models then year. I want it to show versions at the 4th box. however nothing happens. i have changed code and it will show versions in the 3rd box and then years disappears. still nothing in 4th box.
Played around with this bit of the code which makes the above effect but cant figure out why the 4th select box dont work.
$makes_models_years_versions = array();
$uploads_folder = wp_upload_dir()['basedir'];
$file = fopen($uploads_folder.'/make_model_year_version.csv', 'r');
$firstline = true;
while (($line = fgetcsv($file)) !== FALSE) {
if ($firstline){
$firstline = false;
continue;
}
$makes_models_years_versions[$line[0]][$line[1]][$line[2]][] = $line[3];
}
COMPLETE CODE BELOW:
function ajax_cf7_populate_values() {
// read the CSV file in the $makes_models_years_versions array
$makes_models_years_versions = array();
$uploads_folder = wp_upload_dir()['basedir'];
$file = fopen($uploads_folder.'/make_model_year_version.csv', 'r');
$firstline = true;
while (($line = fgetcsv($file)) !== FALSE) {
if ($firstline){
$firstline = false;
continue;
}
$makes_models_years_versions[$line[0]][$line[1]][$line[2]][] = $line[3];
}
fclose($file);
// setup the initial array that will be returned to the the client side script as a JSON object.
$return_array = array(
'makes' => array_keys($makes_models_years_versions),
'models' => array(),
'years' => array(),
'versions' => array(),
'current_make' => false,
'current_model' => false,
'current_year' => false
);
// collect the posted values from the submitted form
$make = key_exists('make', $_POST) ? $_POST['make'] : false;
$model = key_exists('model', $_POST) ? $_POST['model'] : false;
$year = key_exists('year', $_POST) ? $_POST['year'] : false;
$version = key_exists('version', $_POST) ? $_POST['version'] : false;
// populate the $return_array with the necessary values
if ($make) {
$return_array['current_make'] = $make;
$return_array['models'] = array_keys($makes_models_years_versions[$make]);
if ($model) {
$return_array['current_model'] = $model;
$return_array['years'] = $makes_models_years_versions[$make][$model];
if ($year) {
$return_array['current_year'] = $year;
$return_array['versions'] = $makes_models_years_versions[$make][$model][$year];
if ($version) {
$return_array['current_version'] = $version;
}
}
}
}
// encode the $return_array as a JSON object and echo it
echo json_encode($return_array);
wp_die();
}
// These action hooks are needed to tell WordPress that the cf7_populate_values() function needs to be called
// if a script is POSTing the action : 'cf7_populate_values'
add_action( 'wp_ajax_cf7_populate_values', 'ajax_cf7_populate_values' );
add_action( 'wp_ajax_nopriv_cf7_populate_values', 'ajax_cf7_populate_values' );
I have noticed that if a cell is empty phpexcel gives it a null value. Is there a way i can replace the null value with any empty string before i loop through the array and store into the database. Below is my code and i am using the codeigniter framework.
public function import(){
$id = $this->session->userdata('company_id');
$directoryname = get_company_full_name($id);
if (!is_dir(FCPATH.'assets/customer_documents/Databases/'.$directoryname)) {
mkdir(FCPATH.'assets/customer_documents/Databases/'.$directoryname, 0777, TRUE);
}
$database_name = $this->input->post('database_name');
// $data['addressbook'] = $this->csv_model->get_addressbook($id);
$data['errors'] = ''; //initialize upload error array to empty
$config['upload_path'] = FCPATH.'assets/customer_documents/Databases/'.$directoryname;
$config['allowed_types'] = '*';
$config['max_size'] = '';
$this->upload->initialize($config);
if (!$this->upload->do_upload()) {
$data['errors'] = $this->upload->display_errors();
$data['databases'] = $this->database->get_databases($id);
$this->session->set_flashdata($data);
redirect(base_url().'Databases');
} else {
$file_data = $this->upload->data();
$file_ext = $file_data['file_ext'];
// use custom function to determine if filetype is allowed
if (allow_csv_type($file_ext))
{
$file_path = FCPATH.'assets/customer_documents/Databases/'.$directoryname. '/' .$file_data['file_name'];
//read file from path
$objPHPExcel = PHPExcel_IOFactory::load($file_path);
$date_uploaded = date("Y-m-d H:i:s");
if ($objPHPExcel) {
//get only the Cell Collection
$cell_collection = $objPHPExcel->getActiveSheet()->getCellCollection();
//extract to a PHP readable array format
foreach ($cell_collection as $cell) {
$column = $objPHPExcel->getActiveSheet()->getCell($cell)->getColumn();
$row = $objPHPExcel->getActiveSheet()->getCell($cell)->getRow();
$data_value = $objPHPExcel->getActiveSheet()->getCell($cell)->getValue();
//header will/should be in row 1 only. of course this can be modified to suit your need.
if ($row == 1) {
$header[$row][$column] = $data_value;
} else {
$arr_data[$row][$column] = $data_value;
}
}
// array_shift($arr_data); // removes the 1st/header element
//store the database name and details
$database_data = array(
'db_name'=>$database_name,
'company_id' => $id,
'deleted' => 0,
'date_uploaded'=> $date_uploaded
);
$this->database->insert_db($database_data);
$database_id = $this->db->insert_id();
foreach ($arr_data as $row) {
$insert_data = array(
'company_id' => $this->session->userdata('company_id'),
'number'=>$row['A'],
'province'=>$row['B'],
'district'=>$row['C'],
'ward'=>$row['D'],
'farming_type'=>$row['E'],
'commodity'=>$row['F'],
'database_name'=>$database_name,
'db_id' =>$database_id,
'deleted' => 0,
'date_uploaded'=>$date_uploaded
);
$this->database->insert_csv($insert_data, $id);
}
log_message('info', '*****************************Customer with the ID: '.$this->session->userdata('company_id').' and name: '.get_company_full_name($this->session->userdata('company_id')).' uploaded a csv database. The uploder phone number: '.$this->session->userdata('phone').' The database ID: '.$database_id.' The database name: '.$database_name.'*****************************');
$this->session->set_flashdata('success', 'Data Imported Succesfully');
redirect(base_url().'Databases');
} else{
$data['errors'] = "Error occured";
$data['page_class'] = 'Databases-page';
$data['title'] = 'Databases';
$data['content_view'] = 'Databases/index';
$this->template->admin_template($data);
}
}
else {
$this->session->set_flashdata('errors','File type is not allowed!');
redirect('Databases');
}
}
}
}
I am just looking for a way i can add empty sting values on the empty cells that are coming with null values.
Just use a simple array modifier before it reaches PHPExcel.
If performance is an issue, one may consider not to create multiple functions within array_map(). Note that isset() is extremely fast, and this solutions does not call any other functions at all.
$replacements = array(
'search1' => 'replace1',
'search2' => 'replace2',
'search3' => 'replace3'
);
foreach ($a as $key => $value) {
if (isset($replacements[$value])) {
$a[$key] = $replacements[$value];
}
}
See: https://stackoverflow.com/a/32321702/4272537
I am currently doing an internship and I tried to make an activity module to show playlist, from video given by a filemanager. I succeed to send the video to the database but when I want to edit my module, it doesn't show any videos in the filemanager.
I read the moodle documentation about file API and I decided to use the following code (Load existing files into draft area)
:
if (empty($entry->id)) {
$entry = new stdClass;
$entry->id = null;
}
$draftitemid = file_get_submitted_draft_itemid('attachments');
file_prepare_draft_area($draftitemid, $context->id, 'mod_glossary','attachment', $entry->id,array('subdirs' => 0, 'maxbytes' => $maxbytes, 'maxfiles' => 50));
$entry->attachments = $draftitemid;
$mform->set_data($entry);
So I put the following lines in my mod_form.php :
$filemanager_options = array();
$filemanager_options['accepted_types'] = '*';
$filemanager_options['maxbytes'] = 0;
$filemanager_options['maxfiles'] = -1;
$filemanager_options['mainfile'] = true;
$mform->addElement('filemanager', 'files', get_string('selectfiles'), null, $filemanager_options);
if (empty($entry->id)) {
$entry = new stdClass;
$entry->id = null;
}
$draftitemid = file_get_submitted_draft_itemid('mymanager');
file_prepare_draft_area($draftitemid, $this->context->id, 'mod_playlist', 'content', 0,
array('subdirs'=>true));
$entry->attachments = $draftitemid;
$mform->set_data($entry);
The problem is that the file manager is still empty, and the line "$mform->set_data($entry); " makes the page to crash(blank).
Here is a template for uploading files.
In local/myplugin/upload.php
require_once(dirname(dirname(dirname(__FILE__))) . '/config.php');
require_once(dirname(__FILE__) . '/upload_form.php');
require_login();
$context = context_system::instance();
require_capability('local/myplugin:upload', $context);
$pageurl = new moodle_url('/local/myplugin/upload.php');
$heading = get_string('myupload', 'local_myplugin');
$PAGE->set_context($context);
$PAGE->set_heading(format_string($heading));
$PAGE->set_title(format_string($heading));
$PAGE->set_url('/local/myplugin/upload.php');
echo $OUTPUT->header();
echo $OUTPUT->heading($heading);
$fileoptions = array(
'maxbytes' => 0,
'maxfiles' => '1',
'subdirs' => 0,
'context' => context_system::instance()
);
$data = new stdClass();
$data = file_prepare_standard_filemanager($data, 'myfiles',
$fileoptions, context_system::instance(), 'local_myplugin', 'myfiles', 0); // 0 is the item id.
$mform = new upload_form(
null,
array(
'fileoptions' => $fileoptions,
)
);
if ($formdata = $mform->get_data()) {
// Save the file.
$data = file_postupdate_standard_filemanager($data, 'myfiles',
$fileoptions, context_system::instance(), 'local_myplugin', 'myfiles', 0);
} else {
// Display the form.
$mform->set_data($data);
$mform->display();
}
echo $OUTPUT->footer();
Then in local/myplugin/upload_form.php
defined('MOODLE_INTERNAL') || die;
require_once($CFG->libdir . '/formslib.php');
class upload_form extends moodleform {
public function definition() {
$mform =& $this->_form;
$fileoptions = $this->_customdata['fileoptions'];
$mform->addElement('filemanager', 'myfiles_filemanager',
get_string('myfiles', 'local_myplugin'), null, $fileoptions);
$this->add_action_buttons(false, get_string('save', 'local_myplugin'));
}
}
You will also need this in /local/myplugin/lib.php
function local_myplugin_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options = array()) {
if ($context->contextlevel != CONTEXT_SYSTEM) {
send_file_not_found();
}
$fs = get_file_storage();
$file = $fs->get_file($context->id, 'local_myplugin', $filearea, $args[0], '/', $args[1]);
send_stored_file($file);
}
I need to import csv data in database where my Product table have two columns code and price. I am importing data with this script, which find the product code and then update that product price -
function update_price()
{
$this->sma->checkPermissions('csv');
$this->load->helper('security');
$this->form_validation->set_rules('userfile', lang("upload_file"), 'xss_clean');
if ($this->form_validation->run() == true) {
if (isset($_FILES["userfile"])) {
$this->load->library('upload');
$config['upload_path'] = $this->digital_upload_path;
$config['allowed_types'] = 'csv';
$config['max_size'] = $this->allowed_file_size;
$config['overwrite'] = TRUE;
$this->upload->initialize($config);
if (!$this->upload->do_upload()) {
$error = $this->upload->display_errors();
$this->session->set_flashdata('error', $error);
redirect("products/update_price");
}
$csv = $this->upload->file_name;
$arrResult = array();
$handle = fopen($this->digital_upload_path . $csv, "r");
if ($handle) {
while (($row = fgetcsv($handle, 1000, ",")) !== FALSE) {
$arrResult[] = $row;
}
fclose($handle);
}
$titles = array_shift($arrResult);
$keys = array('code', 'price');
$final = array();
foreach ($arrResult as $key => $value) {
$final[] = array_combine($keys, $value);
}
$rw = 2;
foreach ($final as $csv_pr) {
if (!$this->products_model->getProductByCode(trim($csv_pr['code']))) {
$this->session->set_flashdata('message', lang("check_product_code") . " (" . $csv_pr['code'] . "). " . lang("code_x_exist") . " " . lang("line_no") . " " . $rw);
redirect("product/update_price");
}
$rw++;
}
}
}
if ($this->form_validation->run() == true && !empty($final)) {
$this->products_model->updatePrice($final);
$this->session->set_flashdata('message', lang("price_updated"));
redirect('products');
} else {
$this->data['error'] = (validation_errors() ? validation_errors() : $this->session->flashdata('error'));
$this->data['userfile'] = array('name' => 'userfile',
'id' => 'userfile',
'type' => 'text',
'value' => $this->form_validation->set_value('userfile')
);
$bc = array(array('link' => base_url(), 'page' => lang('home')), array('link' => site_url('products'), 'page' => lang('products')), array('link' => '#', 'page' => lang('update_price_csv')));
$meta = array('page_title' => lang('update_price_csv'), 'bc' => $bc);
$this->page_construct('products/update_price', $meta, $this->data);
}
}
But here our product price update and replace old value , but i want check old value of price and
if old value is greater than uploaded value , then not replaced and
if old value is lower than uploaded value of price then update/replaced that value .
means in all condition our price is always maximum .
how we can do it ??? anyone help please ..
I think you should look inside the updatePrice method and modify a mysql query in it.
Mysql has a proper Update if statement.