create OOP using foreach - wordpress

I want to register widgets using foreach
$widgets['Gallery'] = array(
'title' => __('Gallery', 'redux-framework'),
'desc' => __('Creates a custom gallery', 'redux-framework'),
'fields' => array(
array(
'id' => 'ids',
'type' => 'gallery',
'title' => __('Add/Edit Gallery', 'redux-framework'),
'subtitle' => __('Create a new Gallery by selecting existing or uploading new images', 'redux-framework'),
),
)
);
$widgets['textblock'] = array(
'title' => __('Text Block', 'redux-framework'),
'desc' => __('Create a simple block text.', 'redux-framework'),
'fields' => array(
array(
'id' => 'content',
'type' => 'editor',
'title' => __('Content', 'redux-framework'),
'subtitle' => __('Enter some content for this textblock', 'redux-framework'),
),
)
);
foreach ($widgets as $class => $field) {
$class = str_replace('-', '_', $class);
class $class extends Cadr_Widget {
//the rest of methods here
}
if (class_exists($class))
register_widget($class);
}
is it possible to do some thing like this ??
I'm receiving error
Parse error: syntax error, unexpected T_VARIABLE, expecting T_STRING in C:\Dropbox\xampp\htdocs\theme\wp-content\themes\cadr-master\framework\builder\inc\core.php on line 424
without define class inside foreach , I must I write every class and I have a lot of widgets
class Gallery extends cadr_Widget {
/**
* Render the widget in frontend
*
* #param array $args
* #param array $instance
* #return bool|void
*/
function widget($args, $instance) {
//echo $instance['content'];
}
}

Related

A datatable rendred with extra line on the top - SgDatatablesBundle

I am using SgDatatablesBundle 1.0
The datatable is rendred with a line on the top contain inputfileds!
I dont know how to remove it ,Please any help
I have follwed this link to use the bundle :
https://github.com/stwe/DatatablesBundle/blob/master/Resources/doc/installation.md#your-first-datatable
my class postDatatable:
namespace AppBundle\Datatables;
/**
* Class PostDatatable
*
* #package AppBundle\Datatables
*/
class PostDatatable extends AbstractDatatable
{
/**
* {#inheritdoc}
*/
public function buildDatatable(array $options = array())
{
$this->language->set(array(
'cdn_language_by_locale' => true
//'language' => 'de'
));
$this->ajax->set(array( 'url' => $this->router->generate('app_homepage'),
'type' => 'GET'
));
$this->options->set(array(
'individual_filtering' => true,
'individual_filtering_position' => 'head',
'order_cells_top' => true,
));
$this->features->set(array(
));
$this->columnBuilder
->add('name', Column::class, array(
'title' => 'Name',
))
->add('nbPges', Column::class, array(
'title' => 'NbPges',
))
->add('subject', Column::class, array(
'title' => 'Subject',
))
->add(null, ActionColumn::class, array(
'title' => $this->translator->trans('sg.datatables.actions.title'),
'actions' => array(
array(
'route' => 'app_homepage',
'route_parameters' => array(
'id' => 'id'
),
'label' => $this->translator->trans('sg.datatables.actions.show'),
'icon' => 'glyphicon glyphicon-eye-open',
'attributes' => array(
'rel' => 'tooltip',
'title' => $this->translator->trans('sg.datatables.actions.show'),
'class' => 'btn btn-primary btn-xs',
'role' => 'button'
),
),
array(
'route' => 'app_homepage',
'route_parameters' => array(
'id' => 'id'
),
'label' => $this->translator->trans('sg.datatables.actions.edit'),
'icon' => 'glyphicon glyphicon-edit',
'attributes' => array(
'rel' => 'tooltip',
'title' => $this->translator->trans('sg.datatables.actions.edit'),
'class' => 'btn btn-primary btn-xs',
'role' => 'button'
),
)
)
))
;
}
/**
* {#inheritdoc}
*/
public function getEntity()
{
return 'AppBundle\Entity\Post';
}
/**
* {#inheritdoc}
*/
public function getName()
{
return 'post_datatable';
}
}
Take a look at the available options.
You need to set individual_filtering to false to remove the search input fields.

Drupal Custom Entity Page not found

I am actualy trying to implement my first own entity using this tutorial:
http://www.istos.it/en/blog/drupal-entities/drupal-entities-part-3-programming-hello-drupal-entity
So far anything worked fine, but now i ran in some problem I couldnt get fixed.
After creating my new entity, I get redirected to the page "slider/(id)". But it says that the page could not be found. When I try to open the URL manualy I get the same error.
Here is my code:
he_slider.module
/**
* Implements hook_entitiy_info()
*/
function he_slider_entity_info(){
$slider_info['slider'] = array(
'label' => t('Slider Item'),
'controller class' => 'SliderController',
'views controller class' => 'EntityDefaultViewsController',
'base table' => 'slider',
'uri callback' => 'he_slider_uri',
'fieldable' => TRUE,
'entity keys' => array(
'id' => 'sid',
),
'static cache' => TRUE,
'bundles' => array(
'slider'=> array(
'label' => 'Slider',
'admin' => array(
'path' => 'admin/structure/slider/manage',
'access arguments' => array('administer slider'),
),
),
),
'view modes' => array(
'full' => array(
'label' => t('Full Slider Item'),
'custom settings' => FALSE,
),
)
);
return $slider_info;
}
/**
* URI Callback function
*/
function he_slider_uri($slider){
return array(
'path' => 'slider/' . $slider->id,
);
}
/**
* Load the a single or multiple entities
*/
function he_slider_load($sid = NULL, $reset = FALSE){
$sids = (isset ($sid) ? array($sid) : array());
$slider = slider_load_multiple($sids, $reset);
return $slider? reset ($slider) : FALSE;
}
function he_slider_load_multiple($sids = array(), $conditions = array(), $reset = FALSE){
return entity_load('slider', $sids, $conditions, $reset);
}
/**
* Provides the Pages to administer and view the entities
*/
function he_slider_menu(){
$items['admin/content/slider/add'] = array(
'title' => 'Add Slider Item',
'page callback' => 'he_slider_add',
'access arguments' => array('create slideritem'),
);
$items['admin/structure/slider/manage'] = array(
'title' => 'Slider Administration',
'description' => 'Manage Slider Structure',
'page callback' => 'he_slider_info',
'access arguments' => array('administer slideritem'),
);
$items['slider/%slider'] = array(
'title callback' => 'he_slider_page_title',
'title arguments' => array(1),
'page callback' => 'he_slider_page_view',
'page arguments' => array(1),
'access arguments' => array('view slideritem'),
'type' => MENU_CALLBACK,
);
$items['slider/%slider/edit'] = array(
'title' => 'Slider Edit',
'title arguments' => array(1),
'page callback' => 'he_slider_page_edit',
'page arguments' => array(1),
'access arguments' => array('edit slideritem'),
'type' => MENU_CALLBACK,
);
$items['admin/content/slider/add'] = array(
'title' => 'Add Slider Item!',
'page callback' => 'he_slider_add',
'access arguments' => array('create slideritem'),
);
return $items;
}
function he_slider_permission(){
return array(
'administer slideritem' => array(
'title' => t('Administer Slider'),
'restrict access' => TRUE,
),
'view slideritem' => array(
'title' => t('View Slideritems'),
),
'edit slideritem' => array(
'title' => t('Edit Slideritems'),
)
);
}
function he_slider_info() {
return ('Welcome to the administration page for your Slideritems!');
}
function he_slider_page_title($slider){
return $slider->sid;
}
function he_slider_page_view($slider, $view_mode = 'full'){
$slider->content = array();
// Build fields content.
field_attach_prepare_view('slider', array($slider->sid => $slider), $view_mode);
entity_prepare_view('slider', array($slider->sid => $slider));
$slider->content += field_attach_view('slider', $slider, $view_mode);
return $slider->content;
}
function he_slider_field_extra_fields() {
$return = array();
$return['slider']['slider'] = array(
'form' => array(
'title' => array(
'label' => t('Title'),
'description' => t('Slider Title'),
),
),
);
return $return;
}
/**
* Implements the slider add form, where we are able to create our new entities
*/
function he_slider_add() {
$slider = (object) array (
'sid' => '',
'type' => 'slider',
'title' => '',
);
return drupal_get_form('he_slider_add_form', $slider);
}
function he_slider_add_form($form, &$form_state, $slider) {
$form['title'] = array(
'#type' => 'textfield',
'#title' => t('Note'),
'#required' => TRUE,
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Save'),
);
field_attach_form('slider', $slider, $form, $form_state);
return $form;
}
/**
* Implements the Entitiy Edit form
*/
function he_slider_page_edit($slider) {
return drupal_get_form('he_slider_add_form', $slider);
}
/**
* Validates the Entity Add form
*/
function he_slider_add_form_validate($form, &$form_state) {
$slider_submission = (object) $form_state['values'];
field_attach_form_validate('slider', $slider_submission, $form, $form_state);
}
function he_slider_add_form_submit($form, &$form_state) {
$slider_submission = (object) $form_state['values'];
field_attach_submit('slider', $slider_submission, $form, $form_state);
$slider = he_slider_save($slider_submission);
$form_state['redirect'] = "slider/$slider->sid";
}
function he_slider_save(&$slider) {
return entity_get_controller('slider')->save($slider);
}
/**
* Implements hook_views_api().
*/
function he_slider_views_api() {
return array(
'api' => 3,
'path' => drupal_get_path('module', 'slider') . '/views',
);
}
/**
* Implements hook_form_alter().
*/
function he_slider_form_alter(&$form, &$form_state, $form_id) {
if($form_id=='_slider_add_form'){
$form['submit']['#weight'] = 99;
}
}
he_slider.controller.inc:
class SliderController extends DrupalDefaultEntityController {
public function save($slider) {
drupal_write_record('slider', $slider);
field_attach_insert('slider', $slider);
module_invoke_all('entity_insert', $slider, 'slider');
return $slider;
}
}
The problem is here:
$items['slider/%slider'] = array(
Drupal's menu system will look for a function named slider_load(), whereas your entity load function is named he_slider_load(). This causes the router to bail out and throw a 404.
To fix it, simply change that line to
$items['slider/%he_slider'] = array(
And clear your caches.

Load a page with drupal ajax from javascript

I am working on a Drupal module that provides a jvectormap node type.
Everything works fine except the drupal .load(). I use
jQuery("#content").load(Drupal.settings.jvectormapnode.url+'/'+ code +'?ajax=1');
The following happens i click a country on the map and this calls /content/institutes/BE
/content/institutes is an views page with a contextual filter witch grabs the last part of the url and displays some data.
The jvectormap node is included on this same page trough a mini-panel and blocks (the view resides in div #content and the jvectormap in a mini-panel block)
Up to this point everything is ok. Now when i click a second region the URL suddenly switches to /content/undefined.
Let me clarify with an example: I click on Belgium the URL changes to /content/institutes/BE and the view picks this up, then I click France and the URL changes to /content/undefined but the view still reacts correctly and shows the France info. Now I hit F5 to refresh the browser and drupal says that /content/undefined does not exist. If I hit F5 after the first click (Belgium) it reloads the page correctly. The problem seems to happen with consecutive ajax requests. I coud fix this with an url alias so this would handle the F5 refresh edge case seeing everything else works correctly, but if some one else needs more than one node they have a (small) problem.
I suspect the .load is the reason why this is happening.
Any help is welcome thanks.
jvectormapnode.js
(function ($)
{
Drupal.behaviors.jvectormapnode =
{
attach: function (context, settings)
{
$('#jvectormapnode').once('jvectormapnode', function() { //fix duplicating behavior when using ajax
highlighted=JSON.parse(Drupal.settings.jvectormapnode.coloredregions);
//console.log(Drupal.settings.jvectormapnode.coloredregions);
//console.log(highlighted);
//change color of clicked region ==> todo
/*
currentSelected = '';
defaultColor = '#00FF00';
selectedColor = '#FF00FF';
maphandle = $('#map-teste');
maphandle.vectorMap({
map: 'br_en',
onRegionClick: function(event, code){
if(currentSelected !== code) {
if(currentSelected !== ''){
// Deselect, then select new choice
maphandle.vectorMap('set', 'colors', currentSelected, defaultColor);
maphandle.vectorMap('set', 'colors', code, selectedColor);
currentSelected = code;
} else {
// Nothing currently selected, go ahead and select
maphandle.vectorMap('set', 'colors', code, selectedColor);
currentSelected = code;
}
} else {
// Deselect
maphandle.vectorMap('set', 'colors', code, defaultColor);
currentSelected = '';
}
alert(code); // return the state
}
});*/
$('#jvectormapnode').vectorMap({
map: 'world_mill_en',
focusOn: {
x: Drupal.settings.jvectormapnode.x,
y: Drupal.settings.jvectormapnode.y,
scale: Drupal.settings.jvectormapnode.scale
},
color: '#aaaaaa',
hoverColor: false,
hoverOpacity: 0.5,
backgroundColor: 'false',
onRegionClick: function (event, code) {
//if(typeof(afunctiontodo!='undefined') afunctiontodo();
//else
//{
//window.location = Drupal.settings.jvectormapnode.url+'/'+ code;
jQuery("#content").load(Drupal.settings.jvectormapnode.url+'/'+ code +'?ajax=1');
//$('#jvectormapnode').vectorMap('set', 'focus', code);
//showSelectedCountry;
//}
},
series: {
regions: [{
values: highlighted ,
attribute: 'fill'
}]
}
});
});
}
};
}(jQuery));
jvectormapnode.module
<?php
/**
* #file
*/
/**
* #defgroup jvectormapnode : Node
* #ingroup jvectormapnode
* #{
* 20130812 pieterm
* Integrates jvectormapnode into Drupal through the node type system
*/
/**
* Implements hook_libraries_info().
*/
function jvectormapnode_libraries_info() {
$libraries['jvectormap'] = array(
'name' => 'jVectorMap',
'vendor url' => 'http://jvectormap.com/',
'download url' => 'http://jvectormap.com/download/',
'version arguments' => array(
'file' => 'jquery.jvectormap.min.js',
'pattern' => '#jVectorMap version ([0-9\.]+)#',
'lines' => 2,
'cols' => 30,
),
'versions' => array(
'1.2.2' => array(
'files' => array(
'js' => array('jquery.jvectormap.min.js'),
'css' => array('jquery.jvectormap.css'),
),
),
),
);
return $libraries;
}
/**
* Implements hook_view().
*/
function jvectormapnode_view($node, $view_mode) {
$node->content['jvectormapnodebody'] = array(
'#markup' => _jvectormapnode_page($node),
'#weight' => 1,
);
return $node;
}
/**
* Implements hook_theme().
* Overriding the default node template for jvectormapnode pages
*/
function jvectormapnode_theme($existing, $type, $theme, $path) {
$items = array(
'node__jvectormapnode' => array(
// Don't specify the path in the template name.
// Unless you have your template inside a directory within this module.
'template' => 'templates/node--jvectormapnode',
'variables' => array('node' => (object)array()),
// If you want to put the tpl in another location, you can use this key.
//'theme path' => drupal_get_path('module', 'another_module'),
),
);
return $items;
}
/**
* Implements hook_node_info().
*
* We use hook_node_info() to define our node content type.
*/
function jvectormapnode_node_info() {
// We define the node type as an associative array.
return array(
'jvectormapnode' => array(
'name' => t('jvectormapnode'),
'base' => 'jvectormapnode', //function prefix hooks
'description' => t('This is the jvectormapnode node type. It can display interactive maps.'),
'title_label' => t('jvectormapnode page title'),
'locked' => FALSE, //TODO SET TRUE
),
);
}
/**
* Implements hook_node_type_insert().
* lets us know that a new content type has been inserted.
* this gives us a chance to add the fields we want. (called for all node isnert!==>check type)
*/
function jvectormapnode_node_type_insert($content_type) {
if ($content_type->type == 'jvectormapnode') {
// Add default body field
$body_instance = node_add_body_field($content_type, t('Information you want to show on each page before the content of the jvectormapnode module'));
$body_instance['display']['example_node_list'] = array(
'label' => 'hidden',
'type' => 'text_summary_or_trimmed',
);
// Save our changes to the body field instance.
field_update_instance($body_instance);
// Create all the fields we are adding to our content type.
foreach (_jvectormapnode_installed_fields() as $field) {
field_create_field($field);
}
// Create all the instances for our fields.
foreach (_jvectormapnode_installed_instances() as $instance) {
$instance['entity_type'] = 'node';
$instance['bundle'] = 'jvectormapnode';
field_create_instance($instance);
}
}
}
/**
* Define the fields for our content type.
*
* This big array is factored into this function for readability.
*
* #return
* An associative array specifying the fields we wish to add to our
* new node type.
*/
function _jvectormapnode_installed_fields() {
return array(
'jvectormapnode_field_color' => array(
'field_name' => 'jvectormapnode_field_color',
'cardinality' => 1,
'type' => 'text',
),
'jvectormapnode_field_url' => array(
'field_name' => 'jvectormapnode_field_url',
'cardinality' => 1,
'type' => 'text',
),
'jvectormapnode_field_width' => array(
'field_name' => 'jvectormapnode_field_width',
'cardinality' => 1,
'type' => 'text',
),
'jvectormapnode_field_height' => array(
'field_name' => 'jvectormapnode_field_height',
'cardinality' => 1,
'type' => 'text',
),
'jvectormapnode_field_regions' => array(
'field_name' => 'jvectormapnode_field_regions',
'cardinality' => 1,
'type' => 'text',
),
'jvectormapnode_field_scale' => array(
'field_name' => 'jvectormapnode_field_scale',
'cardinality' => 1,
'type' => 'text',
),
'jvectormapnode_field_x' => array(
'field_name' => 'jvectormapnode_field_x',
'cardinality' => 1,
'type' => 'text',
),
'jvectormapnode_field_y' => array(
'field_name' => 'jvectormapnode_field_y',
'cardinality' => 1,
'type' => 'text',
),
);
}
/**
* Define the field instances for our content type.
*
* The instance lets Drupal know which widget to use to allow the user to enter
* data and how to react in different view modes.
*
* This big array is factored into this function for readability.
*
* #return
* An associative array specifying the instances we wish to add to our new
* node type.
*/
function _jvectormapnode_installed_instances() {
return array(
'jvectormapnode_field_url' => array(
'field_name' => 'jvectormapnode_field_url',
'label' => t('URL, format http://www.vliz.be/en/...'),
'widget' => array(
'type' => 'text_textfield',
),
),
'jvectormapnode_field_width' => array(
'field_name' => 'jvectormapnode_field_width',
'label' => t('Map width, format px or %'),
'widget' => array(
'type' => 'text_textfield',
),
),
'jvectormapnode_field_height' => array(
'field_name' => 'jvectormapnode_field_height',
'label' => t('Map height, format px or %'),
'widget' => array(
'type' => 'text_textfield',
),
),
'jvectormapnode_field_regions' => array(
'field_name' => 'jvectormapnode_field_regions',
'label' => t('Regions to be highlighted'),
'widget' => array(
'type' => 'text_textfield',
),
),
'jvectormapnode_field_color' => array(
'field_name' => 'jvectormapnode_field_color',
'label' => t('Highlight color, HEX format #ffffff.'),
'widget' => array(
'type' => 'text_textfield',
),
),
'jvectormapnode_field_scale' => array(
'field_name' => 'jvectormapnode_field_scale',
'label' => t('Initial zoom, nummeric format.'),
'widget' => array(
'type' => 'text_textfield',
),
),
'jvectormapnode_field_x' => array(
'field_name' => 'jvectormapnode_field_x',
'label' => t('Initial x-axis focus, nummeric format.'),
'widget' => array(
'type' => 'text_textfield',
),
),
'jvectormapnode_field_y' => array(
'field_name' => 'jvectormapnode_field_y',
'label' => t('Initial y-axis focus, nummeric format.'),
'widget' => array(
'type' => 'text_textfield',
),
),
);
}
/**
* Implements hook_entity_info_alter().
*
* We need to modify the default node entity info by adding a new view mode to
* be used in functions like node_view() or node_build_content().
*/
function jvectormapnode_entity_info_alter(&$entity_info) {
// Add our new view mode to the list of view modes...
$entity_info['node']['view modes']['example_node_list'] = array(
'label' => t('Example Node List'),
'custom settings' => TRUE,
);
}
/**
* Implement hook_form().
*
* Drupal needs for us to provide a form that lets the user
* add content. This is the form that the user will see if
* they go to node/add/node-example.
*/
function jvectormapnode_form($node, $form_state) {
return node_content_form($node, $form_state);
}
/**
* Implements hook_field_formatter_info().
*/
function jvectormapnode_field_formatter_info() {
return array(
'jvectormapnode_field_color' => array(
'label' => t('jvectormapnode color Handle'),
'field types' => array('text'),
),
'jvectormapnode_field_url' => array(
'label' => t('jvectormapnode url Handle'),
'field types' => array('text'),
),
'jvectormapnode_field_width' => array(
'label' => t('jvectormapnode width Handle'),
'field types' => array('text'),
),
'jvectormapnode_field_height' => array(
'label' => t('jvectormapnode height Handle'),
'field types' => array('text'),
),
'jvectormapnode_field_regions' => array(
'label' => t('jvectormapnode regions Handle'),
'field types' => array('text'),
),
'jvectormapnode_field_scale' => array(
'label' => t('jvectormapnode scale Handle'),
'field types' => array('text'),
),
'jvectormapnode_field_x' => array(
'label' => t('jvectormapnode x Handle'),
'field types' => array('text'),
),
'jvectormapnode_field_y' => array(
'label' => t('jvectormapnode y Handle'),
'field types' => array('text'),
),
);
}
/**
* Implements hook_help().
*/
function jvectormapnode_help($path, $arg) {
switch ($path) {
case 'examples/jvectormapnode':
return "<p>" . t("The Node Example module provides a custom node type.
You can create new Example Node nodes using the <a href='!nodeadd'>node add form</a>.",
array('!nodeadd' => url('node/add/node-example'))) . "</p>";
}
}
/**
* Page callback to show jvectormapnode
*/
function _jvectormapnode_page($n) {
//get params from drupal entity created by user in add content
$dcolor= field_get_items('node', $n, 'jvectormapnode_field_color');
$dcolor=render(field_view_value('node', $n, 'jvectormapnode_field_color',$dcolor[0]));
$durl= field_get_items('node', $n, 'jvectormapnode_field_url');
$durl=render(field_view_value('node', $n, 'jvectormapnode_field_url',$durl[0]));
$dwidth= field_get_items('node', $n, 'jvectormapnode_field_width');
$dwidth=render(field_view_value('node', $n, 'jvectormapnode_field_width',$dwidth[0]));
$dheight= field_get_items('node', $n, 'jvectormapnode_field_height');
$dheight=render(field_view_value('node', $n, 'jvectormapnode_field_height',$dheight[0]));
$dregions= field_get_items('node', $n, 'jvectormapnode_field_regions');
$dregions=render(field_view_value('node', $n, 'jvectormapnode_field_regions',$dregions[0]));
$dscale= field_get_items('node', $n, 'jvectormapnode_field_scale');
$dscale=render(field_view_value('node', $n, 'jvectormapnode_field_scale',$dscale[0]));
$dx= field_get_items('node', $n, 'jvectormapnode_field_x');
$dx=render(field_view_value('node', $n, 'jvectormapnode_field_x',$dx[0]));
$dy= field_get_items('node', $n, 'jvectormapnode_field_y');
$dy=render(field_view_value('node', $n, 'jvectormapnode_field_y',$dy[0]));
//$coloredregions=array();
$exploderegions = explode(",", $dregions);
$coloredregions=array();
foreach ($exploderegions as $region)
{
$coloredregions[$region] = $dcolor ;
}
$coloredregions_object = json_encode($coloredregions);
$jvectormapnodebody.= '<div style="width: '.$dwidth.'; height: '.$dheight.'" id="jvectormapnode"></div>';
libraries_load('jvectormap');
drupal_add_js('/sites/all/modules/vliz/jvectormapnode/js/maps/jquery-jvectormap-world-mill-en.js');
drupal_add_js(array('jvectormapnode' => array('url' => $durl,'coloredregions'=> $coloredregions_object,'scale' => $dscale,'x' => $dx,'y' => $dy)), 'setting');
drupal_add_js('/sites/all/modules/vliz/jvectormapnode/js/jvectormapnode.js');
return $jvectormapnodebody;
}
/**
* #} End of "defgroup jvectormapnode".
*/
It seems that the code argument passed within the onRegionClick callback is undefined.
Can you do a console.log() of that argument to know the exact value? Normally this should be the region code as a string. (i.e.: 'BE', 'NL', ...)
onRegionClick: function (event, code) {
console.log(code);
}
I found out what was causing the undefined, here's the code that works
jQuery("#content").load(Drupal.settings.jvectormapnode.url+'/'+ code ,'ajax=1' ,
function() {Drupal.attachBehaviors('#content');});
hope this helps someone else

Drupal 6 create CRUD grid in settings form

I'm quite new to Drupal and I want to create a custom grid that has some editable columns, some other columns witch checkboxes etc.
I'm using the theme() function to create the table and render it at the settings. Since I cannot find any way to access the form/settings variables, inside the theme function, I create a custom table at the drupal database that will contain the gid values, and I render those rows. For testing purposes I fetch the 'variables' table rows. Here is the code so far:
$form['module_settings']['profile_grid'] = array(
'#type' => 'item',
'#title' => t('Profile Mapping'),
'#theme' => 'profile_mapping_grid'
);
function theme_profile_mapping_grid($sender) {
$header = array('', t('name'), t('value'));
$result = db_query('SELECT v.name, v.value from {variable} v');
while ($pair = db_fetch_object($result)) {
$format = array(
'#type' => 'textfield',
'#size' => 30,
'#value' => $pair->name
);
$hhfield = array(
'#type' => 'textfield',
'#size' => 30,
'#value' => $pair->value
);
$row = array('');
$row[] = drupal_render($format);
$row[] = drupal_render($hhfield);
$rows[] = array('data' => $row);
}
$output = theme('table', $header, $rows, array('id' => 'gridErrors'));
return $output;
}
The grid is generated correctly, but I have an issue. I cannot set the 'name' attribute to the textfield, in order to collect it's value later on, on a submit action.
Furthermore, I'm not sure if this is the best way to create a settings grid.
Any ideas, opinions etc are more than welcome.
According to Drupal 6 Form API Quickstart Guide:
Don't use the '#value' attribute for any form element that can be changed by the user. Use the '#default_value' attribute instead. Don't put values from $form_state['values'] (or $_POST) here! FormsAPI will deal with that for you; only put the original value of the field here.
You have to use '#default_value' => $pair->name not '#value' => $pair->value.
Here is the sample module with settings table.
install file:
<?php
// $Id$
/**
* #file
* The your_module module install file, which handles the install/uninstall tasks.
*
*/
function your_module_install() {
// Create tables.
drupal_install_schema('your_module');
}
/**
* Implementation of hook_schema().
*/
function your_module_schema() {
/* Settings table */
$schema['your_module_settings'] = array(
'description' => 'Stores module settings.',
'fields' => array(
'record_id' => array(
'description' => 'The primary identifier for a record.',
'type' => 'serial',
'unsigned' => TRUE,
'not null' => TRUE),
'item_code' => array(
'type' => 'varchar',
'length' => '255',
'not null' => TRUE),
'setting_one' => array(
'type' => 'varchar',
'length' => '255',
'not null' => TRUE),
'setting_two' => array(
'type' => 'varchar',
'length' => '255')),
'unique keys' => array(
'record_id' => array('record_id')),
'primary key' => array('record_id')
);
return $schema;
}
/**
* Implementation of hook_uninstall().
*/
function your_module_uninstall() {
// Remove tables.
drupal_uninstall_schema('your_module');
}
module file:
<?php
/**
* Implementation of hook_help()
*/
function your_module_help($path, $arg)
{
switch ($path)
{
case 'admin/help#your_module':
return '<p>'. t('Module description.') .'</p>';
}
}
/**
* Implementation of hook_menu()
*/
function your_module_menu()
{
$items = array();
/* module settings page */
$items['admin/settings/your_module'] = array(
'description' => 'Administer your_module module settings.',
'title' => 'Some title',
'page callback' => 'drupal_get_form',
'page arguments' => array('your_module_admin_settings'),
'access arguments' => array('access administration pages'),
'type' => MENU_NORMAL_ITEM,
);
return $items;
}
/**
* Implementation of hook_theme().
*/
function your_module_theme() {
return array(
'your_module_products_settings' => array(
'arguments' => array('form' => NULL),
),
);
}
/**
* Settings form
*/
function your_module_admin_settings(&$form_state)
{
$form['your_module'] = array(
'#type' => 'fieldset',
'#title' => t('Settings'),
'#description' => t('Settings description.'),
);
$form['your_module']['products_settings_table'] = array(
'#theme' => 'your_module_products_settings',
'#tree' => TRUE,
);
$form['your_module']['products_settings_table']['products_settings'] = array();
$result = db_query('SELECT record_id, item_code, setting_one, setting_two FROM {your_module_settings} ORDER BY item_code');
while ($product_setting = db_fetch_object($result)) {
$form['your_module']['products_settings_table']['products_settings'][$product_setting->record_id] = array();
$form['your_module']['products_settings_table']['products_settings'][$product_setting->record_id]['item_code'] = array(
'#type' => 'textfield',
'#default_value' => $product_setting->item_code,
'#size' => 8,
'#maxlength' => 16,
);
$form['your_module']['products_settings_table']['products_settings'][$product_setting->record_id]['setting_one'] = array(
'#type' => 'textfield',
'#default_value' => $product_setting->setting_one,
'#size' => 16,
'#maxlength' => 16,
);
$form['your_module']['products_settings_table']['products_settings'][$product_setting->record_id]['setting_two'] = array(
'#type' => 'textfield',
'#default_value' => $product_setting->setting_two,
'#size' => 40,
'#maxlength' => 255,
);
}
/* "add new row" fields */
$form['your_module']['products_settings_table']['products_settings_new'] = array();
/* new item_code */
$form['your_module']['products_settings_table']['products_settings_new']['item_code'] = array(
'#type' => 'textfield',
'#size' => 8,
'#maxlength' => 16,
'#description' => t('description'),
);
/* new setting_one */
$form['your_module']['products_settings_table']['products_settings_new']['setting_one'] = array(
'#type' => 'textfield',
'#size' => 16,
'#maxlength' => 16,
'#description' => t('description'),
);
/* setting_two */
$form['your_module']['products_settings_table']['products_settings_new']['setting_two'] = array(
'#type' => 'textfield',
'#size' => 40,
'#maxlength' => 255,
'#description' => t('description'),
);
/* Submit button */
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Save Settings'),
'#name' => 'SubmitButton',
);
return $form;
}
/**
* Custom theme function for a table of products settings
*/
function theme_your_module_products_settings($form) {
$header = array(t('Item Code'), t('Setting One'), t('Setting Two'));
$rows = array();
/* saved rows */
foreach (element_children($form['products_settings']) as $key) {
$row = array();
$row[] = drupal_render($form['products_settings'][$key]['item_code']);
$row[] = drupal_render($form['products_settings'][$key]['setting_one']);
$row[] = drupal_render($form['products_settings'][$key]['setting_two']);
$rows[] = $row;
}
/* new row to add */
$row = array();
$row[] = drupal_render($form['products_settings_new']['item_code']);
$row[] = drupal_render($form['products_settings_new']['setting_one']);
$row[] = drupal_render($form['products_settings_new']['setting_two']);
$rows[] = $row;
$output = theme('table', $header, $rows);
return $output;
}
/**
* Submission function for your_module_admin_settings form.
*/
function your_module_admin_settings_submit($form, &$form_state) {
/* processing changes */
if (isset($form_state['values']['products_settings_table']['products_settings'])) {
foreach ($form_state['values']['products_settings_table']['products_settings'] as $record_id => $data) {
if (empty($data['item_code']) && empty($data['setting_one']) && empty($data['setting_two'])) {
/* delete saved row if all fields are empty */
db_query("DELETE FROM {your_module_settings} WHERE record_id=%d", $record_id);
drupal_set_message(t('Deleted.'), 'status');
}
else {
/* update */
db_query("UPDATE {your_module_settings} SET item_code='%s', setting_one='%s', setting_two='%s' WHERE record_id=%d",
$data['item_code'], $data['setting_one'], $data['setting_two'], $record_id);
}
}
}
/* adding new row */
$item_code = $form_state['values']['products_settings_table']['products_settings_new']['item_code'];
$setting_one = $form_state['values']['products_settings_table']['products_settings_new']['setting_one'];
$setting_two = $form_state['values']['products_settings_table']['products_settings_new']['setting_two'];
if (!empty($item_code) && !empty($setting_one) && !empty($setting_two)) {
db_query("INSERT INTO {your_module_settings} (item_code, setting_one, setting_two) VALUES ('%s', '%s', '%s')",
$item_code, $setting_one, $setting_two);
drupal_set_message(t('Added new setting.'), 'status');
}
drupal_set_message(t('Settings updated.'), 'status');
}
You're generating the fields in the theme function and it will not work because the submit function will only act on the fields generated by your form function.
The correct way is to generate all fields in the form function (basically what you're doing now in the theme function) and render them in the theme using drupal_render.
Since I cannot find any way to access the form/settings variables, inside the theme function
The form is passed to the theme function as an argument, in your case $sender, and that's how you access them.
Here's some code, untested, but you get the idea. Remember that the call $output .= drupal_render($form); is very important because it renders the hidden fields needed by the Form API such as the form_id and the CSRF protection. Without this call submit won't work.
function mymodule_grid_form($form_state) {
$form = array();
$form['variables'] = array();
$result = db_query('SELECT v.name, v.value from {variable} v');
while ($pair = db_fetch_object($result)) {
$form['variables'][$pair->name][$pair->name . '_name'] = array(
'#type' => 'textfield',
'#size' => 30,
'#value' => $pair->name
);
$form['variables'][$pair->name][$pair->name . '_value'] = array(
'#type' => 'textfield',
'#size' => 30,
'#value' => $pair->value
);
}
return $form;
}
function theme_mymodule_grid_form($form) {
$header = array('', t('name'), t('value'));
foreach ($form['variables'] as $variable => $values) {
$row = array('');
$row[] = drupal_render($values[$variable . '_name']);
$row[] = drupal_render($values[$variable . '_value']);
$rows[] = array('data' => $row);
}
$output = theme('table', $header, $rows, array('id' => 'gridErrors'));
$output .= drupal_render($form);
return $output;
}
function mymodule_theme() {
return array(
'mymodule_grid_form' => array(
'arguments' => array('form' => NULL),
),
);
}

How To Create New Content Type Programmatically in Drupal 7?

I'm building a module (my_module) in Drupal 7.
It has some functionality and also will create new content type.
In my_module.install I implemented the hook_install (my_module_install).
Can I use more one implementation of hook_install to create new content type (my_cck_install) in this module?
If (yes), how should I do this?
Else: have I do this in another module? :-)
You can't use more than one implementation of hook_install in the same module; in PHP you can't have 2 function with the same name which rules this out.
You would just need to add your new content type in the same hook_install anyway (have a look at how the standard installation profile does it at /profiles/standard/standard.install). This is how I always add new content types from the install file (using the example of a testimonials module):
function testimonial_install() {
// Make sure a testimonial content type doesn't already exist
if (!in_array('testimonial', node_type_get_names())) {
$type = array(
'type' => 'testimonial',
'name' => st('Testimonial'),
'base' => 'node_content',
'custom' => 1,
'modified' => 1,
'locked' => 0,
'title_label' => 'Customer / Client Name'
);
$type = node_type_set_defaults($type);
node_type_save($type);
node_add_body_field($type);
}
}
The following code will create a content type called "Event" with a machine name of 'event' and a title field -
//CREATE NEW CONTENT TYPE
function orderform_node_info() {
return array(
'event' => array(
'name' => t('Event'),
'base' => 'event',
'description' => t('A event content type'),
'has_title' => TRUE
),
);
}
function event_form($node,$form_state) {
$form['title'] = array(
'#type' => 'textfield',
'#title' => t('event Title'),
'#default_value' => !empty($node->title) ? $node->title : '',
'#required' => TRUE,
'#weight' => -5
);
return $form;
}
//END CONTENT TYPE
you should place it in your .module file... if you want do add additional fields to it, let me know and I'll patch you up with the code... good luck!
/**
* Implements hook_node_info()
*/
function mymodule_node_info() {
return array(
'news' => array(
'name' => t('News'),
'base' => 'news',
'description' => t('You can add News here'),
'has_title' => TRUE,
'title_label' => t('News title')
)
);
}
/**
* Implement hook_form()
*/
function mymodule_form($node, $form_state) {
return node_content_form($node, $form_state);
}
Add the implementation to mymodule.install is as follows:
/**
* Implements hook_install().
*/
function mymodule_install() {
node_types_rebuild();
$types = node_type_get_types();|
node_add_body_field($types['news']);
}
You can get a detailed description with code from here
/*
* Implementation in hook node info in .Module file
*/
function test_node_info() {
return array(
'product' => array(
'name' => t('Product'),
'base' => 'product',
'description' => t('Product Title'),
)
);
}
/**
* Implement hook_form()
*/
function product_form($node, $form_state) {
return node_content_form($node, $form_state);
}
/**
* Implements hook_install() in .install file.
*/
function test_install() {
node_types_rebuild();
$types = node_type_get_types();
node_add_body_field($types['product']);
//New way to implement to add fields in your content type
foreach (_test_installed_fields() as $field) {
field_create_field($field);
}
foreach (_test_installed_instances() as $fieldinstance) {
$fieldinstance['entity_type'] = 'node';
$fieldinstance['bundle'] = 'product';
field_create_instance($fieldinstance);
}
}
/*
* Define your fields
*/
function _test_installed_fields() {
$t = get_t();
return array(
'product_title123' => array(
'field_name' => 'product_title123',
'label' => $t('Product Title'),
'type' => 'text'
),
'description123' => array(
'field_name' => 'description123',
'label' => $t('Description'),
'type' => 'text'
),
);
}
/*
* Define your instance of fields
*/
function _test_installed_instances() {
$t = get_t();
return array(
'product_title123' => array(
'field_name' => 'product_title123',
'type' => 'text',
'label' => $t('Product Title'),
'widget' => array(
'type' => 'text_textfield'
),
'display' => array(
'example_node_list' => array(
'label' => $t('Product Title'),
'type' => 'text'
)
)
),
'description123' => array(
'field_name' => 'description123',
'type' => 'text',
'label' => $t('Description'),
'widget' => array(
'type' => 'text_textarea_with_summary'
),
'display' => array(
'example_node_list' => array(
'label' => $t('Description'),
'type' => 'text'
)
)
),
);
}
/**
* Implements hook_uninstall().
*/
function test_uninstall() {
$ournewtype = 'product';
$sql = 'SELECT nid FROM {node} n WHERE n.type = :type';
$result = db_query($sql, array(':type' => $ournewtype));
$nodeids = array();
foreach ($result as $row) {
$nodeids[] = $row->nid;
}
node_delete_multiple($nodeids);
node_type_delete($ournewtype);
}
That's it.

Resources