Drupal allowed_values_function does not get called when creating a field - drupal-7

For some reason my allowed_values_function never gets called when showing a field on a user bundle. Code:
function get_business_units()
{
$options = entity_load('business_unit', FALSE, NULL, FALSE);
$opt = bu_to_list_values($options);
return $opt;
}
function MYMODULE_enable()
{
if (!field_info_field('field_user_business_unit')) {
$field = array(
'field_name' => 'field_user_business_unit',
'type' => 'text',
'settings' => array(
'allowed_values' => array(),
'allowed_values_function' => 'get_business_units',
)
);
field_create_field($field);
// Create the instance on the bundle.
$instance = array(
'field_name' => 'field_user_business_unit',
'entity_type' => 'user',
'label' => 'Business Unit',
'bundle' => 'user',
'required' => FALSE,
'settings' => array(
'user_register_form' => 1,
),
'widget' => array(
'type' => 'options_select',
),
);
field_create_instance($instance);
}
}
The field is created, and even displayed on the users "edit" page when editing their info. But the only value is "Select" or "None". My method is never called (I even placed a debug point). This is all in MYMODULE.install file.

The problem is: 'type' => 'text'.
You have to use: 'type' => 'list_text'.
Allowed values is meaningless for a text type.

Your get_business_units() function needs to be in the MYMODULE.module file; the .install files aren't included in a normal Drupal bootstrap.

Have you tried
drush features-revert MYMODULE ?

Related

CakePHP 2.7 GoogleChart Plugin

First of all, sorry if I'm asking for help regarding this question but I have been working on this for almost a day now. I searched this site and was able to find a post similar to my question but I cannot get it to work.
Anyway, I am using CakePHP 2.x, and I need to show reports via charts. I saw this plugin for CakePHP CakePHP GoogleCharts Plugin by Scott Harwell. I did everything step-by-step and somehow my views keep on appearing empty. I made sure it wasn't because of conflicting files so I decided to make a new CakePHP project, unfortunately, it didn't work.
Here are my codes:
Controller:
<?php
App::uses('AppController', 'Controller');
App::uses('GoogleCharts', 'GoogleCharts.Lib');
class ChartsController extends AppController {
public $uses = array('Student');
public $helpers = array('GoogleCharts.GoogleCharts');
public function test_chart(){
$student= $this->Student->getStudentAges();
$studentAgesChart= new GoogleCharts();
$studentAgesChart->type('LineChart');
$studentAgesChart->options(array('title' => "Student Ages"));
$studentAgesChart->columns(array(
//Each column key should correspond to a field in your data array
'name' => array(
'type' => 'string',
'label' => 'Student Name'
),
'age' => array(
'type' => 'number',
'label' => 'Student Age'
)
));
foreach($student as $row){
$studentAgesChart->addRow(array('age' => $row['Student']['age'], 'name' => $row['Student']['name']));
}
$this->set(compact('studentAgesChart'));
debug($studentAgesChart);
}
}
?>
View:
<div id="chart_div" >
<?php
$this->GoogleCharts->createJsChart($studentAgesChart);
?>
</div>
Debug($studentAgesChart):
object(GoogleCharts) {
[private] type => 'LineChart'
[private] columns => array(
'name' => array(
'type' => 'string',
'label' => 'Student Name'
),
'age' => array(
'type' => 'number',
'label' => 'Student Age'
)
)
[private] rows => array(
(int) 0 => array(
(int) 0 => 'Student 1',
(int) 1 => '17'
),
(int) 1 => array(
(int) 0 => 'Student 2',
(int) 1 => '16'
)
)
[private] options => array(
'width' => (int) 400,
'height' => (int) 300,
'title' => 'Student Ages',
'titleTextStyle' => array(
'color' => 'red'
)
)
[private] callbacks => array()
[private] div => 'chart_div'
}
Model:
public function getStudentAges(){
$student_ages = $this->find('all',
array(
'order' => array('Student.name' => 'ASC'),
'limit' => 3,
'fields' => array(
'Student.name',
'Student.age'
)
)
);
return $student_ages;
}
The way I see it, it doesn't contain any errors but my view is empty.
#Scrappy, do you see any output (JavaScript or HTML) included in the DOM when you view source on your page? Or, is the plugin not generating any content at all? If you do see JavaScript code added, is your page reporting JS errors in the console that might prevent the chart from loading properly? If you do not see the JS code, then you likely have not loaded the plugin in your bootstrap file.
Is the page available on the public Internet for review?
The plugin has not seen updates from me in a few years, but there are a few developers that have forked it and updated it for CakePHP 3.0 too. But, this version should still be working unless something changed on the Google end, which I am sure I would have heard about if that was the case.

zf2 URL Helper customization to add achnor for angularjs router

I have a following Link in zf2
<?php echo $this->translate('Enquiries') ?>
and this router in zf2
'application' => array(
'type' => 'Literal',
'options' => array(
'route' => '/application',
'defaults' => array(
'__NAMESPACE__' => 'Application\Controller',
'controller' => 'Index',
'action' => 'index',
),
),
'may_terminate' => true,
'child_routes' => array(
'default' => array(
'type' => 'Segment',
'options' => array(
'route' => '/[:controller[/:action]]',
'constraints' => array(
'controller' => '[a-zA-Z][a-zA-Z0-9_-]*',
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
),
'defaults' => array(
),
),
),
),
),
which convert above link into
Enquiries
which is fine.
I am using angularjs, which uses anchor fragments a lot.
How can I add achor "#/active" on above zf2 link url, so target url look something like this.
Active Enquiries
do you have a reason why you are not just adding the anchor manually after the url definition url(...).'#/active' ?
if you have, try this:
'route' => '/[:controller[/:action[#/:anchor]]]',
UPDATE:
I checked the source for router and uri and url , it seems that url view helper accepts a 'fragment' key for the third option so try this :
url('[route]',array([params]),array('fragment'=>'/active'));
Zend/View/Helper/Url
Zend/Mvc/Router/Http/TreeRouteStack
Zend/Uri/Uri
Create following view Helper by extending Url
namespace Application\View\Helper;
use Zend\View\Helper\Url;
class MyUrl extends Url {
public function __invoke($name = null, $params = array(), $options = array(), $reuseMatchedParams = false) {
if (isset($params['anchor']) && !empty($params['anchor'])) {
$anchor = $params['anchor'];
unset($params['anchor']);
} else {
$anchor = '';
}
$link = parent::__invoke($name, $params, $options, $reuseMatchedParams);
return $link . $anchor;
}
}
In Module file add following in factory to add newly created helper
public function getViewHelperConfig() {
return array(
'factories' => array(
'myUrl' => function($sm) {
$locator = $sm->getServiceLocator();
$helper = new \Application\View\Helper\MyUrl;
$router = \Zend\Console\Console::isConsole() ? 'HttpRouter' : 'Router';
$helper->setRouter($locator->get($router));
$match = $locator->get('application')
->getMvcEvent()
->getRouteMatch();
if ($match instanceof RouteMatch) {
$helper->setRouteMatch($match);
}
return $helper;
},
),
);
}
Add anchor in URL as parameter
<?php echo $this->translate('Enquiries') ?>

CakePHP: Keep the same checkboxes checked after submit

How can I keep the same checkboxes checked after submit? All the other input fields on the form automatically keeps the values. I thought this would also go for checkboxes, but nope.
echo $this->Form->input('type_id', array(
'multiple' => 'checkbox',
'options' => array(
'1' => 'Til salgs',
'2' => 'Ønskes kjøpt',
'3' => 'Gis bort'
),
'div' => false,
'label' => false
));
I believe this can be done in the controller, but how?
Edit:
Since I posted this question I've changed to CakeDcs Search plugin, because I've gotten this to work with that before. Still... I can't get it to work this time.
Adding model and controller code:
AppController
public $components = array('DebugKit.Toolbar',
'Session',
'Auth' => array(
'loginAction' => '/',
'loginRedirect' => '/login',
'logoutRedirect' => '/',
'authError' => 'Du må logge inn for å vise denne siden.',
'authorize' => array('Controller'),
),
'Search.Prg'
);
public $presetVars = true; //Same as in model filterArgs(). For Search-plugin.
AdsController
public function view() {
$this->set('title_for_layout', 'Localtrade Norway');
$this->set('show_searchbar', true); //Shows searchbar div in view
$this->log($this->request->data, 'debug');
//Setting users home commune as default filter when the form is not submitted.
$default_filter = array(
'Ad.commune_id' => $this->Auth->user('User.commune_id')
);
$this->Prg->commonProcess(); //Search-plugin
$this->paginate = array(
'conditions' => array_merge($default_filter, $this->Ad->parseCriteria($this->passedArgs)), //If Ad.commune_id is empty in second array, then the first will be used.
'fields' => $this->Ad->setFields(),
'limit' => 3
);
$this->set('res', $this->paginate());
}
Model
public $actsAs = array('Search.Searchable');
public $filterArgs = array(
'search_field' => array('type' => 'query', 'method' => 'filterSearchField'),
'commune_id' => array('type' => 'value'),
'type_id' => array('type' => 'int')
);
public function filterSearchField($data) {
if (empty($data['search_field'])) {
return array();
}
$str_filter = '%' . $data['search_field'] . '%';
return array(
'OR' => array(
$this->alias . '.title LIKE' => $str_filter,
$this->alias . '.description LIKE' => $str_filter,
)
);
}
/**
* Sets the fields which will be returned by the search.
*
* #access public
* #return array Database table fields
* #author Morten Flydahl
*
*/
public function setFields() {
return array(
'Ad.id',
'Ad.title',
'Ad.description',
'Ad.price',
'Ad.modified',
'User.id',
'User.first_name',
'User.middle_name',
'User.last_name',
'User.link',
'User.picture_url',
'Commune.name',
'Type.id',
'Type.name'
);
}
You have to set manually the selected option of the input, as an array with "keys = values = intval(checkbox id)"
I cannot explain why this format, but this is the only way I get it to work.
Here is my code:
echo $this->Form->create('User');
// Read the submitted value
$selected = $this->Form->value('User.Albums');
// Formats the value
if (empty($selected)) {
$selected = array(); // avoid mess
} else {
$selected = array_map('intval', $selected);
$selected = array_combine ($selected, $selected);
}
// Renders the checkboxes
echo $this->Form->input('Albums',array(
'type' => 'select',
'multiple' => 'checkbox',
'options' => $albums, // array ( (int)id => string(label), ... )
'selected' => $selected, // array ( (int)id => (int)id, ... )
));
Hope this helps.
++

Comstum magento extention doesnt save form post value

I'm trying to create a custom magento extension.
It works, only 1 form field is not saved to the db.
public function saveAction()
{
if ($postData = $this->getRequest()->getPost()) {
$model = Mage::getSingleton('foo_bar/baz');
$model->setData($postData);
try {
$model->save();
Mage::getSingleton('adminhtml/session')->addSuccess($this->__('The baz has been saved.'));
$this->_redirect('*/*/');
return;
}
catch (Mage_Core_Exception $e) {
Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
}
catch (Exception $e) {
Mage::getSingleton('adminhtml/session')->addError($this->__('An error occurred while saving this baz.'));
}
Mage::getSingleton('adminhtml/session')->setBazData($postData);
$this->_redirectReferer();
}
}
The form:
protected function _prepareForm()
{
$model = Mage::registry('foo_bar');
$form = new Varien_Data_Form(array(
'id' => 'edit_form',
'action' => $this->getUrl('*/*/save', array('id' => $this->getRequest()->getParam('id'))),
'method' => 'post'
));
$fieldset = $form->addFieldset('base_fieldset', array(
'legend' => Mage::helper('checkout')->__('Baz Information'),
'class' => 'fieldset-wide',
));
if ($model->getId()) {
$fieldset->addField('id', 'hidden', array(
'name' => 'id',
));
}
$fieldset->addField('name', 'text', array(
'name' => 'name',
'label' => Mage::helper('checkout')->__('Name'),
'title' => Mage::helper('checkout')->__('Name'),
'required' => true,
));
$fieldset->addField('stock', 'text', array(
'name' => 'stock',
'label' => Mage::helper('checkout')->__('stock'),
'title' => Mage::helper('checkout')->__('stock'),
'required' => true,
));
$form->setValues($model->getData());
$form->setUseContainer(true);
$this->setForm($form);
return parent::_prepareForm();
}
}
The value of the 'stock field is not saved'.
I checked that the column stock exist in the db and en name's are the same.
Does anyone know what I'm doing wrong?
Thanks in advance.
If you have added stock field after all the others it is possible that you only need to clear cache through admin System -> Cache Management (Flush Magento Cache and Flush Cache Storage buttons).
Magento likes to cache previous queries so adding new fields without clearing the cache can cause problems with new columns not being saved.

Saving data array in AppModel with CakePHP

I have this function in CakePHP's AppModel (This is used to install initial data in CakePHP) However, I can't seem to get it to save my data, and I get no errors.
Here is my function inside App/Model/AppModel.php:
public function importData() {
$initialOptionData = array(
array( 'Option' => array( 'name' => 'version', 'value' => '1.0.0', )),
array( 'Option' => array( 'name' => 'site-name', 'value' => 'Site Title', )),
);
$this->create();
$this->saveMany($initialOptionData);
}
From you posted code it seems you're trying to save you data to options table, and to do that you need to use Option model.
But you're code is within AppModel, so first import Option model and then execute your save statements.
Your code should look like:
public function importData() {
$initialOptionData = array(
array( 'Option' => array( 'name' => 'version', 'value' => '1.0.0', )),
array( 'Option' => array( 'name' => 'site-name', 'value' => 'Site Title', )),
);
App::import('model','Option'); // Import the Option Model
$Option = new Option(); // create instance of Option class
// save statements
$Option->create();
$Option->saveMany($initialOptionData);
}
Note
Code you're trying will work if you write that within app/model/Option.php file.
I suppose it would be enough to store the values as model property. No need to call $this->save...
public $initialOptionData = array(
array( 'Option' => array( 'name' => 'version', 'value' => '1.0.0', )),
array( 'Option' => array( 'name' => 'site-name', 'value' => 'Site Title', )),
);
all models will inherit initialOptionData...

Resources