My initial question was posted wrong so i'm reposting it. I am practicing with a tutorial on tutsplus by joost van veen and i added an image upload to the controller but every time i try to save a post i get an error from database saying column 'picture' cannot be null. I've checked other answers but nothing explains the problem. Any help would be appreciated.
MY CONTROLLER
public function edit($post_id = NULL) {
// Fetch all articles or set a new one
if ($post_id) {
$this->data['article'] = $this->article_m->get($post_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);
if ($this->input->post('userSubmit')) {
//check if user uploads picture
if (!empty($_FILES['picture']['name'])) {
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'jpg|png|gif|jpeg';
$config['file_name'] = $_FILES['picture']['name'];
//load upload library and initialize configuration
$this->upload->initialize($config);
if ($this->upload->do_upload('picture')) {
$uploadData = $this->upload->data();
$picture = $uploadData['file_name'];
} else {
$picture = '';
}
} else {
$picture = '';
}
// prepare array of posts data
$data = $this->article_m->array_from_post(array(
'title',
'slug',
'content',
'category_id',
'picture',
'pubdate'
));
$insertPosts = $this->article_m->save($data, $post_id);
redirect('admin/article');
//storing insertion status message
if ($insertPosts) {
$this->session->set_flashdata('success_msg', 'Post has been added Successfully.');
} else {
$this->session->set_flashdata('error_msg', 'error occured while trying upload, please try again.');
}
}
// Load view
$this->data['subview'] = 'admin/article/edit';
$this->load->view('admin/components/page_head', $this->data);
$this->load->view('admin/_layout_main', $this->data);
$this->load->view('admin/components/page_tail');
}
MY_MODEL
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');
}
return $data;
}
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;
}
RULES TO SET FORM VALIDATION
public $rules = array(
'pubdate' => array(
'field' => 'pubdate',
'label' => 'Publication date',
'rules' => 'trim|required|exact_length[10]'
),
'title' => array(
'field' => 'title',
'label' => 'Title',
'rules' => 'trim|required|max_length[100]'
),
'slug' => array(
'field' => 'slug',
'label' => 'Slug',
'rules' => 'trim|required|max_length[100]|url_title'
),
'content' => array(
'field' => 'content',
'label' => 'Content',
'rules' => 'trim|required'
),
'picture' => array(
'field' => 'picture',
'label' => 'Upload File',
'rules' => 'trim'
),
);
public function get_new() {
$article = new stdClass();
$article->title = '';
$article->category_id = '';
$article->slug = '';
$article->content = '';
$article->picture = '';
$article->pubdate = date('Y-m-d');
return $article;
}
I fixed the problem by creating a new method array_me() in the model and calling it in the controller.
NEW METHOD IN MY_MODEL
public function array_me($fields) {
$uploadData = $this->upload->data();
$picture = $uploadData['file_name'];
$data = array();
foreach ($fields as $field) {
$data[$field] = $this->input->post($field);
$data['category_id'] = $this->input->post('category');
$data['picture'] = $picture;
}
return $data;
}
EDITED CONTROLLER
public function edit($post_id = NULL) {
// Fetch all articles or set a new one
if ($post_id) {
$this->data['article'] = $this->article_m->get($post_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);
if ($this->input->post('userSubmit')) {
//check if user uploads picture
if (!empty($_FILES['picture']['name'])) {
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'jpg|png|gif|jpeg';
$config['file_name'] = $_FILES['picture']['name'];
//load upload library and initialize configuration
$this->upload->initialize($config);
if ($this->upload->do_upload('picture')) {
$uploadData = $this->upload->data();
$picture = $uploadData['file_name'];
} else {
$picture = '';
}
} else {
$picture = '';
}
// prepare array of posts data
$data = $this->article_m->array_me(array(
'title',
'slug',
'content',
'category_id',
'picture',
'pubdate'
));
$insertPosts = $this->article_m->save($data, $post_id);
redirect('admin/article');
//storing insertion status message
if ($insertPosts) {
$this->session->set_flashdata('success_msg', 'Post has been added Successfully.');
} else {
$this->session->set_flashdata('error_msg', 'error occured while trying upload, please try again.');
}
}
// Load view
$this->data['subview'] = 'admin/article/edit';
$this->load->view('admin/components/page_head', $this->data);
$this->load->view('admin/_layout_main', $this->data);
$this->load->view('admin/components/page_tail');
}
Related
my model
public function saveProduct(
$name,
$cat_id,
$user_id,
$description,
$status
) {
$post_image = '';
if (array_key_exists('post_image', $_FILES)) {
$config = [];
$config['upload_path'] = './assets/uploads/products';
$config['allowed_types'] = 'gif|svg|jpg|png|jpeg';
$config['max_size'] = '2048';
$config['overwrite'] = TRUE;
$config['remove_spaces'] = TRUE;
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
$this->upload->initialize($config);
if (!$this->upload->do_upload('post_image')) {
echo $this->upload->display_errors();
} else {
$post_image = $_FILES['post_image']['name'];
}
}
$data = [
'name' => $name,
'user_id' => $user_id,
'cat_id' => $cat_id,
'description' => $description,
'status' => 'active'
];
if ($post_image) {
$data['post_image'] = $post_image;
}
$this->db->insert('p0_products', $data);
return true;
}
it is changing file name to encryption in folder but in mysql i'am getting file name same as old name with unchanged on non-encrypted format
It's because you're taking from $_FILES veriable. You should take from
$this->upload->data()
So how?
$fileData = $this->upload->data();
This will return
file_name
file_type
file_path
etc.
$fileName = $fileData['file_name']
I wrote this code for dynamic dropdown select list in hook_form_alter. Options are populated by an external DB.
function car2db_annuncio_form_alter(&$form, FormStateInterface $form_state, $form_id) {
if ($form_id == 'node_annuncio_form') {
$options_type = car2db_annuncio_type_dropdown_options();
$form['field_marca']['#prefix'] = '<div id="field_marca">';
$form['field_marca']['#suffix'] = '</div>';
$form['field_tipologia']['widget']['#options'] = $options_type;
$form['field_tipologia']['widget']['#ajax'] = array(
'event' => 'change',
'callback' => 'car2db_annuncio_make_ajax_callback',
'wrapper' => 'field_marca',
'disable-refocus' => FALSE,
'progress' => [
'type' => 'throbber',
'message' => t('Verify...'),
]
);
}
}
function car2db_annuncio_type_dropdown_options() {
$connection = Database::getConnection('default', 'migrate');
$dropdown_type = ['none' => '- Seleziona - '];
$sql_type = "SELECT * FROM `car_type`";
$query_type = $connection->query($sql_type);
$res_type = $query_type->fetchAll();
foreach ($res_type as $row){
$key = $row->id_car_type;
$value = $row->name;
$dropdown_type[$key] = $value;
}
return $dropdown_type;
}
function car2db_annuncio_make_dropdown_options($key_type) {
$connection = Database::getConnection('default', 'migrate');
$dropdown_make = ['none' => '- Seleziona - '];
$sql_make = "SELECT * FROM `car_make` WHERE `id_car_type` = :tipo";
$query_make = $connection->query($sql_make, [':tipo' => $key_type]);
$res_make = $query_make->fetchAll();
foreach ($res_make as $row){
$Key_make = $row->id_car_make;
$Make_value = $row->name;
$dropdown_make[$Key_make] = $Make_value;
}
return $dropdown_make;
}
function car2db_annuncio_make_ajax_callback(array &$form, FormStateInterface $form_state) {
if ($selectedValue = $form_state->getValue('field_tipologia')) {
$selectedValue = (int) $selectedValue[0]['value'] ? (int) $selectedValue[0]['value'] : 0;
$options_marca = car2db_annuncio_make_dropdown_options($selectedValue);
$form['field_marca']['widget']['#options'] = $options_marca;
}
return $form['field_marca'];
}
Now, when click on "Save button", there is always "An illegal choice is detected...." error.
I also tried loading options into the hook_form alter, but it always returns an error.
Where am i wrong?
I remember this confusing the hell out of me back in the day when I first started playing with ajax forms in Drupal.
Hopefully I am remembering this correctly.
Basically, you have to move your logic for adding the dynamic options into the form build function (but in your case, it's the alter function).
When the ajax function is called, the form is still rebuilt and your alter function is called (and has the current form_state).
Your ajax function will just return the new form element.
Something like below (untested)
function car2db_annuncio_form_alter(&$form, FormStateInterface $form_state, $form_id) {
if ($form_id == 'node_annuncio_form') {
$options_type = car2db_annuncio_type_dropdown_options();
$form['field_marca']['#prefix'] = '<div id="field_marca">';
$form['field_marca']['#suffix'] = '</div>';
$form['field_tipologia']['widget']['#options'] = $options_type;
$form['field_tipologia']['widget']['#ajax'] = array(
'event' => 'change',
'callback' => 'car2db_annuncio_make_ajax_callback',
'wrapper' => 'field_marca',
'disable-refocus' => FALSE,
'progress' => [
'type' => 'throbber',
'message' => t('Verify...'),
]
);
// Check selected value here.
if ($selectedValue = $form_state->getValue('field_tipologia')) {
$selectedValue = (int) $selectedValue[0]['value'] ? (int) $selectedValue[0]['value'] : 0;
$options_marca = car2db_annuncio_make_dropdown_options($selectedValue);
$form['field_marca']['widget']['#options'] = $options_marca;
}
}
}
function car2db_annuncio_type_dropdown_options() {
$connection = Database::getConnection('default', 'migrate');
$dropdown_type = ['none' => '- Seleziona - '];
$sql_type = "SELECT * FROM `car_type`";
$query_type = $connection->query($sql_type);
$res_type = $query_type->fetchAll();
foreach ($res_type as $row){
$key = $row->id_car_type;
$value = $row->name;
$dropdown_type[$key] = $value;
}
return $dropdown_type;
}
function car2db_annuncio_make_dropdown_options($key_type) {
$connection = Database::getConnection('default', 'migrate');
$dropdown_make = ['none' => '- Seleziona - '];
$sql_make = "SELECT * FROM `car_make` WHERE `id_car_type` = :tipo";
$query_make = $connection->query($sql_make, [':tipo' => $key_type]);
$res_make = $query_make->fetchAll();
foreach ($res_make as $row){
$Key_make = $row->id_car_make;
$Make_value = $row->name;
$dropdown_make[$Key_make] = $Make_value;
}
return $dropdown_make;
}
function car2db_annuncio_make_ajax_callback(array &$form, FormStateInterface $form_state) {
// Just return the form element (that has been rebuilt in the form_alter)
return $form['field_marca'];
}
Question: When the user has filled in the form validation correct but there is a error on image upload how is it possible to stop the form being submitted
Currently still submits data even if there is a error on my image upload.
<?php
class Users extends MY_Controller {
private $error = array();
public function __construct() {
parent::__construct();
$this->load->library('form_validation');
$this->load->library('countries');
$this->load->library('upload');
$this->load->model('admin/user/user_model');
$this->load->model('admin/user_group/usergroup_model');
}
public function add() {
$this->form_validation->set_rules('username', 'Username', 'trim|required');
if ($this->form_validation->run() == true) {
if (isset($_FILES['userfile']) && $_FILES['userfile']['size'] > 0) {
if (!is_dir(FCPATH . 'uploads/users/' . $this->input->post('username') . '/')) {
mkdir(FCPATH . 'uploads/users/' . $this->input->post('username') . '/');
}
$config['upload_path'] = './uploads/users/' . $this->input->post('username') . '/';
$config['allowed_types'] = 'gif|png';
$config['max_size'] = 3000;
$config['max_width'] = 0;
$config['max_height'] = 0;
$config['overwrite'] = TRUE;
$this->upload->initialize($config);
if ($this->upload->do_upload('userfile')) {
return true;
}
}
$this->user_model->insert($this->upload->data());
}
if ($this->upload->display_errors() != false) {
$this->error['warning'] = $this->upload->display_errors();
}
if (validation_errors() != false) {
$this->error['warning'] = validation_errors('<div class="alert alert-danger">', '</div>');
}
if (isset($this->error['warning'])) {
$data['warning_error'] = $this->error['warning'];
} else {
$data['warning_error'] = '';
}
$data['countries'] = $this->countries->get();
$data['timezones'] = DateTimeZone::listIdentifiers(DateTimeZone::ALL);
$data['usergroups'] = $this->usergroup_model->get_user_groups();
$data['header'] = Modules::run('admin/common/header/index');
$data['footer'] = Modules::run('admin/common/footer/index');
$this->load->view('user/add_view', $data);
}
}
Model
<?php
class User_model extends CI_Model {
public function insert($upload_data = array()) {
$this->db->trans_begin();
$options = [
'cost' => 12,
];
$hash = password_hash($this->input->post('password'), PASSWORD_BCRYPT, $options);
$data = array(
'user_group_id' => $this->input->post('user_group_id'),
'username' => $this->input->post('username'),
'password' => $hash,
'firstname' => $this->input->post('firstname'),
'lastname' => $this->input->post('lastname'),
'email' => $this->input->post('email'),
'image' => ($upload_data['file_name']) ? $upload_data['file_name'] : '',
'country' => $this->input->post('country'),
'timezone' => $this->input->post('timezone'),
'status' => $this->input->post('status'),
'date_added' => date('Y-m-d')
);
$this->db->set($data);
$this->db->insert($this->db->dbprefix . 'user');
if ($this->db->trans_status() === FALSE) {
$this->db->trans_rollback();
} else {
$this->db->trans_commit();
}
}
}
Codeigniter Version 3.1.0 & XAMPP Windows 10
Have solved it now.
<?php
class Users extends MY_Controller {
private $error = array();
public function __construct() {
parent::__construct();
$this->load->library('form_validation');
$this->load->library('countries');
$this->load->library('upload');
$this->load->model('admin/user/user_model');
$this->load->model('admin/user_group/usergroup_model');
}
public function add() {
$this->form_validation->set_rules('username', 'username', 'trim|required|is_unique[user.username]');
$this->form_validation->set_message('is_unique', 'Opps looks like someone has all ready got that {field}');
if ($this->form_validation->run() == true) {
if (isset($_FILES['userfile']) && $_FILES['userfile']['size'] > 0) {
if ($this->upload() == true) {
$this->user_model->insert($this->upload->data());
}
} else {
$this->user_model->insert();
}
}
if (validation_errors() != '') {
$this->error['warning'] = validation_errors('<div class="alert alert-danger">', '</div>');
}
if (isset($this->error['warning'])) {
$data['warning_error'] = $this->error['warning'];
} else {
$data['warning_error'] = '';
}
$data['countries'] = $this->countries->get();
$data['timezones'] = DateTimeZone::listIdentifiers(DateTimeZone::ALL);
$data['usergroups'] = $this->usergroup_model->get_user_groups();
$data['header'] = Modules::run('admin/common/header/index');
$data['footer'] = Modules::run('admin/common/footer/index');
$this->load->view('user/add_view', $data);
}
public function upload() {
if (!is_dir(FCPATH . 'uploads/users/' . $this->input->post('username') . '/')) {
mkdir(FCPATH . 'uploads/users/' . $this->input->post('username') . '/');
}
$config['upload_path'] = './uploads/users/' . $this->input->post('username') . '/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 3000;
$config['max_width'] = 0;
$config['max_height'] = 0;
$config['overwrite'] = TRUE;
$this->upload->initialize($config);
if (!$this->upload->do_upload('userfile')) {
$this->error['warning'] = $this->upload->display_errors('<div class="alert alert-danger">', '</div>');
} else {
return true;
}
return !$this->error;
}
}
I need to add default images to post, if user do not select an image to upload.
Field to load the image optional.
How can i make it?
I use this controller.
public function news() {
$cur_user_id['user_id'] = $this->ion_auth->user()->row()->user_id;
$this->db->update('news', $cur_user_id);
$crud = new grocery_CRUD();
$crud->set_table('news')
->display_as('title', 'Заголовок')
->display_as('content', 'Текст')
->display_as('date', 'Дата')
->display_as('urlpict', 'Изображение')
->display_as('hide', 'Отображение')
->display_as('tags', 'Теги')
->display_as('add_new_tags', 'Добавить новые теги')
->display_as('menu_id', 'Раздел меню');
$crud->unset_columns('user_id');
$crud->required_fields('title', 'content', 'date', 'hide');
//relation
$crud->set_relation('menu_id', 'my_menu', 'name');
$crud->set_relation_n_n('tags', 'tag2art', 'tags', 'art_id', 'tag_id', 'tag');
//configuration for uploading
$this->config->set_item('grocery_crud_file_upload_allow_file_types', 'gif|jpeg|jpg|png');
$crud->set_field_upload('urlpict', 'assets/uploads/images');
//callback function
$crud->callback_after_upload(array($this, 'func_callback_after_upload'));
$state = $crud->getState();
$state_info = $crud->getStateInfo();
if ($state == 'add') {
$crud->fields('title', 'content', 'date', 'urlpict', 'hide', 'tags', 'add_new_tags', 'menu_id');
$crud->callback_add_field('add_new_tags', array($this, 'add_field_callback_1'));
} else {
$crud->unset_fields('add_new_tags', 'views', 'user_id');
}
$output = $crud->render();
$this->load->view('administrator/news', $output);
}
It's my callback_function
function func_callback_after_upload($uploader_response, $field_info, $files_to_upload)
{
$config['image_library'] = 'gd2';
$config['source_image'] = $field_info->upload_path . '/' . $uploader_response[0]->name;
$config['create_thumb'] = FALSE;
$config['maintain_ratio'] = TRUE;
$config['width'] = 175;
$config['height'] = 175;
$this->load->library('image_lib', $config);
$this->image_lib->resize();
return true;
}
Mine solution
Instead $crud->callback_after_update(array($this, 'default_img'));
I used $crud->callback_after_insert(array($this, 'default_img'));
And my controller
function default_img($post_array, $primary_key) {
if (!$this->input->post('urlpict')) {
$default_img = array(
"id" => $primary_key,
"urlpict" => "news_default.png"
);
$this->db->update('news', $default_img, array('id' => $primary_key));
return true;
}
}
I try to use the "product_attribute.info" to access the API in magento and is returning:
Fatal error: Uncaught SoapFault exception: [3] Invalid api path. in... on line 81
Where is returning return $proxy->call($sessionId, 'product_attribute.info', $attributeId);
Even replacing the function given by $attributeId gives correct this error.
I imagine that some file is corrupted on my server, but do not know which one is responsible.
I thank
EDIT: My Api.php
class Mage_Catalog_Model_Product_Attribute_Api extends Mage_Catalog_Model_Api_Resource
{
public function __construct()
{
$this->_storeIdSessionField = 'product_store_id';
$this->_ignoredAttributeCodes[] = 'type_id';
$this->_ignoredAttributeTypes[] = 'gallery';
$this->_ignoredAttributeTypes[] = 'media_image';
}
public function items($setId)
{
$attributes = Mage::getModel('catalog/product')->getResource()
->loadAllAttributes()
->getSortedAttributes($setId);
$result = array();
foreach ($attributes as $attribute) {
/* #var $attribute Mage_Catalog_Model_Resource_Eav_Attribute */
if ( (!$attribute->getId() || $attribute->isInSet($setId))
&& $this->_isAllowedAttribute($attribute)) {
if (!$attribute->getId() || $attribute->isScopeGlobal()) {
$scope = 'global';
} elseif ($attribute->isScopeWebsite()) {
$scope = 'website';
} else {
$scope = 'store';
}
$result[] = array(
'attribute_id' => $attribute->getId(),
'code' => $attribute->getAttributeCode(),
'type' => $attribute->getFrontendInput(),
'required' => $attribute->getIsRequired(),
'scope' => $scope
);
}
}
return $result;
}
public function options($attributeId, $store = null)
{
$storeId = $this->_getStoreId($store);
$attribute = Mage::getModel('catalog/product')
->setStoreId($storeId)
->getResource()
->getAttribute($attributeId)
->setStoreId($storeId);
/* #var $attribute Mage_Catalog_Model_Entity_Attribute */
if (!$attribute) {
$this->_fault('not_exists');
}
$options = array();
if ($attribute->usesSource()) {
foreach ($attribute->getSource()->getAllOptions() as $optionId=>$optionValue) {
if (is_array($optionValue)) {
$options[] = $optionValue;
} else {
$options[] = array(
'value' => $optionId,
'label' => $optionValue
);
}
}
}
return $options;
}
}