i am a newbie having difficulty in this. i did not getting a value of ID In A box for Update Inside A Box.
update code
<?php
require_once (__DIR__ . '/../../config.php');
require_once($CFG->dirroot.'/local/message/classes/form/edit.php');
global $DB;
$PAGE->set_url(new moodle_url('/local/message/update.php'));
$PAGE->set_context(\context_system::instance());
$PAGE->set_title('Edit');
//here display form
$mform=new edit();
$table='local_message';
$id=required_param('id', PARAM_INT);
$info=$DB->get_records($table,array('id' => $id));
if ($mform->is_cancelled()) {
print_r("1");
redirect($CFG->wwwroot.'/local/message/manage.php', 'You Cancelled The Form');
} else if ($fromform = $mform->get_data()) {
print_r("2");
$record = new stdClass();
$record->id=$id;
$record->messagetext = $fromform->messagetext;
$record->messagetype = $fromform->messagetype;
$DB->update_record($table, $record);
redirect($CFG->wwwroot . '/local/message/manage.php', 'you created a message with a title ' . $fromform->messagetext);
}
echo $OUTPUT->header();
$mform->display();
echo $OUTPUT->footer();
Form/moodle/Code
<?php
require_once("$CFG->libdir/formslib.php");
class edit extends moodleform {
public function definition() {
global $CFG;
$mform = $this->_form; // Don't forget the underscore!
$mform->addElement('text', 'id');
$mform->setType('id', PARAM_INT);
$mform->addElement('text', 'messagetext', get_string('message_text', 'local_message')); // Add elements to your form
$mform->setType('messagetext', PARAM_NOTAGS); //Set type of element
$mform->setDefault('messagetext', get_string('enter_message', 'local_message')); //Default value
$choices = array();
$choices['0'] = \core\output\notification::NOTIFY_WARNING;
$choices['1'] = \core\output\notification::NOTIFY_SUCCESS;
$choices['2'] = \core\output\notification::NOTIFY_ERROR;
$[enter image description here][1]choices['3'] = \core\output\notification::NOTIFY_INFO;
$mform->addElement('select', 'messagetype', get_string('message_type', 'local_message'), $choices);
$mform->setDefault('messagetype', '3');
$this->add_action_buttons();
}
//Custom validation should be added here
function validation($data, $files) {
return array();
}
}
You need to pass the id to the form before displaying the form
$mform->set_data($info);
$mform->display();
Also, you should use the single get_record function not the multiple get_records function
$info = $DB->get_record($table, array('id' => $id));
Also, you might want to use the hidden element for the id
$mform->addElement('hidden', 'id');
Related
I'm beginner in PHP and developing my own component for Joomla. I've replaced all the classes in HelloWorld example but yet I haven't change the names of views. If I try to open the specific message/record in the backend I get the error:
Fatal error: Call to a member function getFieldset() on a non-object in administrator/components/com_mycom/views/helloworld/tmpl/edit.php on line 12
Line 12: <?php foreach ($this->form->getFieldset('details') as $field) : ?>
The code of my administrator/components/com_mycom/models/fields/mycom.php:
<?php
defined('_JEXEC') or die;
jimport('joomla.form.helper');
JFormHelper::loadFieldClass('list');
class JFormFieldHelloWorld extends JFormFieldList
{
protected $type = 'Mycom';
protected function getOptions()
{
$db = JFactory::getDBO();
$query = $db->getQuery(true);
$query->select('h.id, h.header, h.parent')
->from('#__pages as h')
->select('c.title as category')
->leftJoin('#__categories AS c ON c.id = h.parent');
$db->setQuery($query);
$messages = $db->loadObjectList();
$options = array();
if ($messages)
{
foreach ($messages as $message)
{
$options[] = JHtml::_('select.option', $message->id,
$message->header . ($message->parent ? ' (' . $message->category . ')' : '')
);
}
}
$options = array_merge(parent::getOptions(), $options);
return $options;
}
}
Joomla 3.4
There must be administrator/components/com_mycom/models/fields/helloworld.php as model/view for single record
When creating a form, form fields are specified in an XML file in models/forms/helloworld.xml form fields are specified in a fieldset. To get the form fields in view page, we can use any one of the following method.
$this->form = $this->get('Form'); // use in view.html.php file where we store data to be used in view file (edit.php)
in the model file of helloworld.php define the function
public function getForm($data = array(), $loadData = true) {
// Initialise variables.
$app = JFactory::getApplication();
// Get the form.
$form = $this->loadForm('com_helloworld.helloworld', 'helloworld', array('control' => 'jform', 'load_data' => $loadData));
if (empty($form)) {
return false;
}
return $form;
}
in the view edit.php file
<?php echo $this->form->getLabel('name'); ?> // label name
<?php echo $this->form->getInput('name'); ?> // input text fields
The other method is
$fieldset = $this->form->getFieldset('fieldset_name'); // name of the fieldset in xml file.
this returns an array.
https://docs.joomla.org/API16:JForm/getFieldset
Is it possible to get a record of my model by another field of my model?
The normal way
$model = Mage::getModel('foo_bar/baz');
$model->load($id);
// do something with the loaded record
But i need something like this
$model = Mage::getModel('foo_bar/baz');
$model->loadByAnotherFieldOfModel($value)
// do something with the loaded record
is that possible?
$model = Mage::getModel('foo_bar/baz');
$model->load('field_value', 'field_name');
use this
$_category = Mage::getModel('catalog/category')->loadByAttribute('name', 'computer');
$_product = Mage::getModel('catalog/product')->loadByAttribute('name', 'hp2312');
// Load by SKU
$_product = Mage::getModel('catalog/product')->loadByAttribute('sku', 'computer123');
Goto model file
NameSpace/Yourmodule/Model/YourModel.php
add below code
public function loadByField($fieldvalue)
{
$this->_getResource()->loadByField($this, $fieldvalue);
return $this;
}
AND
NameSpace/YourModule/Model/Resource/YourModel.php
and code is
public function loadByField(NameSpace_YourModule_Model_YourModel $Object, $fieldvalue)
{
$adapter = $this->_getReadAdapter();
$bind = array('fieldname' => $fieldvalue);
$select = $adapter->select()
->from($this->getMainTable(), 'tablePrimaryKey')
->where('fieldname = :fieldname');
$modelId = $adapter->fetchOne($select, $bind);
if ($modelId) {
$this->load($Object, $modelId );
} else {
$Object->setData(array());
}
return $this;
}
Does any one know if it is possible to have datetimepicker from date_time_selector function in moodle? I want the date/time selected from date_time_selector in a variable to store it into the database.
This is the code what I am working on right now in my edit.php , what am I missing
require_once('../../config.php');
require_once($CFG->dirroot.'/course/lib.php');
require_once($CFG->dirroot.'/blocks/myblcok/myblock_form.php');
global $DB;
require_login($SITE);
$block = new myblock();
$mform = new myblock_form();
if ($data = $mform->get_data()) {
$startdate = $data->startdate;
}
$dataobject = new stdClass;
$dataobject->name = get_string('entryname', 'myblock');
$dataobject->description = get_string('entrydescription',
'myblock');
$dataobject->course = $COURSE->id;
$dataobject->userid = $USER->id;
$dataobject->starttime = $data->date;
$DB->insert_record('event', $dataobject);
redirect($CFG->wwwroot.'/course/view.php?id='.$courseid, '', 0);
I'm presuming this is being used in a form? The return value from data_time_selector is a timestamp which can be stored in a database. eg:
In edit_form.php file
require_once($CFG->dirroot.'/lib/formslib.php');
class edit_form extends moodleform {
function definition () {
$mform =& $this->_form;
$mform->addElement('date_time_selector', 'mytime', get_string('mytime', 'mycomponent'));
}
}
In edit.php
require_once('edit_form.php');
$mform = new edit_form();
if ($data = $mform->get_data()) {
// This is a timestamp.
$mytime = $data->mytime;
}
EDIT:
Ah... you need to pass a data object to insert a record eg:
$newrecord = new StdClass();
$newrecord->mytime = $mytime;
$DB->insert_record('table', $newrecord);
Or if the form field names are the same as your field names, just use the $data object eg:
$DB->insert_record('table', $data);
Have a look through the database API :
http://docs.moodle.org/dev/Data_manipulation_API#Inserting_Records
I am using joomla 2.5, I am working on custom component of joomla . I have created the form in backend admin page. what i need is , i want to save the post data of form in params row of that component in database of #_extensions.
Here is my tables/component.php
<?php defined('_JEXEC') or die('Restricted access');
jimport('joomla.database.table');
class componentTablecomponent extends JTable {
function __construct(&$db)
{
parent::__construct('#__extensions', 'extension_id', $db);
}
public function bind($array, $ignore = '')
{
if (isset($array['params']) && is_array($array['params']))
{
// Convert the params field to a string.
$parameter = new JRegistry;
$parameter->loadArray($array['params']);
$array['params'] = (string)$parameter;
}
return parent::bind($array, $ignore);
}
public function load($pk = null, $reset = true)
{
if (parent::load($pk, $reset))
{
// Convert the params field to a registry.
$params = new JRegistry;
$params->loadJSON($this->params);
$this->params = $params;
return true;
}
else
{
return false;
}
} public function store() {
parent::store(null);
}
}
Instead of saving the $data in params row of that component . This code is creating new empty rows in that table(data is saving in those params field).
Here is my save() function in controllers/component.php
public function save()
{
// Check for request forgeries.
JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN'));
// Check if the user is authorized to do this.
if (!JFactory::getUser()->authorise('core.admin'))
{
`JFactory::getApplication()->redirect('index.php',JText::_('JERROR_ALERTNOAUTHOR'));`
return;
}
// Initialise variables.
$app = JFactory::getApplication();
$model = $this->getModel('component');
$form = $model->getForm();
$data = JRequest::getVar('jform', array(), 'post', 'array');
print_r($data);
// Validate the posted data.
$return = $model->validate($form, $data);
// Check for validation errors.
if ($return === false)
{
// Get the validation messages.
$errors = $model->getErrors();
// Push up to three validation messages out to the user.
for ($i = 0, $n = count($errors); $i < $n && $i < 3; $i++) {
if ($errors[$i] instanceof Exception) {
$app->enqueueMessage($errors[$i]->getMessage(), 'warning');
} else {
$app->enqueueMessage($errors[$i], 'warning');
}
}
// Redirect back to the edit screen.
$this->setRedirect(JRoute::_('somelink',false));
return false;
}
// Attempt to save the configuration.
$data = $return;
$return = $model->save($data);
// Check the return value.
if ($return === false)
{
// Save failed, go back to the screen and display a notice.
$message = JText::sprintf('JERROR_SAVE_FAILED', $model->getError());
$this->setRedirect('index.php/somelink','error');
return false;
}
// Set the success message.
$message = JText::_('COM_CONFIG_SAVE_SUCCESS');
// Set the redirect based on the task.
switch ($this->getTask())
{
case 'apply':
$this->setRedirect('somelink',$message);
break;
case 'cancel':
case 'save':
default:
$this->setRedirect('index.php', $message);
break;
}
return true;
}
models/component.php
public function save($data) {
parent::save($data);
return true;
}
I thinks these codes are enough . I can add more codes if you need.
If you want to store params in the extension table, why not just use com_config for it?
See http://docs.joomla.org/J2.5:Developing_a_MVC_Component/Adding_configuration
Then you don't have to do anything besides creating the config.xml and adding a link to the config options in the toolbar.
I have come up with a solution . it works for me . By using this method you can control save () functions i.e. you can run your custom php scripts on save, apply toolbar buttons.
I copied save(),save($data), store($updateNulls = false) functions from com_config component , I have copied the layout from component view . Removed the buttons. Added toolbar buttons in .html.php file.
controllers/mycomponent.php
<?php
defined('_JEXEC') or die;
class componentControllermycomponent extends JControllerLegacy {
function __construct($config = array())
{
parent::__construct($config);
// Map the apply task to the save method.
$this->registerTask('apply', 'save');
}
function save()
{
// Check for request forgeries.
JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN'));
// Set FTP credentials, if given.
JClientHelper::setCredentialsFromRequest('ftp');
// Initialise variables.
$app = JFactory::getApplication();
$model = $this->getModel('mymodel');
$form = $model->getForm();
$data = JRequest::getVar('jform', array(), 'post', 'array');
$id = JRequest::getInt('id');
$option = 'com_mycomponent';
// Check if the user is authorized to do this.
if (!JFactory::getUser()->authorise('core.admin', $option))
{
JFactory::getApplication()->redirect('index.php', JText::_('JERROR_ALERTNOAUTHOR'));
return;
}
// Validate the posted data.
$return = $model->validate($form, $data);
// Check for validation errors.
if ($return === false) {
// Get the validation messages.
$errors = $model->getErrors();
// Push up to three validation messages out to the user.
for ($i = 0, $n = count($errors); $i < $n && $i < 3; $i++) {
if ($errors[$i] instanceof Exception) {
$app->enqueueMessage($errors[$i]->getMessage(), 'warning');
} else {
$app->enqueueMessage($errors[$i], 'warning');
}
}
// Save the data in the session.
$app->setUserState('com_iflychat.config.global.data', $data);
// Redirect back to the edit screen.
$this->setRedirect(JRoute::_('index.php?option=com_mycomponent&view=component&component='.$option.'&tmpl=component', false));
return false;
}
// Attempt to save the configuration.
$data = array(
'params' => $return,
'id' => $id,
'option' => $option
);
// print_r($data);
$return = $model->save($data);
// Check the return value.
if ($return === false)
{
// Save the data in the session.
$app->setUserState('com_config.config.global.data', $data);
// Save failed, go back to the screen and display a notice.
$message = JText::sprintf('JERROR_SAVE_FAILED', $model->getError());
$this->setRedirect('index.php?option=com_mycomponent&view=component&component='.$option.'&tmpl=component', $message, 'error');
return false;
}
// Set the redirect based on the task.
switch ($this->getTask())
{
case 'apply':
$message = JText::_('COM_MYCOMPONENT_SAVE_SUCCESS');
print_r($data);
$this->setRedirect('index.php?option=com_mycomponent&view=myview&layout=edit', $message);
break;
case 'save':
default:
$this->setRedirect('index.php');
break;
}
return true;
}
function cancel()
{
$this->setRedirect('index.php');
}
}
models/mymodel.php
<?php
defined('_JEXEC') or die;
jimport('joomla.application.component.modelform');
class componentModelmymodel extends JModelForm {
protected $event_before_save = 'onConfigurationBeforeSave';
protected $event_after_save = 'onConfigurationAfterSave';
public function getForm($data = array(), $loadData = true){
// Get the form.
$form = $this->loadForm('com_mycomponent.form', 'config',
array('control' => 'jform', 'load_data' => $loadData));
if (empty($form)){
return false;
}
return $form;
}
public function save($data)
{
$dispatcher = JDispatcher::getInstance();
$table = JTable::getInstance('extension');
$isNew = true;
// Save the rules.
if (isset($data['params']) && isset($data['params']['rules']))
{
$rules = new JAccessRules($data['params']['rules']);
$asset = JTable::getInstance('asset');
if (!$asset->loadByName($data['option']))
{
$root = JTable::getInstance('asset');
$root->loadByName('root.1');
$asset->name = $data['option'];
$asset->title = $data['option'];
$asset->setLocation($root->id, 'last-child');
}
$asset->rules = (string) $rules;
if (!$asset->check() || !$asset->store())
{
$this->setError($asset->getError());
return false;
}
// We don't need this anymore
unset($data['option']);
unset($data['params']['rules']);
}
// Load the previous Data
if (!$table->load($data['id']))
{
$this->setError($table->getError());
return false;
}
unset($data['id']);
// Bind the data.
if (!$table->bind($data))
{
$this->setError($table->getError());
return false;
}
// Check the data.
if (!$table->check())
{
$this->setError($table->getError());
return false;
}
// Trigger the oonConfigurationBeforeSave event.
$result = $dispatcher->trigger($this->event_before_save, array($this->option . '.' . $this->name, $table, $isNew));
if (in_array(false, $result, true))
{
$this->setError($table->getError());
return false;
}
// Store the data.
if (!$table->store())
{
$this->setError($table->getError());
return false;
}
// Clean the component cache.
$this->cleanCache('_system');
// Trigger the onConfigurationAfterSave event.
$dispatcher->trigger($this->event_after_save, array($this->option . '.' . $this->name, $table, $isNew));
return true;
}
function getComponent()
{
$result = JComponentHelper::getComponent('com_mycomponent');
return $result;
}
}
tables/mycomponent.php
<?php
// No direct access
defined('_JEXEC') or die('Restricted access');
// import Joomla table library
jimport('joomla.database.table');
/**
* Hello Table class
*/
class componentTableMycomponent extends JTable
{
function __construct(&$db)
{
parent::__construct('#__extensions', 'extension_id', $db);
}
public function bind($array, $ignore = '')
{
if (isset($array['params']) && is_array($array['params']))
{
// Convert the params field to a string.
$parameter = new JRegistry;
$parameter->loadArray($array['params']);
$array['params'] = (string)$parameter;
}
return parent::bind($array, $ignore);
}
public function load($pk = null, $reset = true)
{
if (parent::load($pk, $reset))
{
// Convert the params field to a registry.
$params = new JRegistry;
$params->loadJSON($this->params);
$this->params = $params;
return true;
}
else
{
return false;
}
}
public function store($updateNulls = false)
{
// Transform the params field
if (is_array($this->params)) {
$registry = new JRegistry();
$registry->loadArray($this->params);
$this->params = (string)$registry;
}
$date = JFactory::getDate();
$user = JFactory::getUser();
if ($this->id) {
// Existing item
$this->modified = $date->toSql();
$this->modified_by = $user->get('id');
} else {
// New newsfeed. A feed created and created_by field can be set by the user,
// so we don't touch either of these if they are set.
if (!intval($this->created)) {
$this->created = $date->toSql();
}
if (empty($this->created_by)) {
$this->created_by = $user->get('id');
}
}
// Verify that the alias is unique
$table = JTable::getInstance('Yourinstance', 'mycomponentTable');
if ($table->load(array('alias'=>$this->alias, 'catid'=>$this->catid)) && ($table->id != $this->id || $this->id==0)) {
$this->setError(JText::_('COM_CONTACT_ERROR_UNIQUE_ALIAS'));
return false;
}
// Attempt to store the data.
return parent::store($updateNulls);
}
}
Note : your config.xml file should be in models/forms folder.
I'm a Zend Framework newbie and I'm trying to retrieve some values to update the database. I have the following code in the controller. Populating the form works just fine, as does updating the db with some hard-coded values. My problem lies in trying to retrieve an updated value from the form, see the $first_name variable. It gives me a fatal error.
My question: How do I retrieve an updated value from the form?
public function editAction() {
$view = $this->view;
//get the application
$application_id = $this->getRequest()->getParam('id');
$application = $this->getApplication($application_id);
//get the applicant
$applicant_id = $application->applicant_id;
$applicant = $this->getApplicant($applicant_id);
if ($this->getRequest()->isPost()) {
if ($this->getRequest()->getPost('Save')) {
$applicants_table = new Applicants();
$first_name = $form->getValue('applicant_first_name');
$update_data = array ('first_name' => 'NewFirstName',
'last_name' => 'NewLastName');
$where = array('applicant_id = ?' => 16);
$applicants_table->update($update_data, $where);
}
$url = 'applications/list';
$this->_redirect($url);
} else { //populate the form
//applicant data
$applicant_data = array();
$applicant_array = $applicant->toArray();
foreach ($applicant_array as $field => $value) {
$applicant_data['applicant_'.$field] = $value;
}
$form = new FormEdit();
$form->populate($applicant_data);
$this->view->form = $form;
}
}
First off, your example has a problem here:
$first_name = $form->getValue('applicant_first_name');
...your $form isn't created yet, thus the fatal error; you are calling getValue() on a non-object.
Once you get that squared away, you can populate the form with posted data by calling the isValid method on the $form with request data. Here's a quick example:
// setup $application_data
$form = new FormEdit();
$form->populate($applicant_data);
if ($this->getRequest()->isPost()) {
if ($form->isValid($this->getRequest()->getPost())) {
$first_name = $form->getValue('applicant_first_name');
// save data to the database ...
}
}