I want to update a product in laravel, but it does not work properly,
my Controller's update method looks like this:
public function updateProduct(Request $request)
{
# Get input values
$data = $request->all();
$productID = $data['id'];
$product = Product::find($productID);
$product->fill($data);
# Validate input
$validator = Validator::make($request->all(), Product::$rules);
if ($product->save())
{
# save language selection
$lsCounter = 0;
$langSelecName = $request->input('language');
$langSelecFile = $request->file('language');
if ($langSelecName)
{
$projectPath = $dProjectPath . "languages";
foreach ($langSelecName as $langSelecNameKey => $langSelecNameValue)
{
if ($langSelecFile[$lsCounter]['input_vid_lang'] != null)
{
$langVidFileName = $langSelecFile[$lsCounter]['input_vid_lang']->getClientOriginalName();
$languages = new Language();
$languages['short_name'] = $langSelecNameValue;
$languages['input_video'] = $projectLangPath . '\\' . $langVidFileName;
$languages->product()->associate($product);
$langData = [
'languagesShortName' => $languages['short_name'],
'languagesInputVideo' => $languages['input_video']
];
$intProductID = intval($productID);
$findLangId = $languages->find($intProductID);
$findLangId->fill($langData);
if ($languages->save())
{
$langSelecFile[$lsCounter]['input_vid_lang']->move($projectLangPath, $langVidFileName);
}
}
$lsCounter++;
}
}
} else {
return redirect()->route('editProduct', $productID)->with('message', 'Error')->withInput();
}
I get the following error after I try to update it, the error looks like this:
Call to a member function fill() on null
And it points to this line:
$findLangId->fill($langData);
I appreciate some help, thank you.
Edit
Ok people said that $intProductRomID is null, but I get the correct product id if I dd($intProductRomID).
As per the comments, the following line is return null:
$findLangId = $languages->find($intProductRomID);
Meaning this won't be valid:
$findLangId->fill($langData);
In other words, if you were to var_dump out $languages->all(), you will not find $intProductRomID in there. If you are unsure, swap out ->find with ->findOrFail() (which, considering you aren't doing any error catching or checking, you probably should be using it instead).
Edit
After some conversation in the comments, it has been established that the wrong field was being used for reference. Use a where instead:
$languages->where('product_rom_id', $intProductRomID);
Related
I am receiving an error from running the below code?
(1/1) ErrorException
Creating default object from empty value
Code:
public function setServiceSetting(Request $request) {
if (!$request->has('setting_key') ||
!$request->has('setting_value')) {
return $this->getScriptingResponse();
}
$settingKey = $request->input('setting_key');
$settingValue = $request->input('setting_value');
$settings = WebsiteSettings::first();
if ($settings == null) {
return;
}
$setting->$settingKey = $settingValue;
$settings->save();
}
Error Line:
$setting->$settingKey = $settingValue;
I know the column exists, below anyone suggests that. I also know both parameters are non-null.
I think that this is incorrect
$settings->$settingKey = $settingValue;
try this:
$settings->settingKey = $settingValue;
I have situation where codeigniter shows database Error Number 1048. It seems Values NULL but when I try to check it usign var_dump($_POST) Values are not NULL.
Controller : Jurusan.php
public function simpan()
{
$this->form_validation->set_rules('code','Kode','required|integer');
$this->form_validation->set_rules('jurusan','Jurusan','required');
$this->form_validation->set_rules('singkatan','Singkatan','required');
$this->form_validation->set_rules('ketua','Ketua','required');
$this->form_validation->set_rules('nik','NIK','required|integer');
$this->form_validation->set_rules('akreditasi','Akreditasi','required');
if($this->form_validation->run() == FALSE)
{
$isi['content'] = 'jurusan/form_tambahjurusan';
$isi['judul'] = 'Master';
$isi['sub_judul'] = 'Tambah Jurusan';
$this->load->view('tampilan_home',$isi);
} else {
$this->model_security->getSecurity();
$key = $this->input->post('code');
$data['kd_prodi'] = $this->input->post['code'];
$data['prodi'] = $this->input->post['jurusan'];
$data['singkat'] = $this->input->post['singkatan'];
$data['ketua_prodi'] = $this->input->post['ketua'];
$data['nik'] = $this->input->post['nik'];
$data['akreditasi'] = $this->input->post['akreditasi'];
$this->load->model('model_jurusan');
$query = $this->model_jurusan->getdata($key);
if($query->num_rows()>0)
{
$this->model_jurusan->getupdate($key,$data);
} else {
$this->model_jurusan->getinsert($data);
}
redirect('jurusan');
}
}
Model : model_jurusan.php
class Model_jurusan extends CI_model {
public function getdata($key)
{
$this->db->where('kd_prodi',$key);
$hasil = $this->db->get('prodi');
return $hasil;
}
public function getupdate($key,$data)
{
$this->db->where('kd_prodi',$key);
$this->db->update('prodi',$data);
}
public function getinsert($data)
{
$this->db->insert('prodi',$data);
}
}
Here is the error shown :
Here is the database structure :
You have a wrong syntax in these lines:
$key = $this->input->post('code');
$data['kd_prodi'] = $this->input->post['code']; // <-- use ('code')
$data['prodi'] = $this->input->post['jurusan']; // <-- use ('jurusan')
Change this to
$this->input->post['array_key'];
this
$this->input->post('array_key');
Read : Input Class in Codeigniter
Well the problem lies in your way of accepting input parameters.
$this->input->post
is a method which accepts the variable name, not an array. So all the input parameters need to be passed as a function parameter to post method. These lines need to be altered to.
$data['kd_prodi'] = $this->input->post('code');
$data['prodi'] = $this->input->post('jurusan');
$data['singkat'] = $this->input->post('singkatan');
$data['ketua_prodi'] = $this->input->post('ketua');
$data['nik'] = $this->input->post('nik');
$data['akreditasi'] = $this->input->post('akreditasi');
Hope this solves the problem.
EDIT:
You did a var_dump($_POST) which works as it is supposed to and it will read the values of the post parameters. So either you fetch the parameters from $_POST array, or you use the $this->input->post() method. But I would suggest using the $this->input->post() method as it provides additional sanitization such as xss attack handling etc, which could be turned on an off from the config.
i have tried your code...it works. I think there some mistakes in your <input> tags, You must use <input name=""> not <input id=""> or something else. Hope it can help you out
You are try to get value from post is wrong. You should use at this way
$_POST['array value'];
I'm working on a php project but I have a problem with the database , I use this code to get data from the database :
public function getSeenAction(Request $request , $notificationId)
{
$sessionId = $request->headers->get('SessionID');
if( $sessionId == null )
{
//return new Response("Unauthorized",401);
}
$notificationRepo = $this->getDoctrine()->getRepository('MegasoftEntangleBundle:Notification');
$notification = $notificationRepo->findOneById($notificationId);
if($notification == null)
{
return new Response("Notification not found" ,404);
}
$seen = $notification->getSeen();
$response = new JsonResponse();
$response->setdata(array('seen'=>$seen));
$response->setStatusCode(200);
return $response;
}
I tried the same code with other tables and it worked , but whenever I retrive data from the Notification table it always give null , although the table contains the data.
$notificationRepo = $this->getDoctrine()->getRepository('MegasoftEntangleBundle:Notification');
$notification = $notificationRepo->findAll();
var_dump(notification);
Is this code returns you something ? Probably the code of your NotificationRepository.php is not good, can you put it on ?
Try using find instead of findOneById if you just want to find record by Id.
On the other hand if you want to use findOneBy the passed argument for criteria should be an array.
$result = $notificationRepo->find($notificationId);
Or
$result = $notificationRepo->findOneBy(array('id' => $notificationId));
Or
make sure you have a proper code for findOneById in your NotificationRepository.php file
Then you can check
if (!empty($result)) { ... }
I have a code here that, has to search and post back information selected in a table above the add button, the search works but im having a problem with the post back to the table function. These are the lines it shows to have errors.
C:\xampp\htdocs\portal-gep-2\application\models\ServiceProviders.php(68): Zend_Db_Table_Abstract->fetchRow(Object(Zend_Db_Table_Select))
public function getName($id)
{
$select = $this->select();
$select->where('service_provider_id = ?', $id);
$result = $this->fetchRow($select); //this line
return $result['service_provider_name'];
}
#6 C:\xampp\htdocs\portal-gep-2\application\modules\admin\controllers\AjaxController.php(1104): Model_ServiceProviders->getName(NULL)
public function postserviceproviderAction()
{
$form = new Form_IndustrialTable();
$this->view->form = $form;
if(!$form->isValid($_POST))
{
$values=$form->getValues();
}
$sp = $this->getRequest()->getPost('serviceprovider', null);
$mdlserviceprovider = new Model_ServiceProviders();
$serviceprovider = $mdlserviceprovider ->getName($id); //this line
$rtn_array= array( 'sp' => $sp,
'serviceprovider ' => $serviceprovider);
$this->_helper->layout->disableLayout();
$this->_helper->viewRenderer->setNoRender();
echo Zend_Json::encode($rtn_array);
}
You don't put any initial value to $id so it's null which causes error.
You want SQL query to look something like SELECT * FROM service_providers WHERE service_provider_id = 50, but for this you have to provide id which you want to find (50 in this example). You need to add some value to variable $id before using in $select->where('service_provider_id = ?', $id);, but your code you never put any value to variable $id.
If I'm guessing your idea then you need to change line:
$serviceprovider = $mdlserviceprovider ->getName($id);
to:
$serviceprovider = $mdlserviceprovider ->getName($sp);
Also this part of your code probably unnecessary as it does nothing:
$form = new Form_IndustrialTable();
$this->view->form = $form;
if(!$form->isValid($_POST))
{
$values=$form->getValues(); //you never use $values
}
Hi all I'm using zend framework (but I think this is irrelevant) and php5 and I just want to modify an object of an object
public function saveSite($post) {
$form = new Diff_Form_Download();
$subform = new Diff_Form_DownloadSubform();
$form = $this->view->form;
$newSite = 0;
$sitesRecord = new Diff_Model_Sites();
$debugString = null;
if (is_array($post)) {
$subform = $this->getSubformByPost($post);
$debugString = $subform->getContent();
echo $debugString;
//new site instertion
if (is_null($subform)) {
$subform = $form->getSubForm('NewSite');
$newSite = 1;
}
$values = reset($subform->getValues());
$sitesRecord = Doctrine_Core::getTable('Diff_Model_Sites')->findOneBy('idSite', $values['idSite']);
if ($sitesRecord) {
$sitesRecord->idSite = $values['idSite']; //useless but necessary to make Doctrine understand to use update?
} else { //if the record is not present instantiate a new object (otherwise save() will not work
$sitesRecord = new Diff_Model_Sites();
}
$sitesRecord->content = $subform->getContent(); //$values['content'];
$sitesRecord->newHtml = $subform->getContent();
$sitesRecord->url = $values['url'];
$sitesRecord->shortName = $values['shortName'];
$sitesRecord->lastChanged = date("Y-m-d H:i:s");
$sitesRecord->pollingHours = $values['pollingHours'];
$sitesRecord->minLengthChange = $values['minLenghtChange'];
if (Zend_Auth::getInstance()->hasIdentity()) { //save the owner
$sitesRecord->idOwner = Zend_Auth::getInstance()->getIdentity()->idOwner; //retrieve the owner
$sitesRecord->save();
} else {
throw new Exception("your session have expired: \n please login again");
}
}
}
/**
* return the calling subform
* #param type $post
* #return type
*/
public function getSubformByPost($post) {
$form = new Diff_Form_Download();
$form = $this->view->form;
$subform = new Diff_Form_DownloadSubform();
$subformName = "site" . $post['idSite'];
$subform = $form->getSubForm($subformName);
return $subform;
}
public function refreshOneDiff($post) {
$debugString;
if (is_array($post)) {
$form = new Diff_Form_Download();
$form = $this->view->form;
$subform = new Diff_Form_DownloadSubform();
$subform = $this->getSubformByPost($post);
if (!$subform)
$subform = $this->view->form->getSubformByPost('NewSite');
$url = $subform->getUrl();
$idSite = $subform->getIdSite();
$crawler = new Crawler();
$newpageContent = $crawler->get_web_page($url);
$siteRecord = new Diff_Model_Sites();
$siteRecord = $subform->getSiteRecord();
if ($siteRecord) //check if the record is not null
$oldpageContent = $siteRecord->get('content');
else
$oldpageContent = null;
$differences = $this->getDiff($oldpageContent, $newpageContent);
if (!is_null($differences)) {
$siteRecord->content = $newpageContent;
$subform->setContent($newpageContent);
$subform->setContentDiff($differences);
$subform->setSiteRecord($siteRecord);
$subform = $this->getSubformByPost($post);
$debugString = $subform->getContent();
}
//echo $debugString;
$sitePresence = Doctrine_Core::getTable('Diff_Model_Sites')->findOneBy('idSite', $idSite);
if ($sitePresence) {
//$this->saveSite($post);
$this->debugtry($post);
}
} else {
}
}
Basically what I'm doing here is:
1) grab a the form from the view
2) grab a subform from the form (let's call it SubformX)
3) grab an object "siteRecordX" from SubformX
4) change a value of "siteRecordX"
5) call a function saveRecord()
6) In this function regrab the same SubformX and echoing the value of the object siteRecordX
Surprisingly if i change a variable of SubformX it will stay that way, if I change a variable of an object of SubformX it will remain unchanged (if I retrieve SubformX).
It looks like, even if SubformX is passed by reference it is not the same for it's subobjects, wich are passed by value and so they disappear changing the context of the function.
Can you please help me?
Thanks
EDIT
I still cannot solve this issue nor understand it:
This is the constructor of the subform:
public function __construct($site = null, $options = null) {
if ($site instanceof Diff_Model_Sites) {
$this->_shortName = $site->get('shortName');
$this->_url = $site->get('url');
$this->_content = $site->get('content');
$this->_idSite = $site->get('idSite');
$this->_siteRecord = $site;
$this->_lastChanged = $site->get('lastChanged');
}parent::__construct($options);}
while this is the function of SubformX i use to set the value.
public function setContent($contentText) {
$this->_siteRecord->content = $contentText;
$this->_content = $contentText;
}
and this is the function of the subform that I call to get the value
public function getContent() {
if (isset($this->_siteRecord)) {
//return $this->_content;
return $this->_siteRecord->content;
}
}
with the commented line I'm able to retrieve the updated value, not with the second.
This is a real mystery to me because i set and get them exactly the same way at exactly the same point and i cannot understand the difference.
Your _siteRecord property is an ORM object (Doctrine, it appears). So its data may have some behaviors that are not standard for a reference-type object. It surely has some override of __get and __set. It also employs caching. These things are necessary to keep the database-model interaction working properly, but they can confuse what should be a reference and value types. (See: http://www.codinghorror.com/blog/2006/06/object-relational-mapping-is-the-vietnam-of-computer-science.html)
P.S.: in your constructor you use:
$this->_content = $site->get('content');
$this->_siteRecord = $site;
but in your getContent() you use:
$this->_siteRecord->content;
That difference might be part of the problem.
Thank you all guys. It was Doctrine caching.
I have not investigated further the problem, but after getting rid of Doctrine everything works fine.
I have lost one entire day after this issue.
Moreover today I have lost another day for another curious problem related to Doctrine.
It seems that each time you gather data from your db Doctrine decode them for you (just like the php function utf8_decode($data).
Of course if you get the data and then put it back in the db again it will result in a total mayhem of coding and decoding.
This is enough. I still think that ORM are great programming tools but simply Doctrine is not.
I will not rest in peace since I'll have it eliminated from my program.
I will use Zend_Db library instead. Which I have mostly already done without regret and without facing the above-mentioned Doctrine's problems.
Again thanks to Seth Battin and Dave Random for the help and patience to understand my noob-coding.