I wanted to associate a file to a node. so far so good. create a cck type file, and the problem was solved. but I can not do this, I do not want the user to choose the file. the file in question is already in the system.
I have tried to place the file as # default_value field and hide it with the hook_form_FORM_ID_alter, but failed.
function my_module_form_node_form_alter(&$form, $form_state, $form_id) {
if(isset($form['type']) && isset($form['#node'])) {
$type = $form['#node']->type;
if(stripos($type, 'node-type') === FALSE)
return;
switch($type) :
case 'node-type_xyz':
$fid = arg(3);
$file = file_load($fid);
// make a cck field_invoice a hidden field
$form['field_invoice']['#prefix'] = '<div style="display:none;">';
$form['field_invoice']['#suffix'] = '</div>';
$form['field_company']['und'][0]['value']['#default_value'] = 'ABC';
$form['field_account_number']['und'][0]['value']['#default_value'] = '09879';
break;
endswitch;
}
}
anyone have any suggestions?
Don't use #prefix and #suffix to hide it. Instead, set #access to false - that way, people can't fiddle with the form. You can set the value in hook_nodeapi or a submit function, or set the type to 'value' and the #value to your file.
Related
I'm trying to insert a file into TYPO3 db through frontend using core functions or FileRepository, exactly into sys_file table.
While investigating I've seen few solutions like,
$storageRepository = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Resource\\StorageRepository');
$storage = $storageRepository->findByUid(1);
$fileObject = $storage->addFile('/tmp/myfile', $storage->getRootLevelFolder(), 'newFile');
echo $fileObject->getIdentifier(); // Should output "/newFile"
But I still can't find this addFile() in storageRepository class. Am I missing some thing here?
The line $storageRepository->findByUid(1) return a ResourceStorage Object with the Method addFile().
Here is a Documenttion of this class.
https://typo3.org/api/typo3cms/class_t_y_p_o3_1_1_c_m_s_1_1_core_1_1_resource_1_1_resource_storage.html
#mario Thanks. By the way I've achieved what I planned. Here's what I did..
public function uploadFile($uploadedfile) {
$storage = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Resource\\StorageRepository');
$filePath = 'uploads/tx_fileupload/'.$uploadedfile['updata']['name'];
$title = $uploadedfile['updata']['name'];
$size = $uploadedfile['updata']['size'];
// Moving the physical file to destined folder
\TYPO3\CMS\Core\Utility\GeneralUtility::upload_copy_move($uploadedfile['updata']['tmp_name'],$filePath);
// Adding a record in sys_file_storage
$fileObject = $storage->createLocalStorage($uploadedfile['updata']['name'],$uploadedfile['updata']['tmp_name'],$filePath,'');
// Inserting file in sys_file
$repositoryFileObject = \TYPO3\CMS\Core\Resource\ResourceFactory::getInstance()->retrieveFileOrFolderObject($filePath);
return $repositoryFileObject;
}
Now moving onto adding corresponding sys_file_reference record.
Hi for my custom component I need to set some custom parameters for joomla user for membership for checking if the user ni trial period or not and it can be change from the component admin panel for specific user.
The problem arises while retrieving the parameter. I think it is stored in cookie and it isn^t updated. I wrote the code like that to check it.
$user = JFactory::getUser(JRequest::getVar('id','0'));
echo $user->getParam('trialPeriod','0');
to save the value I am useing JHTML booleanlist.
$user->setParam('trialPeriod',$data['trialPeriod']);
$user->save();
Then is stores the value in joomla users table in the row of that user with column of params as;
{"trialPeriod":"0"}
in this situation it echoes the value as 0. Then I am changin the state of trialPeriod var as 1 and storing in db it updates the db as;
{"trialPeriod":"1"}
After all I am refreshing the page where the value is prompt the the screen the the value remains still the same as 0;
To clarify;
First of all there is no problem with saving the param it is changed properly. The problem is retrieving the changed one. The releated piece of code is following;
$user = JFactory::getUser();
$doc = JFactory::getDocument();
if($user->getParam('trialPeriod',0) == 0){
$ed = JFactory::getDate($obj->expirationDate);//obj is user from custom table and there is no problem with getting it.
$isTrialEnd = FALSE;
}else{
$ed = JFactory::getDate($user->getParam('trialExp',0));
$isTrialEnd = TRUE;
}
if($isTrialEnd){
//do something else
}else{
echo $user->getParam('trialPeriod','0');
}
actually big part of the code is unneccessary to explain it but you will get the idea.
What is the solution for this?
Editted.
$app = JFactory::getApplication();
$config = JFactory::getConfig();
$db = $this->getDbo();
$isNew = empty($data['uid']) ? true : false;
$params = JComponentHelper::getParams('com_dratransport');
if($isNew){
// Initialise the table with JUser.
$user = new JUser;
// Prepare the data for the user object.
$username = self::getCreatedUserName($data['type']);
$data['username'] = !empty($data['username']) ? $data['username'] : $username;
$data['password'] = $data['password1'];
$useractivation = $params->get('useractivation');
// Check if the user needs to activate their account.
if (($useractivation == 1) || ($useractivation == 2)) {
$data['activation'] = JApplication::getHash(JUserHelper::genRandomPassword());
$data['block'] = 1;
}
}else{
$user = JFactory::getUser($data['uid']);
$data['password'] = $data['password1'];
}
$membership = DraTransportHelperArrays::membershipCFG();
$membership = $membership[$data['membership']];
if($data['membership'] == 4)
$data['groups'] = array($params->get('new_usertype',2),$params->get($membership,2));
else
$data['groups'] = array($params->get($membership,2));
$data['name'] = $data['companyName'];
$user->setParam('trialPeriod',$data['trialPeriod']);
// Bind the data.
if (!$user->bind($data)) {
$this->setError(JText::sprintf('COM_USERS_REGISTRATION_BIND_FAILED', $user->getError()));
return false;
}
// Load the users plugin group.
JPluginHelper::importPlugin('user');
// Store the data.
if (!$user->save()) {
$app->enqueuemessage($user->getError());
$this->setError(JText::sprintf('COM_USERS_REGISTRATION_SAVE_FAILED', $user->getError()));
return false;
}
this piece of code is for storing the data releated with the users table.
Turns out this was the fact that Joomla stores the JUser instance in the session that caused the problem.
When changing a user's parameters from the back-end, the changes are not reflected in that user's session, until she logs out and back in again.
We could not find an easy option to modify anther user's active session, so we resorted to the use of a plugin that refreshes the JUser instance in the logged-in users' session, something like the following:
$user = JFactory::getUser();
$session = JFactory::getSession();
if(!$user->guest) {
$session->set('user', new JUser($user->id));
}
(reference: here).
I am writing a Drupal custom module in which I create a node based on custom values. This is the code which creates node in proper manner.
global $user;
$node = new stdClass();
$node->type = 'my_node_type';
//$node->title = $nodeInfo->title;
node_object_prepare($node);
$node->language = LANGUAGE_NONE;
$node->uid = $user->uid;
$node->field_node_refrence_field['und'][0]['nid'] = $nid-of-reference-field;
$node = node_submit($node);
node_save($node);
I have the Node Autotitle module enabled for this content type. Due to that, the title is displayed as blank. I have checked the module, and I found that auto_nodetitle_set_title($node) sets the title. When I use this function in my code nothing happens.
Can anyone give me an idea on how to save the node with node_autotitle settings?
The code executed from auto_nodetile_set_title() is the following one. (The comments identifying parts of the code are mine.)
$types = node_type_get_types();
$pattern = variable_get('ant_pattern_' . $node->type, '');
// 1
if (trim($pattern)) {
$node->changed = REQUEST_TIME;
$node->title = _auto_nodetitle_patternprocessor($pattern, $node);
}
// 2
elseif ($node->nid) {
$node->title = t('#type #node-id', array('#type' => $types[$node->type]->name, '#node-id' => $node->nid));
}
// 3
else {
$node->title = t('#type', array('#type' => $types[$node->type]->name));
}
// Ensure the generated title isn't too long.
$node->title = substr($node->title, 0, 255);
// With that flag we ensure we don't apply the title two times to the same
// node. See auto_nodetitle_is_needed().
$node->auto_nodetitle_applied = TRUE;
The first control statement is executed if there is a settings for the title of that content type. If there isn't, and you are updating a module, then the second control statement is executed, otherwise it is executed the third one.
The title should never be empty, since the module always set it. The only time it could be empty is when Drupal doesn't have information about the content type used for the node; in that case $types[$node->type] would be NULL, but $types[$node->type]->name would raise the error "trying to access the property of something that is not an object."
I would use the following code, to save the node.
global $user;
$node = new stdClass();
$node->type = 'my_node_type';
node_object_prepare($node);
$node->uid = $user->uid;
$node->language = LANGUAGE_NONE;
$node->field_node_refrence_field[$node->language][0]['nid'] = $nid-of-reference-field;
$node = node_submit($node);
node_save($node);
auto_nodetitle_set_title($node);
node_save($node);
Since you are saving a new node, calling auto_nodetitle_set_title() before node_save() would not allow the function to execute the code marked with (2), and use the node ID for the title. Once auto_nodetitle_set_title() is called, you need to call node_save() to save the new title.
In hook_user_update I'm retrieving a facebook profile pic and saving a record in the file_managed table. That much is going well. But I also want to save a record for a file field attached to the user entity. Normally what I do in these hooks is assign the values to $edit['field_something'], and I think that's the correct way to do this. That has always worked for other field types, but it is not working for the file field. You can see toward the end of the function where I dump the vars to confirm that I have something suitable to assign to $edit['field_something'] -- at least, I think it's suitable. I get no errors, but no record is created in the field_data_field_image table. What am I missing? Thank you!
/**
* Implementation of hook_user_update().
*
*/
function hifb_user_update(&$edit, $account, $category) {
if (empty($account->field_image['und'])) {
$fbid = $edit['field_facebook_id']['und'][0]['value'];
if (!empty($fbid)) {
$url = 'http://graph.facebook.com/' . $fbid . '/picture?type=large';
if ($file_contents = file_get_contents($url)) {
$size = getimagesize($url);
$ext = image_type_to_extension($size[2]);
$filename = 'fb_' . $fbid . '_u_' . $account->uid . $ext;
$uri = file_default_scheme() . '://' . $filename;
// Saves the file to the default files directory and creates the record in files_managed table.
$file = file_save_data($file_contents, $uri, FILE_EXISTS_REPLACE);
//var_dump($file); die;
/* Here's an example from the var_dump: object(stdClass)#120 (8) { ["fid"]=> string(3) "576" ["uri"]=> string(30) "public://fb_767816596_u_1.jpeg" ["filename"]=> string(21) "fb_767816596_u_1.jpeg" ["filemime"]=> string(10) "image/jpeg" ["uid"]=> string(1) "1" ["status"]=> int(1) ["timestamp"]=> int(1339686244) ["filesize"]=> int(2919) } */
// Creates record in field_data_field_image table??
$edit['field_image']['und'][0] = (array)$file;
}
}
}
}
I believe the reason it doesn't work is because in hook_user_update, the update has already occurred. So setting a value for $edit has no effect. The same code that I posted in the question works fine in hook_user_presave.
I've written a function which updates the mysql database row with some new column data.
Here is the function:
function sql($set,$data){
$sql = mysql_query("UPDATE members SET '".$set."' = '".$data."' WHERE login = '".$_SESSION['login']."'");
if($sql){
echo 'Profile updated.';
}
else{
echo 'Could not update profile. Please try again later.';
}
}
And here is a fragment from the program which is supposed to utilise the function:
$array = array("$password", "$email", "$age");
if($array[0] != 0){
sql("password",$password);
}
if($array[1] != 0){
sql("email",$email);
}
if($array[2] != 0){
sql("age",$age);
}
It doesn't write the values to the database. What's wrong? Maybe it's the quotation of the variables in the function?
Remove the single quote on the SET :
function sql($set,$data){
$sql = mysql_query("UPDATE members SET ".$set." = '".$data."' WHERE login = '".$_SESSION['login']."'");
if($sql){
echo 'Profile updated.';
}
else{
echo 'Could not update profile. Please try again later.';
}
}
Column names don't dont need to be quoted
Working example here -> http://www.sqlize.com/c34I44c37r
It is indeed the quotation. To be specific, it's the quotation for the filed name (name, email, ..)
Just ` instead of '
SET `foo` = 'bar'
PS: Please make sure that you escape the user input before writing it to db using mysql_real_escape_string($data). Otherwise one could alter your query, which is called mysql injection.