Trouble insert date form to mysql in drupal 7 - mysql

hi im having little trouble at inserting date from drupal to mysql
here the code that i'm trying
.....
$form['kotak']['tgl'] = array(
'#type' => 'date',
'#title' => t('Tanggal'),
);
.....
function awal_form_submit($form,&$form_state){
global $user;
$entry = array(
'tanggal' => $form_state['values']['tgl'],
);
$tabel = 'jp_1';
$return = insert_form($entry,$tabel);
}
.....
function insert_form($entry,$tabel){
$return_value = NULL;
try {
$return_value = db_insert($tabel)
->fields($entry)
->execute();
}
.....
everytime i'm submit, error code like this
db_insert failed. Message = SQLSTATE[21S01]: Insert value list does not match column list: 1136 Column count doesn't match value count at row 1, query= INSERT INTO {jp_1} (tanggal) VALUES (:db_insert_placeholder_0_month, :db_insert_placeholder_0_day, :db_insert_placeholder_0_year)
any suggestion or correction?

From the mysql error it looks like the table you created has required fields (a columns Null property is set to 0, which means that there must be a value for tha column for every row you want to insert)
Check whether there are any columns which have null set to 0.
From your example I can't see what you're trying to achieve, but in many cases it's not necessary to write into db tables manually (using db_insert()) as you can get the same result easier by creating a content type (node type) which handles a lot of functionality for you.
I hope that helps, Martin

i'm finally managed to find the answer, all i need is download "Date" module and activate its "Date API". Here the code
.....
$datex = '2005-1-1';
$format = 'Y-m-d';
$form['kotak']['tgl'] = array(
'#type' => 'date_select',
'#default_value' => $datex,
'#date_format' => $format,
'#date_year_range' => '-10:+30',
'#title' => t('Tanggal'),
);
.....
function awal_form_submit($form,&$form_state){
global $user;
$entry = array(
'tanggal' => $form_state['values']['tgl'],
);
$tabel = 'jp_1';
$return = insert_form($entry,$tabel);
}
.....
function insert_form($entry,$tabel){
$return_value = NULL;
try {
$return_value = db_insert($tabel)
->fields($entry)
->execute();
}
.....
and now i have no problem delivering to mysql.
Hope that will help other drupal newbie developer like me. Thanks :D

Related

Check if a field is empty while importing data from Excel file in Laravel?

I am trying to import data from excel file into database tables in Laravel. I have successfully imported the data but If I mistakenly leave a field empty then I get error that column cannot be null. So I need check if the all necessary data is provided.
I use this code.
IndependentContractor::create(['staff_id' => $staff->id, 'address' => $excel_row['address'], 'longitude' => $excel_row['longitude'], 'latitude' => $excel_row['latitude'], 'tax_id' => $excel_row['tax_id'], 'business_name' => $excel_row['business_name'], 'person_incharge' => $excel_row['person_incharge'], 'phone_of_person_incharge' => $excel_row['phone_of_person_incharge'], 'general_manager' => $excel_row['general_manager'], 'phone_of_general_manager' => $excel_row['phone_of_general_manager']]);
I can use If() to check the data but I will have to repeat this in almost 7 places because there are 7 different tables in which data is being stored.
also if statement will look like this.
if(!empty($excel_row['address']) && !empty($excel_row['longitude']) && !empty($excel_row['latitude']) && !empty($excel_row['business_name']) and so on )
So is there any better way to achieve this?
Thanks.
you can try using looping, using the array_key, assumming database column name = excel column name
example :
$data = [];
foreach($excel_row as $key => $value){
if(!empty($excel_row[$key])){
$data[$key] = $excel_row[$key];
}else{
dd('empty column found'); //your code here
}
}
//if everything goes fine
IndependentContractor::create($data);
class UsersImport implements ToModel, WithUpserts
{
/**
* #return string|array
*/
public function uniqueBy()
{
return 'email';
}
if (!isset($row[0])) {
return null;
}
return new User([
'name' => $row[0],
]);
}

Laravel - Create or Update by defined attributes

I have this this table:
--Votes--
id: Integer
post_id: Integer
user_id: Integer
positive: Boolean
Now I would like to create a record only if it not exists. It is working until someone wants to click on dislike after he clicked on like(on the other side exactly equivalent).
For example someone likes a post a record will be created with positive=true. Now if the user clicks on the same post but this time on dislike, it will be created another record, but i want that it only updates the existing record.
Is there a simple solution?
Here is my Code to create the record:
$vote = Vote::firstOrCreate(array(
'post_id' => $request->input('post_id'),
'user_id' => Auth::user()->id,
'positive' => $request->input('positive')
));
Note: If someone knows how to do that, maybe he could show me how a deletion would be. For example someone clicks on like two times. The record should be created an deleted.
You can use updateOrCreate method:
public static function updateOrCreate(array $attributes, array $values = array())
{
$instance = static::firstOrNew($attributes);
$instance->fill($values)->save();
return $instance;
}
have a look: https://github.com/laravel/framework/blob/5.0/src/Illuminate/Database/Eloquent/Model.php#L605
EDIT:
Example
$attributes = [
'name' => 'Christian',
'email' => 'christian#example.com'
];
$values = [
'name' => 'Christian',
'email' => 'christian#example.com',
'phone' => '123456789'
];
MyModel::updateOrCreate($attributes, $values);
In the example above I will search if in my table I have an entry which match name and email, if it exists I will update the records, otherwise I will insert a new entry with the $values infos

updating a record mysql with zend framework 2

I want to update a record, in my case the records name is kindOfFood_vote
I don't quite understand yet how to update a specific record.
I did it this way, but it doesn't work so I assume it's wrong.
first a made a variable data where i store it :
$data = array(
'kindOfFood_name' => $food->kindOfFood_name,
'kindOfFood_votes' => $food->kindOfFood_votes += 1,
);
The insert query works fine, But maybe there can be something wrong with this line of code :
'kindOfFood_votes' => $food->kindOfFood_votes += 1,
This is were I insert or update :
if ($id == 0) {
if ($rowset->count() > 0) {
$this->tableGateway->update($data,array('kindOfFood_name' => $kindOfFood_name));
}else{
$this->tableGateway->insert($data);
}
}
I don't see the problem.
I would be very grateful if someone could help me with this.
Try -
$data = array(
'kindOfFood_name' => $food->kindOfFood_name,
'kindOfFood_votes' => new \Zend\Db\Sql\Expression('kindOfFood_votes + 1'),
);
For single record this would have worked -
$this->tableGateway->update(
array(
'kindOfFood_votes' => new \Zend\Db\Sql\Expression('kindOfFood_votes + 1')
),
array('kindOfFood_name' => $kindOfFood_name)
);

How can I insert data from a table from sql into a dropdown list in zend framework 2?

I need to insert multioptions to a dropdown list, options taken from a table from my database.
I created the elements like:
$this->add(array(
'name' => 'company',
'type' => 'Zend\Form\Element\Select',
//'multiOptions'=> $options,
'options' => array(
'label' => 'Company',
),
'attributes' => array(
'style' => "float:right;",
),
));
I want to choose from a dropdown list some values that are in a table in my database. For example I have the entity Contacts and I need to choose for the contact a company that is in a table named companies in the database.
After reading on zend framework's site, I tried using this code:
$params = array(
'driver'=>'Pdo_Mysql',
'host'=>'localhost',
'username'=>'root',
'password'=>'',
'dbname' =>'myDataBase'
);
$db = new \Zend\Db\Adapter\Adapter($params);
$sql= new Sql($db);
$select = $sql->select();
$select ->from('companies')
->columns(array('id','company_name'))
->order(" 'company_name' ASC");
I also read on some other sites that I could use a function:
$options = $sql->fetchPairs('SELECT id, name FROM country ORDER BY name ASC');
but it seems it doesn't exist anymore in Zend Framework 2.
Please guys, give me a hand. If the code isn't good and you have a better idea, please tell me.
Thanks in advance!
This is just a quick and dirty answer, but i guess it can get you started.
Create a ServiceFactory, this should be done in a separate factory class instead of a closure, but i still use a closure - faster to write ;)
Get the config from the ServiceLocator so you have access to the DB-Params
Create your default SQL Stuff to retriefe the value_options
Populate the value_options using the setValueOptions($valueOptions) function of your given form-element
Module.php getServiceConfig()
return array(
'factories' => array(
'my-form-factory' => function($serviceLocator) {
$form = new My\Form();
$config = $serviceLocator->get('config');
$db = new \Zend\Db\Auth\Adapter\Adapter($config['dbParams']); //or whatever you named the array key
$sql = //do your SQL Stuff
// This is a fake array, it should be your $sql result in the given format
$result = array('value' => 'label', 'value2' => 'label2');
$form->get('elementToPopulate')->setValueOptions($result);
return $form;
}
)
);
SomeController.php someAction()
$form = $this->getServiceLocator()->get('my-form-factory');
return new ViewModel(array(
'form' => $form
));
I hope this gets you started
you have to add that field validation on controller for setting value in it.
$select = $db->select()->where("state_code = ?",$arr["state_code"]);
$resultSet = $cityObj->fetchAll($select);
$cityArr = $resultSet->toArray();
$city_ar = array();
foreach($cityArr as $city){
$city_ar[$city['id']] = $city['company'];
}
$form->company->setMultiOptions($city_ar);
$form->company->setValue($val["company"]);
by using this code drop down of country have the value that are in resultset array ($resultSet).

Filtering theme_table in Drupal

I just created a data table based on a query and displayed it successfully using theme_table().
Now, I'd like to add some filters to the table but have no idea how to proceed.
Is there a built-in feature that allow me to do this easily, or should I manually add a form and update the query/redisplay the results each time the user selects something?
Thanks for your help!
I think you want to use pager_query and tablesort_sql: it's especially made for creating tables of data with pagination and sorting capabilities (and themes usually theme such tables nicely out of the box).
Example:
<?php
// The regular query without sorting or pagination parameters
$sql = 'SELECT cid, first_name, last_name, company, city FROM {clients}';
// Number of rows per page
$limit = 20;
// List of table columns ("field" is the matching database column from the sql query)
$header = array(
array('data' => t('Name'), 'field' => 'last_name', 'sort' => 'asc'),
array('data' => t('Company'), 'field' => 'company'),
array('data' => t('City'), 'field' => 'city')
);
// Calculates how to modify the SQL query according to the current pagination and sorting settings
// Then performs the database query
$tablesort = tablesort_sql($header);
$result = pager_query($sql . $tablesort, $limit);
$rows = array();
while ($client = db_fetch_object($result)) {
$rows[] = array(l($client->last_name.', '.$client->first_name, 'client/'.$client->cid), $client->company, $client->city);
}
// A message in case no results were found
if (!$rows) {
$rows[] = array(array('data' => t('No client accounts created yet.'), 'colspan' => 3));
}
// Then you can pass the data to the theme functions
$output .= theme('table', $header, $rows);
$output .= theme('pager', NULL, $limit, 0);
// And return the HTML output
print $output;
?>
(I added comments, but the original version of the example comes from this page)
Alternatively, maybe you don't need to make a module at all if you're just trying to make a page that displays a list of data, you may prefer using the Views module.