Drupal 7 | Form managed file upload image preview - forms

I'm can't get to work image preview on Drupal 7 Form managed file.
I have for code like this in template.php:
function testform($form, &$form_state) {
$form = array();
$form['con_image'] = array(
'#type' => 'managed_file',
'#title' => t('Image'),
'#required' => TRUE,
'#default_value' => variable_get('con_image', ''),
'#progress_indicator' => 'bar',
'#progress_message' => 'Uploading ...',
'#upload_location' => 'public://gallery/',
'#theme' => 'test',
'#upload_validators' => array(
'file_validate_is_image' => array(),
'file_validate_extensions' => array('jpg jpeg'),
'file_validate_image_resolution' => array('6000x4000','800x600'),
'file_validate_size' => array(6 * 1024 * 1024),
),
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Add to site'),
);
return $form;
}
I call testform after checking additional conditions (like userpoints) via code
$arr = drupal_get_form('testform');
print drupal_render($arr);
The form itself is working, I'm able to add image to node (programmatically) but cannot get the preview of image during upload process. I try to use #theme but it seems doesn't work at all.
My theme function looks like this:
function theme_test($variables) {
$element = $variables['element'];
$output = '';
$base = drupal_render_children($element); // renders element as usual
if($element['fid']['#value'] != 0) {
// if image is uploaded show its thumbnail to the output HTML
$output .= '<div class="multifield-thumbnail">';
$output .= theme('image_style', array('style_name' => 'thumbnail', 'path' => file_load($element['fid']['#value'])->uri, 'getsize' => FALSE));
$output .= '</div>';
}
Any ideas?

You need to declare your theme with a hook_theme in your module.
function yourmodule_theme() {
return array(
'test' => array(
'render element' => 'element',
)
);
}

Related

Fedex SOAP Request Failing

I am looking for the reason why the below request is failing to retrieve information. This is copied from the Fedex developer website and it doesn't work. When my program hits the GetRates line it throws a could not connect to host exception. I tried adding the connection_timeout and setting the default_timeout in php and neither appear to work. I contacted the Fedex dev team and they are receiving my post successfully I am just not able to get any response besides the fault. Has anyone had experience with Fedex or know what might cause this to be failing?
I am posting my current code below. I am using PHP7 on an AS400 machine using Zendserver.
<?php
// Copyright 2009, FedEx Corporation. All rights reserved.
// Version 12.0.0
require_once('../library/fedex-common.php5');
$newline = "<br />";
//The WSDL is not included with the sample code.
//Please include and reference in $path_to_wsdl variable.
$path_to_wsdl = "../wsdl/RateService_v24.wsdl";
ini_set("soap.wsdl_cache_enabled", "0");
ini_set('soap.wsdl_cache_ttl',0);
$client = new SoapClient($path_to_wsdl, array('trace' => 1, 'connection_timeout' => 30)); // Refer to http://us3.php.net/manual/en/ref.soap.php for more information
$request['WebAuthenticationDetail'] = array(
'ParentCredential' => array(
'Key' => getProperty('parentkey'),
'Password' => getProperty('parentpassword')
),
'UserCredential' => array(
'Key' => getProperty('key'),
'Password' => getProperty('password')
)
);
$request['ClientDetail'] = array(
'AccountNumber' => getProperty('shipaccount'),
'MeterNumber' => getProperty('meter')
);
$request['TransactionDetail'] = array('CustomerTransactionId' => ' *** Rate Request using PHP ***');
$request['Version'] = array(
'ServiceId' => 'crs',
'Major' => '24',
'Intermediate' => '0',
'Minor' => '0'
);
$request['ReturnTransitAndCommit'] = true;
$request['RequestedShipment']['DropoffType'] = 'REGULAR_PICKUP'; // valid values REGULAR_PICKUP, REQUEST_COURIER, ...
$request['RequestedShipment']['ShipTimestamp'] = date('c');
$request['RequestedShipment']['ServiceType'] = 'INTERNATIONAL_PRIORITY'; // valid values STANDARD_OVERNIGHT, PRIORITY_OVERNIGHT, FEDEX_GROUND, ...
$request['RequestedShipment']['PackagingType'] = 'YOUR_PACKAGING'; // valid values FEDEX_BOX, FEDEX_PAK, FEDEX_TUBE, YOUR_PACKAGING, ...
$request['RequestedShipment']['TotalInsuredValue']=array(
'Ammount'=>100,
'Currency'=>'USD'
);
$request['RequestedShipment']['Shipper'] = addShipper();
$request['RequestedShipment']['Recipient'] = addRecipient();
$request['RequestedShipment']['ShippingChargesPayment'] = addShippingChargesPayment();
$request['RequestedShipment']['PackageCount'] = '1';
$request['RequestedShipment']['RequestedPackageLineItems'] = addPackageLineItem1();
try {
if(setEndpoint('changeEndpoint')){
$newLocation = $client->__setLocation(setEndpoint('endpoint'));
}
$response = $client -> getRates($request);
if ($response -> HighestSeverity != 'FAILURE' && $response -> HighestSeverity != 'ERROR'){
$rateReply = $response -> RateReplyDetails;
echo '<table border="1">';
echo '<tr><td>Service Type</td><td>Amount</td><td>Delivery Date</td></tr><tr>';
$serviceType = '<td>'.$rateReply -> ServiceType . '</td>';
if($rateReply->RatedShipmentDetails && is_array($rateReply->RatedShipmentDetails)){
$amount = '<td>$' . number_format($rateReply->RatedShipmentDetails[0]->ShipmentRateDetail->TotalNetCharge->Amount,2,".",",") . '</td>';
}elseif($rateReply->RatedShipmentDetails && ! is_array($rateReply->RatedShipmentDetails)){
$amount = '<td>$' . number_format($rateReply->RatedShipmentDetails->ShipmentRateDetail->TotalNetCharge->Amount,2,".",",") . '</td>';
}
if(array_key_exists('DeliveryTimestamp',$rateReply)){
$deliveryDate= '<td>' . $rateReply->DeliveryTimestamp . '</td>';
}else if(array_key_exists('TransitTime',$rateReply)){
$deliveryDate= '<td>' . $rateReply->TransitTime . '</td>';
}else {
$deliveryDate='<td> </td>';
}
echo $serviceType . $amount. $deliveryDate;
echo '</tr>';
echo '</table>';
printSuccess($client, $response);
}else{
printError($client, $response);
}
writeToLog($client); // Write to log file
} catch (SoapFault $exception) {
printFault($exception, $client);
}
function addShipper(){
$shipper = array(
'Contact' => array(
'PersonName' => 'Sender Name',
'CompanyName' => 'Sender Company Name',
'PhoneNumber' => '9012638716'
),
'Address' => array(
'StreetLines' => array('Address Line 1'),
'City' => 'Collierville',
'StateOrProvinceCode' => 'TN',
'PostalCode' => '38017',
'CountryCode' => 'US'
)
);
return $shipper;
}
function addRecipient(){
$recipient = array(
'Contact' => array(
'PersonName' => 'Recipient Name',
'CompanyName' => 'Company Name',
'PhoneNumber' => '9012637906'
),
'Address' => array(
'StreetLines' => array('Address Line 1'),
'City' => 'Richmond',
'StateOrProvinceCode' => 'BC',
'PostalCode' => 'V7C4V4',
'CountryCode' => 'CA',
'Residential' => false
)
);
return $recipient;
}
function addShippingChargesPayment(){
$shippingChargesPayment = array(
'PaymentType' => 'SENDER', // valid values RECIPIENT, SENDER and THIRD_PARTY
'Payor' => array(
'ResponsibleParty' => array(
'AccountNumber' => getProperty('billaccount'),
'CountryCode' => 'US'
)
)
);
return $shippingChargesPayment;
}
function addLabelSpecification(){
$labelSpecification = array(
'LabelFormatType' => 'COMMON2D', // valid values COMMON2D, LABEL_DATA_ONLY
'ImageType' => 'PDF', // valid values DPL, EPL2, PDF, ZPLII and PNG
'LabelStockType' => 'PAPER_7X4.75'
);
return $labelSpecification;
}
function addSpecialServices(){
$specialServices = array(
'SpecialServiceTypes' => array('COD'),
'CodDetail' => array(
'CodCollectionAmount' => array(
'Currency' => 'USD',
'Amount' => 150
),
'CollectionType' => 'ANY' // ANY, GUARANTEED_FUNDS
)
);
return $specialServices;
}
function addPackageLineItem1(){
$packageLineItem = array(
'SequenceNumber'=>1,
'GroupPackageCount'=>1,
'Weight' => array(
'Value' => 50.0,
'Units' => 'LB'
),
'Dimensions' => array(
'Length' => 108,
'Width' => 5,
'Height' => 5,
'Units' => 'IN'
)
);
return $packageLineItem;
}
?>

How to increase picture using html code with yii2 syntax?

Hy guys, following code will increase picture by clicking on it:
<a class="example-image-link" href="http://lokeshdhakar.com/projects/lightbox2/images/image-1.jpg"><img src="http://lokeshdhakar.com/projects/lightbox2/images/thumb-1.jpg" alt="image-1" /></a>
)
In my yii2 application, I have following valid picture-url in anonymous function:
$url = '#web/img/' . $bild->dateiname;
How to tranform upper code in yii2 syntax. I try like this, but it's not working:
return Html::a(
Html::img($url, ['alt' => 'PicNotFound', 'class' => 'img-circle', 'style' => 'width:225px;height:225px']
), [Html::img($url, ['alt' => 'PicNotFound']
)], ['title' => 'Immobiliendaten abrufen', 'data' => ['pjax' => '0'], 'class' => 'example-image-link']
);
Firedebug will show following html-code. url in link is wrong!
a class="example-image-link" href="/yii2_ErkanImmo/frontend/web/index.php/" title="Immobiliendaten abrufen"><img class="img-circle" src="/yii2_ErkanImmo/frontend/web/img/villa1.jpg" alt="PicNotFound" style="width:125px;height:125px;">event
<img class="img-circle" src="/yii2_ErkanImmo/frontend/web/img/villa1.jpg" alt="PicNotFound" style="width:125px;height:125px;">
</a>
Rephrasing question
I will get output as shown up at my attachement after having clicked on picture using code like this:
return Html::a(Html::img($url, ['alt' => 'image-1']), $url, ['class' => 'example-image-link']);[![enter image description here][1]][1]
Here is complete code of view file(for GRU)
[
'attribute' => $dummy,
'label' => Yii::t('app', ''),
'format' => 'html', // sorgt dafür,dass das HTML im return gerendert wird
'vAlign' => 'middle',
'value' => function($model) {
$bmp = '/bmp/';
$tif = '/tif/';
$png = '/png/';
$psd = '/psd/';
$pcx = '/pcx/';
$gif = '/gif/';
$jpeg = '/jpeg/';
$jpg = '/jpg/';
$ico = '/ico/';
try {
$bilder = \frontend\models\Dateianhang::GetBild($model);
foreach ($bilder as $bild) {
if (preg_match($bmp, $bild->dateiname) || preg_match($tif, $bild->dateiname) || preg_match($png, $bild->dateiname) || preg_match($psd, $bild->dateiname) || preg_match($pcx, $bild->dateiname) || preg_match($gif, $bild->dateiname) || preg_match($jpeg, $bild->dateiname) || preg_match($jpg, $bild->dateiname) || preg_match($ico, $bild->dateiname)) {
$url = '#web/img/' . $bild->dateiname;
}
}
return Html::a(Html::img($url, ['alt' => 'image-1', 'class' => 'img-circle', 'style' => 'width:225px;height:225px']), $url, ['class' => 'example-image-link', 'title' => 'Touch picture to increase', 'target' => '_blank']);
//return Html::img($url, ['alt' => 'Bewerberbild nicht vorhanden', 'class' => 'img-circle', 'style' => 'width:225px;height:225px']);
} catch (Exception $e) {
return;
}
}
],
Neither picture will be increased, nor target=>_blank is doing its job :=(
Try following code -
<?php
$url = 'http://lokeshdhakar.com/projects/lightbox2/images/thumb-1.jpg';
//in your case
//$url = '#web/img/'.$bild->dateiname;
echo Html::a(
Html::img($url, ['alt'=>'image-1']),
$url, ['class'=>'example-image-link']);
?>
If you want to redirect to some action in controller, replace $url in last line with ['/controller/action']

Drupal7 managed_file form

I have this managed_file form in a Drupal customized module, with this form a user can upload an image and saved it under sites/default/files.
$form['Background_image'] = array(
'#type' => 'managed_file',
'#title' => t('Image'),
'#progress_message' => t('Please wait...'),
'#progress_indicator' => 'bar',
'#description' => t('Click "Browse..." to select an image to upload.'),
'#required' => TRUE,
///'#upload_validators' => array('file_validate_extensions' => array('jpeg jpg png gif')),
'#upload_location' => 'public://backgroundimage/'
'#default_value' => $this->options['Background image'],
);
how to add a function to get the uploaded file?
I tried this but it didnt work.
$image = file_load($form_state['values']['Background_image']);
You should be able to just create the form element, and then use the $form_state['values'] array to get the fid. like this:
function my_module_form() {
$form = array();
$form['background_image'] = array(
'#type' => 'managed_file',
'#title' => t('Image'),
'#progress_message' => t('Please wait...'),
'#progress_indicator' => 'bar',
'#description' => t('Click "Browse..." to select an image to upload.'),
'#required' => TRUE,
'#upload_location' => 'public://backgroundimage/',
'#default_value' => $this->options['background image'] //fid
);
return $form;
}
function my_module_form_submit($form, &$form_state) {
$file = file_load($form_state['values']['background_image']);
$file->status = FILE_STATUS_PERMANENT;
file_usage_add($file, 'module_name', 'entity_name', $entity_id);
file_save($file);
}
I just wrote that on the fly so I'm sure there are syntax errors :) but that's the idea. If you are not getting the file id from $form_state['values']['background_image'], I would try dying in your submit handler and dumping the contents of $form_state['values']:
function my_module_form_submit($form, &$form_state) {
die(var_dump($form_state['values']['background_image']));
}
That should tell you a few things about whats being returned from your form.

Edit form in drupal module?

I have a problem making Drupal module .
I created a form for adding into database but i am having no luck with creating form to edit some record here is my problem.
The problem is when i load values into form load from database and change them and then click submit button form refresh before it submit new values. So it updates into database same thing as it was. Here is a code :
function edit_form($form, &$form_state) {
$query = db_select('activity', 'f')
->fields('f')
->condition('IDA', $_GET['edit']);
$thefile = $query->execute();
$title = "";
$desc = "";
$file = "";
$privacy = "";
while($record = $thefile->fetchAssoc())
{
$title = $record['title'];
$desc = $record['description'];ick submit button form refresh before it submit new values. So it updates into database same thing as it was. Here is a good :
function edit_form($form, &$form_state) {
$query = db_select('activity', 'f') ->fields('f') ->co
$file = $record['trainingresource'];
$privacy = $record['privacy'];
}
$form['activity'] = array(
'#type' => 'fieldset',
'#title' => t('Create a new activity'),
'#tree' => TRUE,
);
$form['activity']['title'] = array(
'#type' => 'textfield',
'#title' => t('Title'),
'#description' => t('Please enter the title here.'),
'#value' => t($title),
);
$form['activity']['description'] = array(
'#type' => 'textarea',
'#title' => t('Enter Description'),
'#value' => t($desc),
'#description' => t('Please put description here.'),
);
/* $form['activity']['date'] = array(
'#type' => 'date',
'#title' => t('Enter activity date'),
'#description' => t('Please put activity date in here.'),
); */
$form['activity']['file'] = array(
'#type' => 'file',
'#title' => t('Submit activity file'),
'#value' => t($file),
'#description' => t('Please files in here.'),
);
$form['activity']['security'] = array(
'#type' => 'radios',
'#title' => t('Privacy'),
'#value' => t($privacy),
'#options' => array('True'=>t('True'),'False'=>t('False')),
);
// Description
$form['hidden'] = array('#type' => 'value', '#value' => 'is_it_here');
$form['submit'] = array('#type' => 'submit', '#value' => t('Save'));
return $form;
}
And here is a submit form code:
function edit_form_submit($form, $form_state) {
$idt = $_GET['edit'];
$title = trim($form_state['values']['activity']['title']);
$desc = trim($form_state['values']['activity']['description']);
//$date = trim($form_state['values']['activity']['date']['year']."-".$form_state['values']['activity']['date']['month']."-".$form_state['values']['activity']['date']['day']);
$file = "file";
$privacy = trim($form_state['values']['activity']['security']['#value']);
$nid = db_update('activity') // Table name no longer needs {}
->fields(array(
'title' => $title,
'description' => $desc,
//'date' => $date,
'trainingresource' => $file,
'privacy' => $privacy,
))
->condition('IDA', $idt,'=')
->execute();
drupal_set_message($idt);
drupal_set_message("Added into database");
drupal_goto('activity', array('query'=>array(
'activ'=>$_GET['activ'],
)));
}
If someone have the same problem or know how to solve this problem , please help me .
Thanks in advance.
First of all i would like to point out your example code has been pasted wrongly. I see two declaration of same function edit_form.
Am assuming the first declaration was a wrong paste and continuing to answer this.
The major issue i have seeen in your form declaration is that you are using "#value" to store the a default value. Please use "#default_value".
If you use #value, it ignores the user submitted values.
Read more about use of #value.
Read more about use of #default_value
For example change,
$form['activity']['description'] = array(
'#type' => 'textarea',
'#title' => t('Enter Description'),
'#value' => t($desc),
'#description' => t('Please put description here.'),
);
to
$form['activity']['description'] = array(
'#type' => 'textarea',
'#title' => t('Enter Description'),
'#default_value' => t($desc),
'#description' => t('Please put description here.'),
);
Also i strongly recommend you to check this link which is a module that provides lots of examples to interact with Drupal.

Multistep drupal form with tables

Can anyone tell me how to make a multi-step drupal form which prints a table in one of the steps?-
This is the code I already have, it corresponds to the second step of the form. It throws me this error:
Fatal error: Cannot unset string offsets in C:\wamp\www\academicus\includes\form.inc on line 497
function listarAlumnos($nombre, $apellido) {
if($nombre=='') {
$consulta="SELECT * FROM Pinteres WHERE PinApe1='".$apellido."' or PinApe2='".$apellido;
} else if ($apellido=='') {
$consulta="SELECT * FROM Pinteres WHERE PinNom1='".$nombre."' or PinNom2='".$nombre."'";
} else {
$consulta="SELECT * FROM Pinteres WHERE (PinNom1='".$nombre."' or PinNom2='".$nombre."') AND (PinApe1='".$apellido."' or PinApe2='".$apellido."')";
}
$resultado=consultarContacta($consulta);
$form=array();
$header = array(t('Id'), t('Primer nombre'), t('Segundo nombre'), t('Primer apellido'), t('Segundo apellido'), t('Direccion'), t('Telefono'), t('Celular'), t('Email'));
$rows = array();
while ($rs=odbc_fetch_array($resultado)) {
$row=array();
$id=$rs['PinId'];
$primerNombre=$rs['PinNom1'];
$segundoNombre=$rs['PinNom2'];
$primerApellido=$rs['PinApe1'];
$segundoApellido=$rs['PinApe2'];
$direccion=$rs['PinDir'];
$telefono=$rs['PinTelPri'];
$celular=$rs['PinTelCel'];
$email=$rs['PinEMail'];
$row[] = $id;
$row[] = $primerNombre;
$row[] = $segundoNombre;
$row[] = $primerApellido;
$row[] = $segundoApellido;
$row[] = $direccion;
$row[] = $telefono;
$row[] = $celular;
$row[] = $email;
$rows[] = $row;
};
$form['IdIngresado'] = array (
'#title' => t('Id interesado a importar'),
'#type' => 'textfield',
'#required' => TRUE,
'#description' => t('Ingrese el id del interesado a importar de los listados arriba.')
);
$form['CedulaIngresada'] = array (
'#title' => t('Cedula interesado a importar'),
'#type' => 'textfield',
'#required' => TRUE,
'#description' => t('Ingrese la cedula del interesado a importar.')
);
$form['finalizar'] = array (
'#type' => 'submit',
'#value' => t('Finalizar')
);
$output .= theme('table', $header, $rows);
$output .= drupal_render($form);
return $output;
}
I could make it work using some code like this:
$form['serial'] = array(
'#type' => 'textfield',
'#title' => t('serial number'),
'#prefix' => '<table><tr><td>',
'#suffix' => '</td>',
);
but I know it's not the proper way of doing it.
I assume you know how to do the multi-step form. For the table, you can use Drupal's table theme function. If the table contains only markup, you can do something like this:
$form['table'] = array ('#value' => theme('table', $headers, $rows));
$headers are the table headers and $rows are your data.
If the table contains actual form elements (such as selects, textfields, etc.), you can wrap them in a form element that calls a theme function, like so:
$form['table'] = array ('#theme' => 'output_table');
$form['table']['element_1'] = array (...);
$form['table']['element_2'] = array (...);
Within 'theme_output_table', generate your $headers and $rows to feed to 'theme_table' by calling 'drupal_render' on the relevant form elements that are children of $form['table'].