save form field in component params joomla - php

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.

Related

Secure a class for a form hydratation : is this a good way?

I use PHP classes for managing users accounts and I wonder if what I'm doing is correct.
I directly use the $_POST['form'] for hydrate User objects.
But there is some field that I don't want user to modify (i.e. : Id_user, admin_level,...) so i use an argument in each setID or setAdmin_level (a boolean called $force) :
public function __construct(array $donnees = null, $forcer = false)
{
if($donnees){
$this->hydrate($donnees,$forcer);
}
}
public function hydrate(array $donnees, $forcer = false)
{
foreach($donnees as $champ => $valeur){
$method = 'set'.ucfirst($champ);
if(method_exists($this,$method))
{
if($forcer){
try {
$this->$method($this->securite($valeur), true);
}catch(Exception $e){
$this->$method($this->securite($valeur));
}
}else {
$this->$method($this->securite($valeur));
}
}
}
}
Here is an example of a "secured" setter :
public function setId_user($id_user, $forcer = false)
{
if(is_numeric($id_user)&&$forcer)
{
$this->_id_user = $id_user;
return true;
}else {
$this->addErreur('id_user','User ID incorrect');
return false;
}
}
So, in order to register a new user, I hydrate a new User object with the form POST :
$user = new User($_POST[form], false);
And I need to set the $force bool to true for creating a new User from an Id or if I want to set a field protected.
$userManager->getUserFromId(new User(['id_user' => 1], true));
Or
$userManager->getUserFromEmail(new User(['email' => "my_email#email.com"], true));
Is this a good way?

session_set_start_handler throwing warnings

I am writing my own session handler as below to make Aerospike as the session manager. However, it is throwing warnings about session handler.
Warning: session_start(): Cannot find save handler '' - session startup failed in /var/www/session.php on line 165
I have set the values of session.save_path and session.save_handler to "" in php.ini as I want to manage the session data storage and retrieval myself with the below class.
NOTE: I can use the default aerospike session handling but it saves session data as bytes(hexadecimal format), I can't use it as it is as other applications need to read this data as well, so I am trying to save data as a json encoded string.
A weird behavior is that the close method always gets called at script shutdown even though the session_set_save_handler's return value is false!
This works sometimes without error and sometimes throws a warning shown above. Not sure what is missing.
Code:
<?php
ini_set( 'display_errors', 1 );
ini_set( 'error_reporting', E_ALL );
define('SESS_ID', '66ac548234f96b48b42e18b2d3d7b73a3f1aceb01fa4c20647d3dcaa055b5099');
class MySessionHandler implements SessionHandlerInterface {
private $database = null;
private $recordKey = null;
public function __construct(){
$this->init();
}
private function init() {
$this->database = new \Aerospike(
[
"hosts" => [
0 => [
"addr" => "IP_HERE",
"port" => 3000
]
]
], false);
$this->recordKey = $this->database->initKey( 'cache', 'data', SESS_ID);
}
private function isConnected() : bool {
return ( $this->database instanceof \Aerospike ) && $this->database->isConnected();
}
public function open($savepath = '', $id = ''){
// If successful
if( is_null($this->database) ) {
$this->init();
}
$status = $this->database->get($this->recordKey, $data);
if ($status == \Aerospike::OK) {
$data = json_decode($data['bins']['PHP_SESSION'], 1);
if( !is_array($data) ) {
$data = [];
}
} else {
$data = [];
}
return true;
}
public function read($id)
{
if( is_null($this->database) ) {
$this->init();
}
$status = $this->database->get($this->recordKey, $data);
if ($status == \Aerospike::OK) {
$data = json_decode($data['bins']['PHP_SESSION'], 1);
if( !is_array($data) ) {
$data = [];
}
} else {
$data = [];
}
$_SESSION = $data;
return json_encode($data);
}
public function write($id, $dataNode)
{
if( is_null($this->database) ) {
$this->init();
}
$data = false;
if( $this->isConnected() ) {
$bins = [
"PHP_SESSION" => json_encode($_SESSION)
];
$status = $this->database->put( $this->recordKey, $bins );
if ($status == \Aerospike::OK) {
$data = true;
} else {
// error while saving data, log it
}
}
return $data;
}
public function destroy($id)
{
$removeStatus = false;
if( $this->isConnected() ) {
$status = $this->database->remove( $this->recordKey );
if ($status == \Aerospike::OK) {
$removeStatus = true;
} else {
// error while saving data, log it
}
}
return $removeStatus;
}
public function close(){
// Close the database connection
if($this->isConnected() && $this->database->close()){
// Return True
return true;
}
// Return False
return false;
}
public function gc($max)
{
return 0;
}
public function __destruct()
{
$this->close();
}
}
$s = new MySessionHandler();
// Set handler to overide SESSION
$newSession = session_set_save_handler($s, true);
var_dump($newSession); // this returns false sometimes and throws a warning
register_shutdown_function('session_write_close');
session_id(SESS_ID);
session_start();
$_SESSION['dfc'] = 'xdc1';
//unset($_SESSION['dfc']);
pr($_SESSION);
unset($s);
function pr($data) {
if( is_object($data) ) {
// $data = serialize($data);
}
echo '<pre>' . var_export($data, 1) . '</pre>';
}
These warnings are thrown intermittently and I am not sure what might be causing this. Any help would be appreciated.
The PHP client for Aerospike comes with a session handler. Set session.save_handler=aerospike. See the php.ini options of the module.
If you're writing your own session handler
Don't set session.save_handler=''. You want to comment it out in your php.ini instead, because that gets loaded and executed first (before your script) and it's non-sensical. There is no such handler. That should suppress the warning.
Watch out for null bytes. PHP strings can have those in the middle, but Aerospike strings will terminate there, so it'll get truncated at that point. Read the documentation on Handling Unsupported Types, which is why you're provided the \Aerospike\Bytes wrapper class.

Moodle: Error on form submission in activity module

Below is a sample of the code that I'm using for the form and then the handling og the file saving. There's something that I'm doing wrong, but I'm not sure what it is. Please assist. I have attached a screenshot showing the error that I'm getting after submitting the form.
error on form submission in moodle inside activity module
class mod_audio_mod_form extends moodleform_mod {
/**
* Defines forms elements
*/
public function definition() {
global $CFG;
$mform = $this->_form;
// Adding the "general" fieldset, where all the common settings are showed.
$mform->addElement('header', 'general', get_string('general', 'form'));
// Adding the standard "name" field.
$mform->addElement('text', 'name', get_string('audioname', 'audio'), array('size' => '64'));
if (!empty($CFG->formatstringstriptags)) {
$mform->setType('name', PARAM_TEXT);
} else {
$mform->setType('name', PARAM_CLEANHTML);
}
$mform->addRule('name', null, 'required', null, 'client');
$mform->addRule('name', get_string('maximumchars', '', 255), 'maxlength', 255, 'client');
$mform->addHelpButton('name', 'audioname', 'audio');
// Adding the standard "intro" and "introformat" fields.
if ($CFG->branch >= 29) {
$this->standard_intro_elements();
} else {
$this->add_intro_editor();
}
// Adding the rest of audio settings, spreading all them into this fieldset
// ... or adding more fieldsets ('header' elements) if needed for better logic.
$mform->addElement('header', 'audiofieldset', get_string('audiofieldset', 'audio'));
$filemanager_options = array();
$filemanager_options['accepted_types'] = '*';
$filemanager_options['maxbytes'] = 0;
$filemanager_options['maxfiles'] = -1;
$filemanager_options['mainfile'] = true;
$mform->addElement('filemanager', 'files', get_string('selectfiles'), null, $filemanager_options);
$mform->addRule('files', null, 'required', null, 'client');
// Add standard grading elements.
$this->standard_grading_coursemodule_elements();
// Add standard elements, common to all modules.
$this->standard_coursemodule_elements();
// Add standard buttons, common to all modules.
$this->add_action_buttons();
}
function data_preprocessing(&$default_values) {
if ($this->current->instance) {
// editing existing instance - copy existing files into draft area
$draftitemid = file_get_submitted_draft_itemid('files');
file_prepare_draft_area($draftitemid, $this->context->id, 'mod_audio', 'content', 0, array('subdirs' => true));
$default_values['files'] = $draftitemid;
}
}
function definition_after_data() {
if ($this->current->instance and $this->current->tobemigrated) {
// resource not migrated yet
return;
}
parent::definition_after_data();
}
function validation($data, $files) {
global $USER;
$errors = parent::validation($data, $files);
$usercontext = context_user::instance($USER->id);
$fs = get_file_storage();
if (!$files = $fs->get_area_files($usercontext->id, 'user', 'draft', $data['files'], 'sortorder, id', false)) {
$errors['files'] = get_string('required');
return $errors;
}
if (count($files) == 1) {
// no need to select main file if only one picked
return $errors;
} else if (count($files) > 1) {
$mainfile = false;
foreach ($files as $file) {
if ($file->get_sortorder() == 1) {
$mainfile = true;
break;
}
}
// set a default main file
if (!$mainfile) {
$file = reset($files);
file_set_sortorder($file->get_contextid(), $file->get_component(), $file->get_filearea(), $file->get_itemid(), $file->get_filepath(), $file->get_filename(), 1);
}
}
return $errors;
}
}
// THE CLASS IN LOCALLIB.PHP
class audio_content_file_info extends file_info_stored {
public function get_parent() {
if ($this->lf->get_filepath() === '/' and $this->lf->get_filename() === '.') {
return $this->browser->get_file_info($this->context);
}
return parent::get_parent();
}
public function get_visible_name() {
if ($this->lf->get_filepath() === '/' and $this->lf->get_filename() === '.') {
return $this->topvisiblename;
}
return parent::get_visible_name();
}
function save_files($data) {
global $DB;
// Storage of files from the filemanager (videos).
$draftitemid = $data->files;
if ($draftitemid) {
file_save_draft_area_files(
$draftitemid, $this->context->id, 'mod_audio', 'files', 0
);
}
}
}
// FUNCTION THAT ADDS THE INSTANCE IN LIB.PHP
function audio_add_instance(stdClass $audio, mod_audio_mod_form $mform = null) {
global $CFG, $DB;
require_once("$CFG->libdir/resourcelib.php");
require_once("$CFG->dirroot/mod/audio/locallib.php");
$cmid = $audio->coursemodule;
$audio->timecreated = time();
$audio->timemodified = time();
resource_set_display_options($audio);
$audio->id = $DB->insert_record('audio', $audio);
$context = context_module::instance($audio->coursemodule);
$audiofile = new audio_content_file_info($context, null, null);
$audiofile->save_files($audio);
// we need to use context now, so we need to make sure all needed info is already in db
$DB->set_field('course_modules', 'instance', $audio->id, array('id' => $cmid));
resource_set_mainfile($audio);
return $audio->id;
}
Please advice on what I could be doing wrong here.

want to pass variable to aftersave() method after save(false) in yii

Actually,
as you see below code,
in model two functions are calling
$this->sendMailtoTutor(),$this->sendMailtoLearner()
i want to check a condition in model that if that condition will true then only these both function will call otherwise not. Is there any way to pass attributes or variable so that i can check condition in aftersave().
my code is as below
in controller
public function actionBooking()
{
$booking_temp = new BookingTemp();
$this->performAjaxValidation($booking_temp);
if (Yii::app()->request->isPostRequest && Yii::app()->request->getPost('BookingTemp'))
{
$booking_temp->attributes = Yii::app()->request->getPost('BookingTemp');
//echo '<pre>';print_r($booking_temp->attributes);exit;
if ($booking_temp->validate())
{
$extra_price = 0;
$post_data = Yii::app()->request->getPost('BookingTemp');
$cam = Cam::model()->findByPk($post_data['temp_cam_id']);
$data = array();
$data = $post_data;
$data['temp_book_user_id'] = Yii::app()->user->id;
$data['temp_book_cam_price'] = $cam->cam_price;
$data['temp_book_duration'] = $cam->cam_duration;
if ($post_data['temp_book_session'] == 2) {
$data['temp_book_cam_price'] = 2 * $cam->cam_price;
$data['temp_book_duration'] = 2 * $cam->cam_duration;
}
if ($post_data['temp_book_is_extra'] == "Y") {
$extra_price = $cam->camExtras->extra_price;
$data['temp_book_extra_price'] = $extra_price;
}
$price_calculation = CamBooking::price_calculation(Yii::app()->user->country_id, $data['temp_book_cam_price'], $extra_price);
$data['temp_book_processing_fees'] = $price_calculation['processing_fees'];
$data['temp_book_service_tax'] = $price_calculation['service_tax'];
$data['temp_book_total_price'] = $price_calculation['total_price'];
$booking_temp->temp_value = serialize($data);
$booking_temp->user_id = Yii::app()->user->id;
$booking_temp->tutor_id = $cam->tutor_id;
$booking_temp_variable = 'check_aftersave';
$booking_temp->save(false, $booking_temp_variable);
//$booking_temp->saveAttributes(array('tutor_id', 'user_id', 'temp_value'));
$created_at = Yii::app()->localtime->fromUTC($booking_temp->created_at);
$created_at_time = strtotime($created_at);
$end_time = $created_at_time + (60 * 3); // 3 min greater from created
$end_time_format = date("Y/m/d H:i:s", $end_time);
echo json_encode(array(
'status' => 'success',
'temp_guid' => $booking_temp->temp_guid,
'end_time_format' => $end_time_format,
), JSON_UNESCAPED_SLASHES);
Yii::app()->end();
} else {
$error = CActiveForm::validate($booking_temp);
if ($error != '[]')
echo $error;
Yii::app()->end();
}
}
}
in model
protected function afterSave()
{
if ($this->isNewRecord)
{
$this->sendMailtoTutor();
$this->sendMailtoLearner();
if ($this->is_message == 'Y' && !empty($this->book_message))
{
Message::insertMessage($this->book_message, $this->book_user_id, $this->cam->tutor_id, $this->cam_id);
}
$user_profile_link = CHtml::link($this->bookUser->fullname, array("/site/user/profile", "slug" => $this->bookUser->slug));
$cam_link = CHtml::link($this->cam->cam_title, array("/site/cam/view", "slug" => $this->cam->slug));
$message = "You have a new booking from {$user_profile_link} for your {$cam_link}";
Notification::insertNotification($this->cam->tutor_id, $message, 'book', $this->book_id);
}
return parent::afterSave();
}
How can I perform this?
Hi See if you want to do it in the afterSave() of BookingTemp Model;. Then you can define a variable in that model like
like
class BookingTemp extends CActiveRecord
{
public $booking_temp_variable;
............
}
now assign this variable before saving your model in actionBooking();
as
$booking_temp->booking_temp_variable = 'check_aftersave';
$booking_temp->save(false);// no need to pass a varible
now in your aftersave function you can easily get it like
protected function afterSave()
{
if ($this->isNewRecord)
{
$this->booking_temp_variable; // this has your value
}
return parent::afterSave();
}
Don't forget to keep it in rules as safe
public function rules(){
// your rules
array('booking_temp_variable','safe');
}
What exacly you want to do?
At first you have to know, that when you are calling save() method and u pass there two args - false and, $booking_temp_variable . The first arg says that you do not run validation, the second one is (should be) array of attributes.
http://www.yiiframework.com/doc/api/1.1/CActiveRecord#save-detail

Creating helper for my application

I have been creating a helper class for the Facebook PHP API in order to avoid reusing a lot of code. The helper works but the only problem is that its very slow.. and I also figured out why! when I initialize the class, the constructor is called twice! I checked in my code and the other elements which use this class only call it once (It's something inside the class itself) Could you please help me figure out what the problems could be?? Thanks!
class FbHelper
{
private $_fb;
private $_user;
function __construct()
{
// Initalize Facebook API with keys
$this->_fb = new Facebook(array(
'appId' => 'xxxxxxxxxxx',
'secret' => 'xxxxxxxxxxxxxxxxxxxxxx',
'cookie' => true,
));
// set the _user variable
//
$this->doLog("Called Constructor");
//
$this->_user = $this->UserSessionAuthorized();
return $this;
}
function doLog($text)
{
// open log file <----- THIS GETS CALLED TWICE EVERY TIME I INITIALIZE THE CLASS!!
$filename = "form_ipn.log";
$fh = fopen($filename, "a") or die("Could not open log file.");
fwrite($fh, date("d-m-Y, H:i")." - $text\n") or die("Could not write file!");
fclose($fh);
}
function getUser() { return $this->_user; }
function getLoginUrl() { return $this->_fb->getLoginUrl(); }
function getLogoutUrl() { return $this->_fb->getLogoutUrl(); }
function UserSessionAuthorized()
{
// Checks if user is authorized, if is sends back user object
$user = null;
$session = $this->_fb->getSession();
if (!$session) return false;
try {
$uid = $this->_fb->getUser();
$user = $this->_fb->api('/me');
if ($user) return $user;
else return false;
}
catch (FacebookApiException $e) { return false; }
}
private function _rebuildSelectedFriends($selected_friends)
{
// Creates a new array with less data, more useful and less malicious
$new = array();
foreach ($selected_friends as $friend)
{
$f = array('id' => $friend['id'], 'name' => $friend['name']);
$new[] = $f;
}
return $new;
}
function GetThreeRandomFriends()
{
$friends = $this->_fb->api('/me/friends');
$n = rand(1, count($friends['data']) - 3);
$selected_friends = array_slice($friends['data'], $n, 3);
return $this->_rebuildSelectedFriends($selected_friends);
}
function UserExists($user_id)
{
try { $this->_fb->api('/' . $user_id . '/'); return true; }
catch (Exception $e) { return false; }
}
}
You must be calling the FbHelper class twice as your doLog function is in the constructor, therefore the repetition is somewhere higher up in your application and not in this class itself.

Categories