I have created a simple form in the NEWMODULE plugin and a database table to save form data, but i don't know how to insert the form data into the database. I save the code into my_form.php, this is my code:
class myform_form extends moodleform {
public function definition() {
global $DB,$CFG;
$mform = &$this->_form;
$mform->addElement('text', 'tendethi', get_string('tendethi', 'myform'));
$mform->setType('tendethi', PARAM_TEXT);
$mform->setDefault('tendethi','Nhập tên đề thi');
$mform->addElement('text', 'mdt', get_string('madethi','myform'));
$mform->setType('mdt', PARAM_TEXT);
$mform->setDefault('mdt','Nhập mã đề thi');
$mform->addElement('duration', 'timelimit', get_string('thoigianlambai','myform'));
$mform->setType('timelimit', PARAM_TEXT);
$mform->addElement('text', 'gvrd', get_string('giaovienrade','myform'));
$mform->setType('gvrd', PARAM_TEXT);
$mform->setDefault('gvrd','Nhập họ tên giáo viên ra đề thi');
$mform->addElement('text', 'tmh', get_string('tenmonhoc','myform'));
$mform->setType('tmh', PARAM_TEXT);
$mform->setDefault('tmh','Nhập tên môn học');
$buttonarray=array();
$buttonarray[] = &$mform->createElement('submit', 'submitbutton', get_string('savechanges'));
$buttonarray[] = &$mform->createElement('reset', 'resetbutton', get_string('revert'));
$buttonarray[] = &$mform->createElement('cancel');
$mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
$mform->closeHeaderBefore('buttonar');
and this is code insert form data into database :
// insert database into table
//global $DB;
$tendethi = optional_param('tendethi', null, PARAM_TEXT);
$mdt = optional_param('mdt', null, PARAM_INT);
$timelimit = optional_param('timelimit', null, PARAM_INT);
$gvrd = optional_param('gvrd', null, PARAM_TEXT);
$tmh = optional_param('tmh', null, PARAM_TEXT);
if($data = $mform->get_data()){
$record = new stdClass();
$record->tendethi = $tendethi ;
$record->mdt = $mdt ;
$record->timelimit = $timelimit ;
$record->gvrd = $gvrd ;
$record->tmh = $tmh ;
$DB=insert_record('myform_form', $record, false);
}
please help me !
Your code should look roughly like this:
$urlaftersubmission = new moodle_url(); // You will need to fill this in.
$form = new myform_form();
if ($form->is_cancelled()) {
redirect($urlaftersubmission);
}
if ($data = $form->get_data()) {
$DB->insert_record('name_of_table', $data);
redirect($urlaftersubmission);
}
echo $OUTPUT->header();
$form->display();
echo $OUTPUT->footer();
Note, you may have to adjust the data slightly for it to be in the correct format for inserting in the database. You should also make sure that you create your database table using the install.xml or upgrade.php files in your plugin (and use the Moodle built-in xmldb editor to generate those files correctly), otherwise Moodle will not recognise them for inserting data.
Related
I am using contact form 7 for creating my form and I have a custom db hosted in the same server that should contain the related data.
I want to store the data from the contact from7 into my custom db and not a wordpress db.
I am doing the below in functions.php now,
add_action('wpcf7_before_send_mail', 'save_form');
function save_form($wpcf7) {
/* For connecting to database */
$dbuser = "user";
$dbpass = "pass";
$dbhost = "localhost";
$dbname = "cistom_db";
// Connect to server and select database.
$db = mysqli_connect($dbhost, $dbuser, $dbpass) or die("cannot connect");
mysqli_select_db($db, $dbname) or die("cannot select DB");
$submission = WPCF7_Submission::get_instance();
if ($submission) {
$submited = array();
$submited['title'] = $wpcf7->title();
} else {
echo 'error';
}
$insert_query = "insert into candidate(title)values('" . $submited['title'] . "')";
$result = mysqli_query($db, $insert_query);
if (!$result) {
die('Invalid query: $insert_query : ' . mysqli_error($db));
}
}
However, nothing seems to be working here. Can anyone please help?
Follow the steps to store contact form 7 data in custom table:
1) Create Custom table
CREATE TABLE candidate(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(50)
);
2) Create contact form 7 fields
[text* title]
[submit "Send"]
3) Add Below code to function.php
function contactform7_before_send_mail( $form_to_DB ) {
//set your db details
$mydb = new wpdb('root','','cistom_db','localhost');
$form_to_DB = WPCF7_Submission::get_instance();
if ( $form_to_DB )
$formData = $form_to_DB->get_posted_data();
$title = $formData['title'];
$mydb->insert( 'candidate', array( 'title' =>$title ), array( '%s' ) );
}
remove_all_filters ('wpcf7_before_send_mail');
add_action( 'wpcf7_before_send_mail', 'contactform7_before_send_mail' );
Hope this works for you.
I'm new to CakePHP. I have a table to keep record of user's activity by creating a log in it. The table has two columns
+----+------------+-----------+
| id | user_id | comment |
+----+------------+-----------+
I want to pass values from within controller like
$this->ActivityLogs->log($user_id, 'Message sent');
log is a custom function inside ActivityLogs model which will record some more data along with passed data
public function log($user_id = null, $message = null)
{
... record code goes here
return true;
}
But couldn't get how to write insert query inside model.
How can I create custom methods like this and also can anyone suggest me good resource to go through model queries and understanding.
public function log($user_id = null, $message = null){
//I assume here that your table name is 'logs'
$logsTable = \Cake\ORM\TableRegistry::get('Logs', array('table' => 'logs'));
$log = $logsTable->newEntity();
$log->user_id = $user_id;
$log->body = $message ;
if ($logsTable->save($log)) {
return true;
}
return false;
}
Looping to save each column field picture1pic6:
Please help, i using cake php version 2.0, try to do looping to save each column, but only the first row data save, the data should be save like attached picture1.Hope someone can help, i tried to figure out 2 weeks. V_COUNT i hardcode the number to 23.
if($this->IPI->save($this->request->data))
{
$table_name = 'IPI_V';
$this->IPI->setSource($table_name);
for($i=1;$i<=$this->request->data['IPI']['V_COUNT'];$i++)
{
if($i<10){$i = '0'. $i;}
if(($this->request->data['IPI']['Quantity'.$i])!=NULL)
{
$this->request->data['IPI']['Type_Defect'] = $this->request->data['IPI']['Type_Defect'.$i];
$this->request->data['IPI']['CAT'] = $this->request->data['IPI']['CAT'.$i];
$this->request->data['IPI']['Defect'] = $this->request->data['IPI']['Defect'.$i];
$this->request->data['IPI']['Quantity'] = $this->request->data['IPI']['Quantity'.$i];
$this->IPI->create();
$this->IPI->save($this->request->data);
}
}
try this
if($this->IPI->save($this->request->data))
{
$table_name = 'IPI_V';
for($i=1;$i<=$this->request->data['IPI']['V_COUNT'];$i++)
{
$data = array();
if($i<10){$i = '0'. $i;}
if(($this->request->data['IPI']['Quantity'.$i])!=NULL)
{
$data['IPI']['Type_Defect'] = $this->request->data['IPI']['Type_Defect'.$i];
$data['IPI']['CAT'] = $this->request->data['IPI']['CAT'.$i];
$data['IPI']['Defect'] = $this->request->data['IPI']['Defect'.$i];
$data['IPI']['Quantity'] = $this->request->data['IPI']['Quantity'.$i];
$this->IPI->setSource($table_name);
$this->IPI->create();
$this->IPI->save($data);
}
}
I'm trying to save the following data. But it's not saving the datetime fields.
Created is saving current datetime in cakephp way & the others are null.
How can I save custom datetime?
Thanks in advance
foreach ($passwords as $key => $value ) {
$data['id'] = $collection_id;
$data['name'] = $value['password'];
$data['collection_id'] = $collection_id;
$data['photo_count'] = $value['photos_count'];
$data['download_count'] = $value['downloaded_users_count'];
$data['created'] = $value['created'];
$data['modified'] = $value['modified'];
$data['expires_at'] = $value['expires_at'];
$saveData[] = $data;
}
$passwords = $this->Passwords->find('all')->toArray();
$patched = $this->Passwords->patchEntities($passwords, $saveData);
foreach ($patched as $entity) {
$this->Passwords->save($entity);
}
I've fixed the Issue. Just have to use as follows-
$data['created'] = new Time($value['created']);
$data['expires_at'] = new Time($value['expires_at']);
And to do so, have to use this.
use Cake\I18n\Time;
I am building a simple application for windows phone. I want to create a database and want to have several (lets say 10) items in the database. I am a beginner and every tutorial that i have seen is sth about adding items in the database on button "add" or sth like that. I don't need that, because I want to have several item that are in the database, ready for the user to use them. How can I achieve this? Please write to me in a clear way, because I am still a beginner. If you can provide some links of examples or tutorials, that would be great. Thank u!
If you need to have the preloaded DB then you can Add a sqlCe DB in your application and populate the db with your seed Data.
then you can copy the DB file to your ISO Store while your Constructor of DBContext is invoked.
public Moviadb1DataContext (string connectionString) : base(connectionString)
{
IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication();
if (!iso.FileExists("Moviadb1.sdf"))
{
MoveReferenceDatabase();
}
if (!DatabaseExists())
CreateDatabase();
}
public static void MoveReferenceDatabase()
{
// Obtain the virtual store for the application.
IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication();
// Create a stream for the file in the installation folder.
using (Stream input = Application.GetResourceStream(new Uri("Moviadb1.sdf", UriKind.Relative)).Stream)
{
// Create a stream for the new file in isolated storage.
using (IsolatedStorageFileStream output = iso.CreateFile("Moviadb1.sdf"))
{
// Initialize the buffer.
byte[] readBuffer = new byte[4096];
int bytesRead = -1;
// Copy the file from the installation folder to isolated storage.
while ((bytesRead = input.Read(readBuffer, 0, readBuffer.Length)) > 0)
{
output.Write(readBuffer, 0, bytesRead);
}
}
}
}
you can also add some seed data instead of moving the reference DB if you have very small amount of Data.
public ListenDataDataContext (string connectionString) : base(connectionString)
{
if (!DatabaseExists())
{
CreateDatabase();
List<Audiables> PreLoads = new List<Audiables>();
PreLoads.Add(new Audiables { Category = 1, Name = "I want To Eat", AudioLocation = "Sounds/Food/1_IwantToEat.wma", ImageLocation = "Images/Food/1_IwantToEat.jpg" });
PreLoads.Add(new Audiables { Category = 1, Name = "I want To Drink", AudioLocation = "Sounds/Food/1_IwantToDrink.wma", ImageLocation = "Images/Food/1_IwantToDrink.jpg" });
PreLoads.Add(new Audiables { Category = 2, Name = "I want A Ticket", AudioLocation = "Sounds/Travel/1_IwantATicket.wma", ImageLocation = "Images/Travel/1_IwantATicket.jpg" });
PreLoads.Add(new Audiables { Category = 2, Name = "I want To Sit", AudioLocation = "Sounds/Travel/1_IwantToSit.wma", ImageLocation = "Images/Travel/1_IwantToSit.jpg" });
PreLoads.Add(new Audiables { Category = 3, Name = "How Much Is That", AudioLocation = "Sounds/Shopping/1_HowMuchIsThat.wma", ImageLocation = "Images/Shopping/1_HowMuchIsThat.jpg" });
PreLoads.Add(new Audiables { Category = 3, Name = "Please Take the Money", AudioLocation = "Sounds/Shopping/1_PleaseTakeTheMoney.wma", ImageLocation = "Images/Shopping/1_PleaseTakeTheMoney.jpg" });
Audiables.InsertAllOnSubmit(PreLoads);
this.SubmitChanges();
}
}
Happy app making :)
Best way is to check the "Local Database Sample" in the Windows Phone Code Samples!