Drupal 7 - get variables from hook_theme - variables

I tried to pass a variable from a custom module to a tpl file.
In my custom module (named example)
1. I created a route with an argument via hook_menu :
function example_menu() {
$items['example/fancybox-photos/%'] = array(
'page callback' => 'example_display_fancybox_photos',
'page arguments' => array(2),
'type' => MENU_CALLBACK,
'access arguments' => array('access content'),
);
return $items;
}
2. I created my page callback function :
function example_display_fancybox_photos($nid) {
$nodePhoto = node_load($nid);
$field_photo = field_get_items('node', $nodePhoto, 'field_photo');
$photo = [
"field_photo" => $field_photo[0]['uri'],
....
];
return theme('example_fancybox_photos', array('infosPhoto' => $photos));
}
3 . I created a hook_theme
function example_theme() {
$themes = array();
$themes['example_fancybox_photos'] = array(
'template' => 'templates/example-fancybox-photos',
'variables' => array('infosPhoto' => NULL),
);
return $themes;
}
4 . I finally created a tpl named "example-fancybox-photos.tpl.php" in templates folder (in theme folder)
<pre><?php print var_dump($infosPhoto); ?></pre>
The result is NULL
I did some researchs but i dont understand why the variable is still NULL.
thanks for your help !

I finally managed to get the variable from the module to the tpl !
1. I created a route with an argument via hook_menu :
function example_menu() {
$items['example/fancybox-photos/%'] = array(
'page callback' => 'example_display_fancybox_photos',
'page arguments' => array(2),
'type' => MENU_CALLBACK,
'access arguments' => array('access content'),
);
return $items;
}
2. I created my page callback function :
function example_display_fancybox_photos($nid) {
$nodePhoto = node_load($nid);
$field_photo = field_get_items('node', $nodePhoto, 'field_photo');
$photos = [
"field_photo" => $field_photo[0]['uri'],
....
];
return theme('example_fancybox_photos', array('infosPhoto' => $photos));
}
3 . I created a hook_theme
function example_theme() {
$themes = array();
$themes['example_fancybox_photos'] = array(
'template' => 'templates/example_fancybox_photos',
'variables' => array('infosPhoto' => NULL),
);
return $themes;
}
4 . I finally created a tpl named "example_fancybox_photos.tpl.php" in templates folder (in MODULE (example) folder)
The problems were that:
- the tpl was not named in the same way and with dashes instead of underscore
- the tpl was in the template folder of the theme and not of the module

You have passed $photos but you have array as $photo. try to change that
Hope the below code helps you.
function example_menu(){
$items['example/fancybox-photos/%'] = array(
'page callback' => 'example_display_fancybox_photos',
'page arguments' => array(2),
'type' => MENU_CALLBACK,
'access arguments' => array('access content'),
);
return $items;
}
function example_display_fancybox_photos($nid){
$photos = 'value from example module!';
return theme('example_fancybox_photos',array('photos' => $photos));
}
function example_theme() {
$path = drupal_get_path('module', 'example');
return array(
'example_fancybox_photos' => array(
'variables' => array('photos' => null),
'template' => 'example_fancybox_photos',
'path' => $path,
),
);
}
Place your tpl file example_fancybox_photos.tpl.php in your module directory and inside it use the below code.
<?php print $photos; ?>
or
function example_theme() {
return array(
'example_fancybox_photos' => array(
'variables' => array('photos' => null),
'template' => 'example_fancybox_photos',
),
);
}
Place your tpl file example_fancybox_photos.tpl.php in your theme directory and inside it place the below code
<?php print $photos; ?>

Related

ExpressionEngine Custom Control Panel tab not working

I'm trying to add a tab to my Publish entry form, I have the following code (pruned for simplicity), but it's not working:
in tab.my_module.php:
public function display($channel_id, $entry_id = '')
{
$settings = array();
$settings = array(
'custom_field' => array(
'field_id' => 'custom_field',
'field_label' => 'custom_field',
'field_type' => 'text'
)
);
return $settings;
}
in upd.my_module.php:
public function install() {
ee()->layout->add_layout_tabs($this->tabs(), 'my_module');
}
public function tabs()
{
$tabs['my_module'] = array(
'custom_field'=> array(
'visible' => 'true',
'collapse' => 'false',
'htmlbuttons' => 'true',
'width' => '100%'
),
);
return $tabs;
}
But hte tab doesnt appear after i reinstall the module, what am I missing?
The problem was caused by having style information in the lang file!
The new tab was actually being included on the Publish and Edit pages but the style in the Tab title was somehow causing the new tab to be hidden.
$lang = array(
'module_name' => 'My Module',
'module_description' => 'Brief description ',
'save_btn' => 'Save',
'save_btn_clicked' => 'Clicked',
'module_name' => '<style color="green">My Module</style>',
);

Yii file CFormInputElement won't display unless explicitly marked "safe"

I'm trying to use Form Builder to build a simple file upload prompt. I want to specify the rule for the file to be similar to
array('formFile', 'file', 'allowEmpty' => false, 'types' => 'html'),
but something is wrong. The file upload element only appears if I explicitly mark the element as 'safe' (and remove the 'file' rule). What am I missing?
models/UploadForm.php
class UploadForm extends CFormModel
{
public $year;
public $formFile;
public function rules ()
{
return array(
array('year', 'required'),
array('year', 'date', 'format'=>'yyyy'),
// array('formFile', 'safe'),
array('formFile', 'file', 'allowEmpty' => false, 'types' => 'html'),
);
}
static public function getYearOptions () {...}
}
views/extranet/uploadForm.php
return array(
'title' => 'Select year',
'method' => 'post',
'enctype' => 'multipart/form-data',
'elements' => array(
'year' => array(
'type' => 'dropdownlist',
'items' => UploadForm::getYearOptions(),
),
'formFile' => array(
'type' => 'file',
'label' => 'form source file',
),
),
'buttons' => array(
'upload' => array(
'type' => 'submit',
'label' => 'upload',
),
),
);
controllers/ExtranetController.php
class ExtranetController extends CController
{
public function actionIndex ()
{
$form = new CForm('application.views.extranet.uploadForm', new UploadForm());
if ($form->submitted('upload') && $form->validate()) {...}
$this->render('index', array('form' => $form));
}
}
The reason for this is very simple.
The form builder only renders input elements which are considered safe (I.E. have a validation rule). What you have done is perfectly fine, except CFileValidator isn't "safe" by default, whereas other validators are safe.
The quickest way to solve this is the following:
// In your model::rules() function
return array(
array('formFile', 'file', 'allowEmpty' => false, 'types' => 'html', 'safe' => true),
);
Refer to these two links for more information: the CFileValidator#safe documentation, and the Github issue for a problem very similar to yours.

Yii select2 - returned data cannot be selected

I have been looking into select2 and yii and have managed to load data via json request/response.
The issue I'm faced with is when I try to select an entry of the returned data, I can not.
Where am I going wrong ? The data returnd by the action is json formatted as CustomerCode and Name
Widget code in form
$this->widget('bootstrap.widgets.TbSelect2', array(
'asDropDownList' => false,
'name' => 'CustomerCode',
'options' => array(
'placeholder' => 'Type a Customer Code',
'minimumInputLength' => '2',
'width' => '40%',
'ajax' => array(
//'url'=> 'http://api.rottentomatoes.com/api/public/v1.0/movies.json',
'url'=> Yii::app()->getBaseUrl(true).'/customer/SearchCustomer',
'dataType' => 'jsonp',
'data' => 'js: function (term,page) {
return {
term: term, // Add all the query string elements here seperated by ,
page_limit: 10,
};
}',
'results' => 'js: function (data,page) {return {results: data};}',
),
'formatResult' => 'js:function(data){
var markup = data.CustomerCode + " - ";
markup += data.Name;
return markup;
}',
'formatSelection' => 'js: function(data) {
return data.CustomerCode;
}',
)));
code snipped from controller action SearchCustomer
Yii::app()->clientScript->scriptMap['jquery.js'] = false;
$this->renderJSON(Customer::model()->searchByCustomer($term));
renderJSON function from base controller class
protected function renderJSON($data)
{
header('Content-type: application/json');
echo $_GET['callback'] . "(";
echo CJSON::encode($data);
echo ")";
foreach (Yii::app()->log->routes as $route) {
if($route instanceof CWebLogRoute) {
$route->enabled = false; // disable any weblogroutes
}
}
Yii::app()->end();
}
Appreciate any help on this
i try.
change
'dataType' => 'jsonp' to 'dataType' => 'json'
and check json format
https://github.com/ivaynberg/select2/issues/920

Zend - inputfilter get randomize name

Hello I'm trying ZF2 form with an input file.
I have a form with a file input and I want to insert the randomize name into my db.
How I can return the randomized name?
thanks.
This is the simple form class:
class OrdineForm extends Formhttp://stackoverflow.com/questions/ask
public function __construct($name = null)
{
parent::__construct('ordine');
$this->setAttribute('method', 'post');
$this->addElements();
$this->addInputFilter();
}
public function addElements(){
$this->add(array(
'name' => 'pdf',
'attributes' => array(
'type' => 'text',
'disabled' =>'true',
),
'options' => array(
'label' => 'PDF',
),
));
// FILE INPUT
$file = new File('file');
$file
->setLabel('PDF attach')
->setAttributes(array(
'id' => 'file',
));
$this->add($file);
$this->add(array(
'name' => 'submit',
'attributes' => array(
'type' => 'submit',
'value' => 'Add',
'id' => 'submitbutton',
'class' => 'btn btn-success'
),
));
}
public function addInputFilter()
{
$inputFilter = new InputFilter\InputFilter();
$fileInput= new FileInput('file');
$fileInput->setRequired(false);
$fileInput->getFilterChain()->attachByName(
'filerenameupload',
array(
'target' => './public/tmpuploads/',
'randomize' => true,
"UseUploadname" => true,
)
);
$inputFilter->add($fileInput);
$this->setInputFilter($inputFilter);
}
}
After you have validated the form in your controller you can use $form->getData();
there should be a key 'file' as that is what you named your file element. Within that a key 'tmp_name'.
This will be the randomized name.
Eg:
public function uploadfileAction()
{
//get form and filter
$form = $this->getServiceLocator()->get('SomeModule\Form\UploadFileForm');
$filter = $this->getServiceLocator()->get('SomeModule\Form\UploadFileFilter');
$form->setInputFilter($filter->getInputFilter());
if ($this->getRequest()->isPost()) {
//merge files with post
$post = array_merge_recursive(
$this->getRequest()->getPost()->toArray(),
$this->getRequest()->getFiles()->toArray()
);
//set data in form
$form->setData($post);
//check is valid- form data will now contain new name
if ($form->isValid()) {
var_dump($form->getData());
}
}
}
The resulting array dump may look something like this:
array(13) {
["file"]=>
array(5) {
["name"]=>
string(14) "some-pdf.pdf"
["type"]=>
string(24) "application/pdf"
["tmp_name"]=>
string(46) "/public/tmpuploads/new-randomized-name.pdf"
["error"]=>
int(0)
["size"]=>
int(651264)
}
["submit"]=>
string(6) "Submit"
["csrf"]=>
string(32) "4df771bb2fb14e28992a408583745946"
}
You can then just do:
$formData = $form->getData();
$fileNewLocation = $formData['file']['tmp_name'];
//do what you want with $fileNewLocation

dynamically adding text boxes in drupal form api

I want to have a add more button on clicking which i can add dynamically, textboxes in a drupal form api.. can someone help on this?
Thanks in advance
Take a look at Adding dynamic form elements using AHAH. It is a good guide to learn AHAH with Drupal's form API.
EDIT: For an example, install the Examples for Developers module, it has an AHAH example you can use to help you learn.
Here is an example how to solve this with Ajax in Drupal 7(If anyone want I can convert it also to Drupal 6 using AHAH(name before it became Ajax)).
<?php
function text_boxes_form($form, &$form_state)
{
$number = 0;
$addTextbox = false;
$form['text_lists'] = array
(
'#tree' => true,
'#theme' => 'my_list_theme',
'#prefix' => '<div id="wrapper">',
'#suffix' => '</div>',
);
if (array_key_exists('triggering_element', $form_state) &&
array_key_exists('#name', $form_state['triggering_element']) &&
$form_state['triggering_element']['#name'] == 'Add'
) {
$addTextbox = true;
}
if (array_key_exists('values', $form_state) && array_key_exists('text_lists', $form_state['values']))
{
foreach ($form_state['values']['text_lists'] as $element) {
$form['text_lists'][$number]['text'] = array(
'#type' => 'textfield',
);
$number++;
}
}
if ($addTextbox) {
$form['text_lists'][$number]['text'] = array(
'#type' => 'textfield',
);
}
$form['add_button'] = array(
'#type' => 'button',
'#name' => 'Add',
'#ajax' => array(
'callback' => 'ajax_add_textbox_callback',
'wrapper' => 'wrapper',
'method' => 'replace',
'effect' => 'fade',
),
'#value' => t('Add'),
);
return $form;
}
function ajax_add_textbox_callback($form, $form_state)
{
return $form['text_lists'];
}
function text_boxes_menu()
{
$items = array();
$items['text_boxes'] = array(
'title' => 'Text Boxes',
'description' => 'Text Boxes',
'page callback' => 'drupal_get_form',
'page arguments' => array('text_boxes_form'),
'access callback' => array(TRUE),
'type' => MENU_CALLBACK,
);
return $items;
}