Drupal node_save is not saving fields - drupal-7

I have just stumbled upon very strange behaviour. In my code I am saving new node with some fields. I must say this used to work perfectly well. However now it just stopped working. I use the devel module to print out the content of objects and variables and this is my code:
dsm($node);
node_save($node);
dsm($node);
The first dsm() function displays node object as I created it and as it is supposed to be. The second dsm() function displays entirely correct node object with nid populated, fields content, etc... However, none of the fields is saved in database although there is new record in {node} table. Also, node_save does not generate any kind of error.
Any idea what is happening here?
This is the function storing the node:
function manhattan_incident_save($data) {
if ($data['nid']) {
$node = node_load($data['nid']);
manhattan_compare_changes($node, $data);
}
else {
$node = new stdClass();
$node->type = 'incident';
node_object_prepare($node);
$node->title = manhattan_create_incident_id();
$node->language = LANGUAGE_NONE;
}
$node->field_incident_popis[$node->language][0]['value'] = $data['field_incident_popis'];
$node->field_incident_popis[$node->language][0]['safe_value'] = check_plain($data['field_incident_popis']);
$node->field_incident_agent[$node->language][0]['uid'] = isset($data['field_incident_agent'])?intval($data['field_incident_agent']):NULL;
$node->field_incident_zdroj[$node->language][0]['tid'] = intval($data['field_incident_zdroj']);
$node->og_group_ref[$node->language][0]['target_id'] = $data['field_incident_oblast']?intval($data['field_incident_oblast']):variable_get('manhattan_public_form_default_area_nid', NULL);
$node->field_incident_riesitel[$node->language][0]['uid'] = isset($data['field_incident_riesitel'])?intval($data['field_incident_riesitel']):NULL;
$node->field_incident_typ[$node->language][0]['tid'] = intval($data['field_incident_typ']);
$node->field_incident_doplnenie[$node->language][0]['nid'] = intval($data['field_incident_doplnenie']);
$node->field_incident_sposob_kontaktu[$node->language][0]['value'] = $data['field_incident_sposob_kontaktu'];
$node->field_incident_dovod_vzniku[$node->language][0]['tid'] = intval($data['field_incident_dovod_vzniku']);
if ($data['field_incident_suvisiaci_zaznam']) {
foreach ($data['field_incident_suvisiaci_zaznam'] as $file) {
$result = manhattan_save_files($file);
if ($result) {
$node->field_incident_suvisiaci_zaznam[$node->language][] = array('nid' => $result);
}
}
}
// now create/save the customer
if (function_exists('customer_customer_save')) {
$customer = $data;
$customer['nid'] = $data['field_incident_customer'];
$result = customer_customer_save($customer);
if ($result) {
watchdog('upvs', $result['message'], array(), WATCHDOG_NOTICE);
}
else {
watchdog('upvs', t('There was a problem with saving customer %nid'), array('%nid' => $data['nid']), WATCHDOG_ERROR);
}
}
// now we store nid of saved customer to the node object
$node->field_incident_customer[$node->language][0]['nid'] = $result['nid'];
dsm($node);
node_save($node);
dsm($node);
if ($data['nid']) {
watchdog('upvs', t('Incident number %title has been succesfully saved.'), array('%title' => $node->title), WATCHDOG_NOTICE);
}
else {
watchdog('upvs', t('Incident number %title has been succesfully created.'), array('%title' => $node->title), WATCHDOG_NOTICE);
}
return $node;
}

Related

foreach by quantity in laravel

I develop a ticketing system which user have to choose the quantity of ticket category. I want to save the record to database by the total of quantity. But it seems to be failed. I end up only save the record by category id. Here is the result when I try to return it.
and this is my code in controller.
public function ticket_checkout(Request $request)
{
$ctg_id = $request->cat_id;
$price = $request->price;
$name = $request->name;
$qty = $request->qty;
// return count($qty);
$data = [];
$i = 0;
foreach($qty as $item){
if($qty[$i] != 0){
$data[] = [
"ctg_id" => $ctg_id[$i],
"price" => $price[$i],
"qty" => $item,
];
}
$i++;
}
return $data;
Ticket_checkout::insert($data);
// return $qty;
return view('ticket.index', compact('data','qty'));
}
I wonder if I missing something here? I tried to do looping 'for' by quantity inside the 'foreach' but it seems not working too.

PUT request with formData could not update using react.js and laravel

I am not receiving formdata in the Api endpoint which is being sent by fetch and PUT method.
I used the POST method and it worked out which i think is not recommended for updating.
I have react running on localhost:3000 and the laravel-API running on localhost:5000.
This is the route in API
Route::put('updateSlide/{id}', 'SlidesController#updateSlide');
This is what is in the controller
public function updateImage(Request $request, int $id)
{
$image = $this->slideRepo->findSlideById($id)->image;
if ($image) {
$result = Storage::disk('ucmp')->delete($image);
}
if ($request->hasFile('image') && $request->file('image') instanceof UploadedFile) {
return $this->slideRepo->saveCover($request->file('image'));
} // return response()->json($data);
// data is an array (note)
return null;
}
public function updateSlide(Request $request, int $id)
{
$imageUrl=$this->updateImage($request, $id);
return response()->json($this->slideRepo->updateSlide([
'caption' => $request['caption'],
'image' => $imageUrl,
'url' => $request['url']
],$id));
}
This is the function sending to fetch
export const updateSlideApi = (token, _slide, id) => {
return {
url: `${BASE_URL}/api/updateSlide/${id}`,
opt: API.requestOptions("PUT",token,null,{ body: _slide }, true)
};
};
In my header i do not have the content-type.
I expect json data from the laravel API function but am having an error, " Can only throw objects"
PHP does not parse the body of a PUT request.
Use POST and add parameter _method with value PUT.
PHP put has given me tough time, use this function will save your time parsing it else method:
function parsePutRequest()
{
// Fetch content and determine boundary
$raw_data = file_get_contents('php://input');
$boundary = substr($raw_data, 0, strpos($raw_data, "\r\n"));
// Fetch each part
$parts = array_slice(explode($boundary, $raw_data), 1);
$data = array();
foreach ($parts as $part) {
// If this is the last part, break
if ($part == "--\r\n") break;
// Separate content from headers
$part = ltrim($part, "\r\n");
list($raw_headers, $body) = explode("\r\n\r\n", $part, 2);
// Parse the headers list
$raw_headers = explode("\r\n", $raw_headers);
$headers = array();
foreach ($raw_headers as $header) {
list($name, $value) = explode(':', $header);
$headers[strtolower($name)] = ltrim($value, ' ');
}
// Parse the Content-Disposition to get the field name, etc.
if (isset($headers['content-disposition'])) {
$filename = null;
preg_match(
'/^(.+); *name="([^"]+)"(; *filename="([^"]+)")?/',
$headers['content-disposition'],
$matches
);
list(, $type, $name) = $matches;
isset($matches[4]) and $filename = $matches[4];
// handle your fields here
switch ($name) {
// this is a file upload
case 'userfile':
file_put_contents($filename, $body);
break;
// default for all other files is to populate $data
default:
$data[$name] = substr($body, 0, strlen($body) - 2);
break;
}
}
}
return $data;
}

Symfony - saving array to database

I wrote a function where I get array of marks that i need to post to my database..
My function stores it in a filed row like:
And I need to pull just one per column individually like:
Here is my api call..
public function generate(Map $seatMap)
{
$layout = $seatMap->getSeatLayout();
$seats = [];
$layoutArray = json_decode($layout, true);
$columns = range('A', 'Z');
foreach($layoutArray as $index => $result)
{
$columnLetter = $columns[$index];
$letters = str_split($result);
$letterIndex = 1;
foreach($letters as $letterIndex => $letter) {
switch($letter) {
case 'e':
$seats[] = $columnLetter . $letterIndex;
$letterIndex++;
}
}
}
foreach($seats as $seat => $result) {
$result = new Seat();
$result->setName(json_encode($seats));
$this->em->persist($result);
$this->em->flush();
}
}
Any suggestions?
I think that problem is in the part where I need to store it to database..
If I understand you correctly, your issue is here:
foreach($seats as $seat => $result) {
$result = new Seat();
$result->setName(json_encode($seats));
$this->em->persist($result);
$this->em->flush();
}
}
You're indeed creating new Seat instance for every seat, but in this line:
$result->setName(json_encode($seats));
you still assign all (encoded) seats to every instance of Seat. What you want is to assign only the seat from current loop iteration, which is represented by $result variable.
So try with:
$result->setName($result);
You do not need json_encode here too.
If your array is like you say it it then try this
foreach($seats as $seat) {
$result = new Seat();
$result->setName($seat);
$this->em->persist($result);
$this->em->flush();
}

Get array data and insert into database

I'm trying to get the data in the array that came from another function(that function is extracting the data in the csv file) and when i tried calling the two fields from that array it shows an error that it is unidentified variables.
The $this->csv_process(); as shown on the function action() is the function that extracts the data from the csv file and stores it in an array which is successful since I tried checking it on var_dump();
I also named the two fields as $name and $email as shown below:
Function CSV_process()
public function csv_process()
{
/* variables for openning the csv file */
if (!in_array($extension, $allowed_ext)) {
$this->session->set_flashdata("message", "Sorry, CSV file only.");
} else {
if ($filesize > 0) {
$file = fopen($filename, "r");
$toWrite = array();
$error = false;
$col_size = 2;
$skip = 0;
while ($data = fgetcsv($file, 10000, ","))
{
$skip++;
if ($skip == 1) {
continue;
}
$numofcol = count($data);
if ($numofcol != $col_size ) {
$this->session->set_flashdata("message", "Column count exceeded or missing.");
} else {
$name1 = $data[0];
$name = str_replace("'", "''", $name1);
$email1 = $data[1];
$email = str_replace("'", "''", $email1);
$toWrite[] = [
'name' => $name,
'email' => $email
];
}
}
}
}
return $toWrite;
}
Function Action()
function action(){
$toWrite[] = $this->csv_process();
foreach ($toWrite as $arr) {
list($name, $email) = $arr;
//die(var_dump($arr));
$query = $this->db->query("SELECT * FROM import WHERE name ='$name' AND email = '$email'");
if ($query->num_rows() >= 1) {
} else {
if ($name == "" OR $email == "") {
} else {
if ((filter_var($email, FILTER_VALIDATE_EMAIL)) == FALSE ) {
} else {
$this->db->query("INSERT INTO import(name, email, created_date) VALUES('".$name."', '".$email."', '".date("Y-m-d h-i-s")."')");
$this->session->set_flashdata('message', 'SUCCESS YEAY');
redirect('Clean_csv/index');
}
}
}
$query->free_result();
}
}
Listing arrays doesn't seem to work for here, anyone knows how to extract the data array from $arr?
You don't need to extract the values. You can use each $arr in a bound query. It simplifies the syntax for the select query.
For inserting use CodeIgniter's insert() method. Again, the $arr can be used directly by adding the date to it before the insert is attempted.
I think this will work.
function action()
{
$toWrite[] = $this->csv_process();
foreach($toWrite as $arr)
{
$query = $this->db->query("SELECT * FROM import WHERE name=? AND email=?", $arr);
if($query->num_rows() >= 1)
{}
else
{
if($arr['name'] == "" OR $arr['email'] == "")
{}
else
{
if((filter_var($email, FILTER_VALIDATE_EMAIL)) == FALSE)
{}
else
{
$arr['created_date'] = date("Y-m-d h-i-s");
$this->db->insert("import", $arr);
$this->session->set_flashdata('message', 'SUCCESS YEAY');
//??? redirect('Clean_csv/index');
//Are you sure, you may still have more $arr in $toWrite to process - right?
}
}
}
$query->free_result();
}
}
You need to know what a terrible idea it is to repeatedly run database queries inside a loop. Even though you use free_result() it could be a massive drain on server resources. If your csv file has several thousand items you are severely stressing the database and the server.

cakephp: creating new records from other controller

I'm going to create 50 temp/dummy rows inside my model database. My problems is how can I create and save new records in my DB? Assume my model Random containts columns (id,randomValue,...).
public function addNew() {
$this->autoRender = false; // We don't render a view in this example
$moduleSize = 50;
$count = $moduleSize;
while ($count > 0) {
$random_number = rand(1000000000, 9999999999);
//check if duplicate
if ($this->checkIfDuplicateSerial($random_number)) {
//nothing to be done
} else {
$this->Random->create(array('randomValue' => $random_number));
$this->Random->save();
$this->Random->clear(); //to init new one
$count--;
}
}
$this->response->body('Inserted' . $moduleSize . 'Random Numbers');
}

Resources