How to update data using session in codeigniter - codeigniter-3

This my code in codeigniter but it doesn't update in database, I'm beginner ni codeigniter, how could I fix this error, or what is wrong in my code?
THis is my Controller:
function edit() {
$role = $this->session->userdata('role');
$this->form_validation->set_rules('firstname', 'firstname', 'required|xss_clean');
$this->form_validation->set_rules('lastname', 'lastname', 'required|xss_clean');
if ($this->form_validation->run() == FALSE) {
//set page data
$data['title'] = 'Update Profile';
if($role!=''){
$data['admin'] = $this->M_user->get($this->session->userdata('user_id'));
}else{
$data['admin'] = $this->M_administrator->getAdmin($this->session->userdata('id_admin'));
}
$data['sitename'] = $this->M_website->getName();
$data['content'] = 'admin/myaccount/edit';
//parse template
$this->parser->parse('admin/template', $data);
} else {
if($role!=''){
if ($this->M_user->updateStatus($_POST['user_id'])) {
//SAVE ADMIN ACTION LOG
//save_admin_action(array('module' => Constant::AM_ACCOUNT, 'action' => Constant::AL_EDIT, 'title' => $this->form_validation['username'], 'object_id' => $id));
//redirect page
$this->session->set_flashdata('saved', TRUE);
redirect('admin/myaccount');
}
}else{
if ($this->M_administrator->updateStatus($_POST['id_admin'])) {
//SAVE ADMIN ACTION LOG
//save_admin_action(array('module' => Constant::AM_ACCOUNT, 'action' => Constant::AL_EDIT, 'title' => $this->form_validation['username'], 'object_id' => $id));
//redirect page
$this->session->set_flashdata('saved', TRUE);
redirect('admin/myaccount');
}
}
}
}
This is my model administrator:
function updateStatus($post, $id){
$data = array(
'firstname' => $post['firstname'],
'lastname' => $post['lastname']
);
$this->db->where('id_admin', $id);
if($this->db->update('admin', $data)){
return TRUE;
}else{
return FALSE;
}
}
user Model:
function updateStatus($post, $id){
$data = array(
'firstname' => $post['firstname'],
'lastname' => $post['lastname']
);
$this->db->where('user_id', $id);
if($this->db->update('user', $data)){
return TRUE;
}else{
return FALSE;
}
}

pass firstname and last name to your updatestatus model function if you are not getting that value in model so you are not able to change
print your query using $this->db->last_query(); to get query output and post your query here

Change your where clause to
$this->db->where('id_admin', $post);

Related

Facebook Login Exception

I have this function that handle the Fb Callback.
public function handleFbCallback() {
if( !\Input::get('error', NULL) ) {
try {
$fuser = \Socialize::with('facebook')->user();
$token = $fuser->token;
if($fb = \App\UserFacebook::whereEmail($fuser->getEmail())->first()) {
$fb->fb_id = $fuser->getId();
$fb->nickname = $fuser->getNickname();
$fb->name = $fuser->getName();
$fb->avatar = $fuser->getAvatar();
$fb->token = $token;
$fb->save();
$profile = \App\Profile::whereUserId($fb->user_id)->first();
if($profile) {
$profile->name = $fuser->user['first_name'];
$profile->last_name = $fuser->user['last_name'];
$profile->save();
} else {
\App\Profile::create([
'name' => $fuser->user['first_name'],
'last_name' => $fuser->user['last_name'],
'user_id' => $fb->user_id,
]);
}
//load user and increments number login
$user = \App\User::find($fb->user_id);
if($user) {
$user->last_login = date('Y-m-d H:i:s');
$user->number_logins = $user->number_logins + 1;
$user->save();
}
}
else {
$password = str_random(8);
$nuser = \App\User::whereEmail($fuser->getEmail())->first();
if(!$nuser) {
$nuser = \App\User::create([
'email' => $fuser->getEmail(),
'password' => bcrypt($password),
'active' => 1,
]);
if(\Session::get('source', NULL)) {
$nuser->source = \Session::get('source');
\Session::forget('source');
}
if(\Session::get('campaign', NULL)) {
$nuser->source = \Session::get('campaign');
\Session::forget('campaign');
}
$nuser->save();
//profile
\App\Profile::create([
'name' => $fuser->user['first_name'],
'last_name' => $fuser->user['last_name'],
'user_id' => $nuser->id,
]);
}
$nuser->last_login = date('Y-m-d H:i:s');
$nuser->number_logins = 1;
$nuser->save();
$fb = \App\UserFacebook::create([
'fb_id' => $fuser->getId(),
'nickname' => $fuser->getNickname(),
'name' => $fuser->getName(),
'email' => $fuser->getEmail(),
'avatar' => $fuser->getAvatar(),
'token' => $token,
'user_id' => $nuser->id
]);
}
\Auth::loginUsingId($fb->user_id);
if(\Session::get('custom_url', NULL) == 'thanks') {
return redirect()->route('landing.thanks', array('social', $fb->user_id));
} elseif($url = \Session::get('custom_url', NULL)) {
\Session::forget('custom_url');
return redirect($url);
}
return redirect()->intended();
}
catch(Exception $e) {
dd($e->getMessage());
}
}
return redirect('/');
}
Running this function it make an exception:
Client error: GET https://graph.facebook.com/v2.6/me?access_token=&appsecret_proof=cb32db5fac27b922d1a9c3040772a05b9a6e79f8145ee5a9fc21bbefd1f00909&fields=name,first_name,last_name,email,gender,verified resulted in a 400 Bad Request response: {"error":{"message":"An active access token must be used to query information about the current user.","type":"OAuthExce (truncated...)
But it make an exception about the token.
Someone have any idea to solve that?
Thank you!

Phalcon uniqueness on update

folks. The uniqueness validator in my form works as expected on adding new records, but on updating an exsisting record, it throws an error that the url already exists. It exists, in fact, but only in the current record.
Here is my controller:
$feed = Feeds::findFirst($id);
$feedForm = new FeedForm($feed, array('edit' => true));
if ($this->request->isPost() == true) {
$feedData = $this->request->getPost();
if ($feedForm->isValid($feedData, $feed)) {
if ($feed->save()) {
$this->flash->success("Feed successfuly updated.");
} else {
$this->flash->error("Update failed.");
}
} else {
foreach ($feedForm->getMessages() as $message) {
$this->flash->error($message);
}
}
}
And my form class:
class FeedForm extends FormBase {
public $options;
public function initialize($entity = null, $options = null) {
parent::initialize();
$this->setEntity($entity);
$this->options = $options;
$status = new Radio('status');
$status->addValidator(
new PresenceOf(
array(
'message' => 'The status is required.'
)
));
$this->add($status);
$name = new Text('name');
$name->addValidator(
new PresenceOf(
array(
'message' => 'The name is required.'
)
));
$name->addValidator(
new StringLength(
array(
'max' => 50,
'messageMaximum' => 'The name you entered is too long.'
)
));
$this->add($name);
$xml = new Text('xml');
$xml->addValidator(
new PresenceOf(
array(
'message' => 'The URL address is required.'
)
));
$xml->addValidator(
new StringLength(
array(
'max' => 2048,
'messageMaximum' => 'The URL address you entered is too long.'
)
));
$xml->addValidator(
new Url(
array(
'message' => 'The URL you entered is invalid.'
)
));
$xml->addValidator(
new Uniqueness(
array(
'model' => 'Sravnisite\Admin\Models\Feeds',
'table' => 'feeds',
'column' => 'xml',
'message' => 'The entered URL address already exists.'
)
));
$periodOptions = array();
for ($i = 4; $i <= 24; $i++) {
array_push($periodOptions, $i);
}
$this->add($xml);
$period = new Select('period', $periodOptions);
$period->addValidator(
new PresenceOf(
array(
'message' => 'The period is required.'
)
));
$this->add($period);
$shopID = new Select('shop_id', Shops::find(), array('using' => array('id', 'name')));
$shopID->addValidator(
new PresenceOf(
array(
'message' => 'The shop is required.'
)
));
$this->add($shopID);
}
}
Any ideas?
The form validation doesn't know to ignore the record you are updating - so for uniqueness it finds the record you're trying to update and gives an error. You could do some complicated find logic to keep the uniqueness validation in the form but it is better moved to the model. Your result would end up something like:
Controller
$feed = Feeds::findFirst($id);
$feedForm = new FeedForm($feed, array('edit' => true));
if ($this->request->isPost() == true) {
$feedData = $this->request->getPost();
if ($feedForm->isValid($feedData, $feed)) {
if ($feed->save()) {
$this->flash->success("Feed successfuly updated.");
} else {
$this->flash->error("Update failed.");
// Get each of the validation messages from the model
foreach ($feed->getMessages() as $message) {
$this->flash->error($message);
}
}
} else {
foreach ($feedForm->getMessages() as $message) {
$this->flash->error($message);
}
}
}
Form
// Exactly the same as you currently have but without the Uniqueness Validator
Model
class Feeds extends Phalcon\Mvc\Model
/**
* Validate that xml URLs are unique
*/
public function validation()
{
$this->validate(new Uniqueness(array(
"field" => "xml",
"message" => "The url must be unique."
)));
return $this->validationHasFailed() != true;
}

How to do add and edit in same method in codeigniter controller

I am new to codeigniter and trying to add and edit a category with the same method add.
Here is my add method:
public function add($category_id = FALSE)
{
$this->load->helper('form');
$this->load->library('form_validation');
if($category_id === FALSE)
{
$this->data['mode'] = 'insert';
$this->data['hidden_fields'] = array('mode' => $this->data['mode']);
}
else
{
$this->data['mode'] = 'update';
$this->data['category_details'] = $this->category_model->get_category_details($category_id);
$this->data['category_id'] = isset($this->data['category_details'][0]['category_id']) ? $this->data['category_details'][0]['category_id'] : '';
$this->data['hidden_fields'] = array('category_id' => $this->data['category_id'], 'mode' => $this->data['mode']);
}
// Fill the form data for edit.
$this->data['name'] = isset($this->data['category_details'][0]['name']) ? $this->data['category_details'][0]['name'] : set_value('name');
$this->data['description'] = isset($this->data['exam_category_details'][0]['description']) ? $this->data['category_details'][0]['description'] : set_value('description');
$this->data['status_y'] = (isset($this->data['category_details'][0]['status']) && $this->data['category_details'][0]['status'] === 'Y') ? 'checked="checked"' : set_radio('status', 'Y', TRUE);
$this->data['status_n'] = (isset($this->data['category_details'][0]['status']) && $this->data['category_details'][0]['status'] === 'N') ? 'checked="checked"' : set_radio('status', 'Y');
// set the validation rules
$validation_rules = array(
array(
'field' => 'name',
'label' => 'Name',
'rules' => 'trim|required|min_length[5]|max_length[20]|xss_clean'
),
array(
'field' => 'description',
'label' => 'Description',
'rules' => 'trim|min_length[5]|max_length[256]|xss_clean'
)
);
$this->form_validation->set_rules($validation_rules);
// check if validation fails or upload logo fails
if ($this->form_validation->run() === FALSE)
{
$this->data['validation_errors'] = validation_errors();
$this->load->view($this->config->item('templates_path').'header', $this->data);
$this->load->view($this->config->item('templates_path').'sidebar_content', $this->data);
$this->load->view($this->config->item('templates_path').'navigation', $this->data);
$this->load->view('add_category', $this->data);
$this->load->view($this->config->item('templates_path').'footer');
}
else
{
$id = $this->category_model->update_category();
if($id !== FALSE && is_numeric($id))
{
$this->session->set_flashdata('msg_success', 'Operation Successful');
redirect('/exams/exam_category/');
}
else
{
// update exam category failed some where
log_message('error', 'Update exam category failed', TRUE);
show_error("Unable to Update exam category : ".$id);
}
}
}
The above method works fine for add and edit category, but if form validation fails I am loosing my form default values in both add and edit cases. I have used set_value method of codeignitor. How can I retain the form input values in case of validation fails?

InputFilter "setRequired" not working for html5 multiple

I'm having hard time with a weird behaviour of fileinput.
This is my form:
namespace Frontend\Form;
use NW\Form\Form;
use Zend\InputFilter;
use Zend\Form\Element;
use Zend\ServiceManager\ServiceManager;
use Zend\ServiceManager\ServiceManagerAwareInterface;
class EnrollStructure extends Form implements ServiceManagerAwareInterface
{
protected $sm;
public function __construct($name=null) {
parent::__construct("frmEnrollStructure");
$this->setAttribute("action", "/registrazione_struttura/submit")
->setAttribute('method', 'post')
->setAttribute("id", "iscrizione_struttura")
->setAttribute("class", "form fullpage");
$this->addInputFilter();
}
public function init()
{
$structureFs = $this->sm->get('Structure\Form\Fieldsets\Structure');
$structureFs->setUseAsBaseFieldset(true);
$structureFs->remove("id")
->remove("creationTime")
->remove("latLon");
$file = new Element\File("images");
$file->setAttribute('multiple', true);
$this->add($structureFs)->add($file);
$this->add(array(
'name' => 'submit',
'attributes' => array(
'type' => 'submit',
'value' => 'Iscriviti',
'id' => 'sbmtEnrollStructure',
'class' => 'submit_btn'
),
));
$this->setValidationGroup(
array(
'structure' =>
array(
'companyname',
'vatNumber',
'addressStreet',
'addressZip',
'addressCity',
'addressRegion',
'fax',
'publicPhone',
'publicEmail',
'website',
'status',
'ownerNotes',
'category',
'subcategory',
"facilities",
"agreeOnPolicy",
"agreeOnPrivacy",
"subscribeNewsletter",
"contact" => array("name", "surname", "email", "role", "phone"),
),
"images"
));
}
/**
* Set service manager
*
* #param ServiceManager $serviceManager
*/
public function setServiceManager(ServiceManager $serviceManager)
{
$this->sm = $serviceManager;
}
public function addInputFilter()
{
$inputFilter = new InputFilter\InputFilter();
// File Input
$fileInput = new InputFilter\FileInput('images');
$fileInput->setRequired(true);
$fileInput->getValidatorChain()
->attachByName('filesize', array('max' => "2MB"))
->attachByName('filemimetype', array('mimeType' => 'image/png,image/x-png,image/jpg,image/jpeg'))
->attachByName('fileimagesize', array('maxWidth' => 2048, 'maxHeight' => 2048));
$inputFilter->add($fileInput);
$this->setInputFilter($inputFilter);
}
}
Basically, I mainly use a fieldset which contains most of the data I request to the user, plus a File input field.
This is the Fieldset Structure: (most important parts..)
use Zend\Form\Element;
use Zend\Form\Fieldset;
use Zend\InputFilter\InputFilterProviderInterface;
use Zend\ServiceManager\ServiceManager;
use Zend\ServiceManager\ServiceManagerAwareInterface;
use DoctrineModule\Stdlib\Hydrator\DoctrineObject as DoctrineHydrator;
use Zend\Validator\Identical;
use Zend\Validator\NotEmpty;
use Zend\Validator\Regex;
use Zend\Validator\StringLength;
class Structure extends Fieldset implements InputFilterProviderInterface, ServiceManagerAwareInterface
{
protected $sm;
public function __construct()
{
parent::__construct('structure');
}
public function init()
{
$this->setHydrator(new DoctrineHydrator($this->_entityManager(),'Structure\Entity\Structure'));
$this->setObject($this->sm->getServiceLocator()->get("Structure_Structure"));
$id = new Element\Hidden("id");
$name = new Element\Text("companyname");
$name->setLabel("Ragione Sociale");
...........
}
public function getInputFilterSpecification()
{
return array
(
"id" => array(
"required" => false,
),
"companyname" => array(
"required" => true,
"validators" => array(
array('name' => "NotEmpty", 'options' => array("messages" => array( NotEmpty::IS_EMPTY => "Inserire la ragione sociale")))
),
),
.....
}
}
This is my controller:
public function submitAction()
{
try {
$this->layout("layout/json");
$form = $this->getForm('Frontend\Form\EnrollStructure');
//$form->addInputFilter();
$structure = $this->getServiceLocator()->get("Structure_Structure");
$viewModel = new ViewModel();
$request = $this->getRequest();
if ($request->isPost())
{
$post = array_merge_recursive
(
$request->getPost()->toArray(),
$request->getFiles()->toArray()
);
$form->setData($post);
if ($form->isValid())
{
$structure = $form->getObject();
$contact = $structure->getContact();
$this->getServiceLocator()->get('Structure_ContactService')->save($contact);
$files = $request->getFiles()->toArray();
if(isset($files['images']))
{
$count = 3;
foreach($files['images'] as $pos => $file)
{
$fpath = $this->getServiceLocator()->get('RdnUpload\Container')->upload($file);
if(!empty($fpath))
{
if(--$count ==0) break;
$asset = $this->getServiceLocator()->get("Application_AssetService")->fromDisk($fpath, $file['name']);
$this->getServiceLocator()->get("Application_AssetService")->save($asset);
$structure->addImage($asset);
}
}
}
$this->getServiceLocator()->get('Structure_StructureService')->save($structure);
$retCode = RetCode::success(array("iscrizione_struttura!" => array("form_submit_successfull")), true);
}
else
{
$messages = $form->getMessages();
if(empty($messages))
$retCode = RetCode::error(array("iscrizione_struttura" => array("need_at_least_one_file" => "missing file")), true);
else
$retCode = RetCode::error(array("iscrizione_struttura" => $messages), true);
}
$viewModel->setVariable("retcode", $retCode);
return $viewModel;
}
} catch(Exception $e)
{
throw $e;
}
}
The strange thing is that if i remove from the field "images" the "multiple" attribute everything works fine, causing the form not to validate and i get this message:
[images] => Array
(
[fileUploadFileErrorFileNotFound] => File was not found
)
While, if i set the attribute multiple, and the user does not upload a file i get no error, but the form gets invalidated (this is the reason for this "bad" code in my controller:)
$messages = $form->getMessages();
if(empty($messages))
$retCode = RetCode::error(array("iscrizione_struttura" => array("need_at_least_one_file" => "missing file")), true);
else
$retCode = RetCode::error(array("iscrizione_struttura" => $messages), true);
I found the problem was caused by the Jquery form plugin, without it it works fine. :( In case somebody needs, I think the correct action code can be found here (I haven't tryied it anyway)
https://github.com/cgmartin/ZF2FileUploadExamples/blob/master/src/ZF2FileUploadExamples/Controller/ProgressExamples.php

ZEND, Edit form

I have a Zend form to add something to database. And then I want to use this form to edit what I added to the databese. Is any possibility to use this form (fill it from database and display it???)
I have this in my controller:
public function editAction() {
if (Zend_Auth::getInstance()->hasIdentity()) {
try {
$form = new Application_Form_NewStory();
$request = $this->getRequest();
$story = new Application_Model_DbTable_Story();
$result = $story->find($request->getParam('id'));
// $values = array(
// 'title' => $result->title,
// 'story' => $result->story,
// );
if ($this->getRequest()->isPost()) {
if ($form->isValid($request->getPost())) {
$data = array(
'title' => $form->getValue("title"),
'story' => $form->getValue("story"),
);
$where = array(
'id' => $request->getParam('id'),
);
$story->update($data, $where);
}
}
$this->view->form = $form;
$this->view->titleS= $result->title;
$this->view->storyS= $result->story;
} catch (Exception $e) {
echo $e;
}
} else {
$this->_helper->redirector->goToRoute(array(
'controller' => 'auth',
'action' => 'index'
));
}
}
In my view:
<?php
try
{
$tmp = $this->form->setAction($this->url());
//$tmp->titleS=$this->title;
//$tmp->storyS=$this->story;
//echo $tmp->title = "aaaaa";
}
catch(Exception $e)
{
echo $e;
}
And when I try to change something in this view I mean give any value different then NULL I have error that I can not do it so is any possibility to reuse this form? Or not?
Thanks!
Zend_Form has method populate(), which sets values of the form based on array data. So just do:
$form->populate($result->current()->toArray());
and form will be populated based on keys from array.