Why isn't my managed file getting saved? Please save me from ripping out the rest of my hair...

I've got a "managed_file" field in a form; nothing special.  When the form is submitted, I run something like the following code to, presumably, catch and save it:

$destination = "public://video_posters";
$file_return = file_save_upload('field_poster_frame', array('file_validate_extensions' => array('jpg jpeg png gif')), $destination, FILE_EXISTS_RENAME);
if ($file_return) {
     $file_return->status = FILE_STATUS_PERMANENT;
     file_save($file_return);
     file_usage_add($file_return, 'my_module', 'node', $some_nid);
}

(There is more testing of $file_return to catch the other cases, and a few other things, but you get the idea.)

What's happening is:

An entry shows up in the file_managed table that is correct except that its uri is temporary://the_file_name.jpg instead of, presumably, public://video_posters/the_file_name.jpg.
The file was indeed uploaded and is in the indicated place in temp storage -- just not where I want it to be.

Am I missing something obvious?  Any things to check on?  This is really driving me over the edge.  Thanks!

The managed_file element handles moving the file into place and adding a file record, you don't need to save it yourself. The file module does all this in a validation function which makes the fid available in the submit handler.

So, for example, if your file element is defined with $form['file_id'] = ..., you can change your code to something like the following

$fid = $form_state['values']['file_id'];
$file = file_load($fid);
$file->status = FILE_STATUS_PERMANENT;
file_save($file);
file_usage_add($file, 'my_module', 'node', $some_nid);


Image{cache,style} for compression? Has anyone seen modules that provide image effects for post-generation compression?

I'm thinking things like running the image through a tool like optipng, or similar.

For Drupal 7, the best thing I've seen/used for this is ImageAPIOptimize.

To use it properly you can either use an external toolkit like Yahoo SmushIT! or different options on your server like optipng as you mention above, among others.  See screenshot for partial config screen.  I've run tests with GD, ImageMagick and this module and it produces the best results (in my testing).

Config screen from admin/config/media/image-toolkit:


Moving File Directory to Other Partition I want to know if it's possible to move the files directory, put it in another partition, and point to it. I've tried several methods and can't find the solution.

This is what I've tried:

I created a second partition on my disk and moved all /files/ folders into it, so I have a D:/files folder.
I went to admin/config/media/file-system and changed the 'Public file system path' prompt from 'sites/FirstProject/files' to D:/files/.

However, the styles are missing from the site and I don't know why.

The installation path of my project is C:/xampp/htdocs/www/proyects/sites/FirstProject/files (it is a multi-site installation), and I want to move the files directory to this partition, D:/files.

Can someone help me?

Thanks in advance.

It's probably easier to simply use symlinks to point to the new folder. That way, you can leave the default settings as they are. In addition, Windows will deal with the change instead of Drupal. Move the files folder to D:/files, open a command prompt (cmd), and run the following:

C:\> mklink /j "C:\xampp\htdocs\www\proyects\sites\FirstProject\files" d:\files\

Are you sure its proyects and not projects?


How to manage translations when a site is being re-installed frequently? Sites built on a profile, will, during it's early development experience frequent re-installs.

If a translator makes changes to a site, these will get lost when the database is dropped.

What options are there for handling this, in a way that survives re-installs?

The only way is to make a copy of the translation options.

I'm not sure if a hook_cron or a drush can donwload the files, if not the only way is to donwload and them copy into
../profiles/myprofile/translations/*.po


Add field_tags on module install Is it possible to add the field field_tags in mymodule_install() like the body field?
I added a body field with node_add_body_field. I can see the field in field_config_instance table. Is there a posibility to add field_tags in hook_install() without doing it in the GUI?

Is it done by field_create_field?

if (!field_info_field('my_field')) {
  field_info_cache_clear();

  $field = array(
    'field_name' => 'my_field',
    'type' => 'custom_field_type',
    'cardinality' => 1
  );
  field_create_field($field);
}

But how to set the values for a default article or gui custom like tags field?

Yeah, i know according to strict forum rules it's not fine to answer your own question :-)
But anyway ...

I not realized, that the default fields are stored in table field_config and just a instance for a node in table field_config_instance.

I added the following lines to mymodule_install() of my module:

$instance = array(
  'field_name' => 'field_tags',
  'entity_type' => 'node',
  'label' => 'Tags',
  'bundle' => 'mynode',
  'widget' => array(
    'type' => 'textfield',
  ),
);

I don't need field_create_field() because the field_tags already exists.

And i added a field to the custom node form:

function mymodule_node_form($form, &$form_state, $node) {
...
   $form['field_tags'][LANGUAGE_NONE] = array(
       // '#entity_type' => 'node',
      '#type' => 'textfield',
      '#title' => t('Tags'),
       // '#autocomplete_path' => 'taxonomy/autocomplete/field_tags',
      '#field_name' => 'field_tags',
       // '#bundle' => 'mymodule',
      '#element_validate' => array(
                                 0 => 'taxonomy_autocomplete_validate',
                             ),
       //    '#after_build' => array(
       //                        0 => 'field_form_element_after_build',
       //                      ),
      '#field_parents' => array(),
      '#language' => LANGUAGE_NONE,
      '#columns' => array(
                        0 => 'tid',
                    ),
      '#parents' => array(
                       0 => 'field_tags',
                       1 => LANGUAGE_NONE,
                    ),
   );
...
}

I tried to find out the obligate values. I'm not sure if it's wise to add more values?! I just realized that some values are not nescessary (the commented ones).


How can I implement this floating sidebar block? I'm going to implement a floating sidebar block that can contain user's selections. It is a kind of cart. Please check the image below.

If the use press 'Add to my favorite', then it should be contained in the sidebar.
The floating sidebar block should slide up and down with buttons. Each item of it should be removed if the user press some kind of cross mark at the edge of item.
After selection, the user can check all the items which have selected using 'View my favorites' button.

What is the right solution to do this?
I was thinking that I needed to use 'Views module'. But I can't imagine how to make this sidebar slided.

You can achieve it with HotBlocks module, Check out the screencast

Add, remove, and reorder nodes or blocks to a page without leaving or
reloading the page or using editors
Content added to hotblocks can be constrained to individual pages or
be made global to display on all pages that contain the hotblock
Can display multiple instances of the same block or node in multiple
regions
Can give end users the ability to add and remove blocks to pages
without exposing the administer blocks permission
Provides a means to filter which of those blocks are available to the
user for adding so every block in the system is not exposed
See an overview and administer all of your assigned hotblock content
grouped by region, url, or taxonomy on a single page
Allow users to add and remove content to a page without giving them
permission to edit that content
Advanced permissioning possible - allows you to control which roles
can assign/remove/reorder each type of content to every hotblock
individually if necessary
You can use your own custom icon set for the UI controls to customize
look and feel
If you don't like the term "hotblock" you can customize the
terminology exposed to the user to suit your purposes

and for floating use Floating block module.


How to change Drupal's default login error text I have tried using this code -

     */
    function customform_demo_form_alter(&$form, &$form_state, $form_id) {
     global $user;

      if ($form_id == 'user_login'); {
        if (!$user->uid) {
            array_unshift($form['#validate'],'customform_demo_user_login_form_validate');
        }else{
        drupal_get_messages();
        }
      }

}

function customform_demo_user_login_form_validate(&$form, &$form_state) {
  drupal_set_message('Your username or password was not recognized. Click here to reset your password.', 'status');
}

but can't get the message in the default format.

I'm pretty sure you shouldn't have a semi-colon after your if condition.

 if ($form_id == 'user_login'); {}

Does removing that have any effect?


Checking caller of a hook Is it possible to know which code called a hook? I have two cases--one where I want to return, one where I want to continue.

Anonymous user views a page, thus firing hook_entity_load() (I want to deny this--return)
Cron creates page as anonymous user, thus firing hook_entity_load() (I want to accept this--continue)

If I can check to see if cron called the hook, I'll continue. Is there a way to do this?

I don't know of a "drupal" way to do this but The calling function will be in the backtrace. I have two helpers I use strictly for debugging. It's not a pretty solution but you might be able to check calling function.

Calling function:

// Returns the name of the calling function.
// Since this function call adds to the stack [0]
// The function calling this adds to the stack [1]
// That means [2] is the desired function name.
function getCallingFunction()
{
  $callers = debug_backtrace();
  return $callers[2]['function'];
}

Full stack:

// Returns the full stack.
function getCallingFunctionStack()
{
  $callers = debug_backtrace();
  $stack = array();
  foreach ($callers as $caller)
  {
    $stack[] = $caller['function'];
  }

  return implode('->', $stack);
}

I do not see a way to prove you are in a cron run but You can check if cron is running with:

if (!lock_acquire('cron', 0)) {
  // cron is running.
}

But this does not mean you are a cron user. It just means cron is running during this access attempt.

You could do something like store the cron session id in a variable on hook_cron_queue_info then check if that is the current session id. Kind of dirty but pretty much guarantees you are in cron.

Several other ideas can be found on this question.


Sub-Website within a bigger website I want to create an entirely new website within a drupal7 website.
 For example:
www.school.edu will have theme A (not sure if theme's the right word, basically, different looking webpage). And all its subpages and paths will have the same thing. (i.e. www.school.edu/news, wwww.school.edu/about, www.school.edu/contact ... etc).
 And, I want a new website within www.school.edu to exist. And that new website should have a different theme.

 for example:
www.school.edu/compsci will have theme B. And all the subpages that follows under compsci/ should all have the same themes; by having a different theme, I mean they will have different headers, different logos, different main menus, different everything, basically entirely new website. (i.e. www.school.edu/compsci/news, www.school.edu/compsci/about, www.school.edu/compsci/contact

I have looked around for answers; it's just that I haven't been able to phrase my question well and I thought if I explained it as such, I would be able to get more accurate answers.

With the code below, I have been able to make each subpage that exist under /compsci to go to page__layout_1 ...

function theme_preprocess_page(&$vars, $hook) {
    $path = drupal_get_path_alias($_GET['q']);
    $current_page_path = explode('/', request_path());

    if ($current_page_path[0] == 'compsci') {
      $vars['theme_hook_suggestions'][] = 'page__layout_1';
    }
}

Now, the question is, how I would be able to define different main-menus, different nav-bars, so on. I am quite new to drupal so some terms I am still unfamiliar with -- do I create custom themes or custom modules -- what's the best approach to this?

You can set different themes using hook_custom_theme()

function HOOK_custom_theme() {
  if(arg(0, drupal_get_path_alias()) == 'compsci') {
    return 'theme_machine_name';
  }
}

When you create menus, they will create a block. You can enable the menu blocks on a per-theme basis.


Webform User Contact Form in Block I cant seem to find any solid info on how to do this in the Webform module, is there a function or a module that goes with webforms to do this?

Thanks

Webforms when created are nodes by default. In drupal 6 there was a module called webform block (http://drupal.org/project/webformblock) this got encorprated into webform with webform 3 (which as your using drupal 7 you will be using, I dont think its even possible to get webform 2.x on D7)

To get the webform as block:

Create your webform in a node.
Edit the node.
Select the Webform tab.
Select the Forms settings tab.
Select the Forms settings tab.
Select Advanced settings.
Switch on Available as block.
Save configuration.

Source: http://drupal.org/node/1447436


How I can give a particular style to maps in drupal site based on gmap module I am currently developing a website which makes heavy use of gmap and location module.
I want to style maps in a particular style by appending style to google.maps.MapOptions.styles array, But maps in website still come out plain defaults.
I am not sure how I have to proceed, as firebug reports that style changes are done properly in styles array

(function() {
var style = [
{
    featureType: "landscape",
    elementType: "all",
    stylers: [
    { hue: "#ffa200" },
    { lightness: -20 }
    ]
},{
    featureType: "water",
    elementType: "all",
    stylers: [
    { hue: "#ff9100" },
    { lightness: 52 }
    ]
},{
    featureType: "administrative",
    elementType: "labels",
    stylers: [
    { hue: "#1100ff" },
    { saturation: -100 },
    { lightness: -18 }
    ]
},{
    featureType: "poi",
    elementType: "all",
    stylers: [
    { lightness: -18 },
    { visibility: "off" }
    ]
},{
    featureType: "landscape",
    elementType: "all",
    stylers: [
    { visibility: "off" }
    ]
},{
    featureType: "water",
    elementType: "labels",
    stylers: [
    { lightness: -18 },
    { visibility: "off" }
    ]
},{
    featureType: "road",
    elementType: "labels",
    stylers: [
    { visibility: "off" }
    ]
},{
    featureType: "administrative",
    elementType: "geometry",
    stylers: [
    { visibility: "simplified" }
    ]
},{
    featureType: "road.highway",
    elementType: "geometry",
    stylers: [
    { saturation: -100 }
    ]
},{
    featureType: "road.arterial",
    elementType: "geometry",
    stylers: [
    { saturation: -100 }
    ]
},{
    featureType: "road.local",
    elementType: "geometry",
    stylers: [
    { lightness: -27 }
    ]
},{
    featureType: "transit",
    elementType: "all",
    stylers: [
    { visibility: "off" }
    ]
}
];

Drupal.behaviors.sepiaStyle = function(context) {
Drupal.gmap.addHandler('gmap', function(elem) {
    var obj = this;
    obj.bind("bootstrap_options", function() {
    var new_style = $.extend(obj.vars.styles, style)
    jQuery(elem).change(function() {
        obj.vars.styles= new_style;
    });

    });

});
};
}());

Any help is greatly appreciated. Thanks in advance

I managed to do it by changing a little bit the gmap.js file. At the line 358

obj.bind("boot", function () {
    obj.map = new google.maps.Map(elem, obj.opts);
});

Add these line:

obj.bind("boot", function () {
     obj.opts.styles = [
                                        {
                                            "featureType": "water",
                                            "stylers": [
                                                { "color": "#808084" }
                                            ]
                                        },{
                                            "featureType": "road",
                                            "stylers": [
                                                { "color": "#c8cacc" }
                                            ]
                                        },{
                                            "featureType": "landscape.man_made",
                                            "stylers": [
                                                { "color": "#b0b3b4" }
                                            ]
                                        },{
                                            "featureType": "road",
                                            "elementType": "labels.text.fill",
                                            "stylers": [
                                                { "color": "#000000" }
                                            ]
                                        },{
                                            "featureType": "poi",
                                            "stylers": [
                                                { "color": "#9c9ea2" }
                                            ]
                                        },{
                                            "featureType": "poi",
                                            "elementType": "labels.text.fill",
                                            "stylers": [
                                                { "color": "#000000" }
                                            ]
                                        },{
                                            "featureType": "administrative",
                                            "elementType": "labels.text.fill",
                                            "stylers": [
                                                { "color": "#808080" }
                                            ]
                                        },{
                                            "featureType": "landscape.natural",
                                            "stylers": [
                                                { "color": "#808084" }
                                            ]
                                        },{
                                            "featureType": "transit",
                                            "stylers": [
                                                { "color": "#c9c9cc" }
                                            ]
                                        },{
                                            "featureType": "transit.station.rail",
                                            "stylers": [
                                                { "color": "#838080" }
                                            ]
                                        },{
                                            "featureType": "road.arterial",
                                            "stylers": [
                                                { "color": "#adaeb1" }
                                            ]
                                        },{
                                            "featureType": "poi",
                                            "elementType": "labels.icon",
                                            "stylers": [
                                                { "color": "#3e3d3a" },
                                                { "visibility": "off" }
                                            ]
                                        },{
                                            "featureType": "transit.station",
                                            "elementType": "labels",
                                            "stylers": [
                                                { "visibility": "off" }
                                            ]
                                        },{
                                        }
                                    ];
    obj.map = new google.maps.Map(elem, obj.opts);

});

Also check this thread:

drupal.org


Add a JOIN with a subquery into a views query Here's my SQL, which I am trying to include in hook_views_query_alter() to modify the uc_catalog view (from Ubercart 3):

JOIN (
   SELECT uc_products.nid, MIN(uc_products.sell_price) AS min_price
   FROM uc_products
   JOIN node as n ON n.nid = uc_products.nid
   WHERE uc_products.nid IN
   (
     # in an ideal world, this is the WHERE statement from my views query
     SELECT ti.nid AS nid
     FROM taxonomy_index ti
     WHERE ti.tid = :db_condition_placeholder_1
     AND n.status = :db_condition_placeholder_2
     AND n.type IN :db_condition_placeholder_3
     GROUP BY uc_products.model
   )
 ) AS s2
 ON node.nid = s2.nid AND uc_products.sell_price = s2.min_price

I am confused as to how to make this work with the tools in views_plugin_query_default since this SQL has a subquery, etc. that is more complex than a simple JOIN statement.  I am having a hard time conceptualizing using add_relationship or add_table to make this work.  Is there something about $join building I don't understand.

After some work this problem was solved with the Views Field View module.


How to obtain a list of JS files from enabled modules, or expose such list from a theme as library? I'm in the process of extending jQuery Multi module. Libraries API libraries was built in, I have already added support for JavaScript libraries provided by modules, so with minimal cooperation on the side of modules' authors I have that part covered. Now time to add themes to the list - and I'm stuck.

I found no way to make a theme use hook_library() and by the API docs it's a module hook, so I can't use method I used for modules.

I can use list_themes() to list themes, but how to see a JS files?

list_themes() returns an array of objects:

The keys are the themes' machine names and the values are objects having the following properties:

scripts: An associative array of JavaScripts, using the filename as key and the complete filepath as value. Not set if no scripts are defined in the .info file.


Render only one field of an entity On my controller for a custom page I've loaded an entity and I want to render, on the template for this custom page, only a field of the loaded entity. I would like to get the render array for this field.

Is it possible?
I don't want to create a template for this content type only for this

This is an example for D8:

$node = Node::load('1');
$display_settings = array(
  'label' => 'inline',
);
$build = $node->body->view($display_settings);


Use Context to load JavaScript on certain pages Is it possible to load a JavaScript file on certain pages with the Context module?

The Context Add Assets module does exactly that :)

Taken from the README

  Supports adding active theme files to page via context

I've used 7.x-1.0-beta1 with no major problems, so don't be afraid that there's no full release :)


How do I populate an address field in php? I want to import data from a external source and so am writing a module that creates content by populating the fields of node bundles in code. I followed this guide which is great.

So I am working on adding lists of properties (flats and houses) that belong to estates. I am using an address field to store the address and found this comment on the address field module page that tells me that the address field is an array and so I can access each element and set it in turn.

But what are the address field element and how do I get a list of them? Can they be anything I want? Does the create content form create the array when the form is submitted and therefore the form labels are just a guide or do I have to match them in my code? For example, a UK address has two textboxes for address (address1 and address2) that do not match any of the element names in the module documentation.

But what are the address field element and how do I get a list of them?

You can get a list of the available field columns from addressfield_field_schema():

country
administrative_area
sub_administrative_area
locality
dependent_locality
postal_code
thoroughfare
premise
sub_premise
organisation_name
name_line
first_name
last_name
data

  Can they be anything I want?

Not by default, but as the addressfield module uses ctools plugins, it's easy to extend to add your own if necessary (see the Address Field Phone module for inspiration).

  Does the create content form create the array when the form is submitted and therefore the form labels are just a guide

Exactly right, the addressfield module provides labels and fields based on the currently selected country. They can be whatever suits the locale, but if you look at the names of the form elements, or inspect the field array on form submissions, you'll see they always match the keys from the field schema hook above. There's an excellent answer to a question on SO which goes some way to explaining the reasons for this implementation.

For a UK address specifically, you would populate it roughly like this:

$node->field_address[LANGUAGE_NONE][0] = array(
  'organisation_name' => 'Company',
  'first_name' => 'Joe',
  'last_name' => 'Bloggs',
  'country' => 'GB',
  'thoroughfare' => 'Street address 1',
  'premise' => 'Street Address 2',
  'locality' => 'Town/City',
  'administrative_area' => 'County',
  'postal_code' => 'SW1 1AA',
);


Node id of home page If I choose a node to be the home page, how can I get its node id in the page template?

Can menu_get_item() be used for this?

@Oswald: thanks for pointing in the right direction. This snippet does exactly what I need:

$front_url = variable_get('site_frontpage', 'node');
$front_url = trim($front_url, '/');
$front = explode('/', $front_url);
if( $front[0]=='node' && ctype_digit($front[1]) ) {
  $front_nid = $front[1];
}
echo $front_nid;


It's true that policy file in drush prevents sql-sync from local to prod? I know in the policies file in drush there was/is a way to prevent sql-sync'ing from local to prod.

Is this still true? If so how do you go about this?

Yes this is still true you can find the relevant snippet in the drush source code:

/**
 * Implement of drush_hook_COMMAND_validate().
 *
 * Prevent catastrophic braino. Note that this file has to be local to the machine
 * that intitiates sql-sync command.
 */
function drush_policy_sql_sync_validate($source = NULL, $destination = NULL) {
  if ($destination == '@prod') {
    return drush_set_error(dt('Per examples/policy.drush.inc, you may never overwrite the production database.'));
  }
}

You should include the policy.drush.inc in your .drush folder usually located in the users home folder.


Trying to get a field from a fetched entity in rules I'm trying to use PHP evaluation in rules, and I'm having some trouble getting the data.

This is the beginning of the variable $entity_fetched:

Test 103
stdClass Object
(
[vid] => 611
[uid] => 1
[title] => Test 103
[log] =>
[status] => 1
[comment] => 1
[promote] => 1
[sticky] => 0
[nid] => 611
[type] => calendar_event
[language] => und
[created] => 1380898459
[changed] => 1380898459
[tnid] => 0
[translate] => 0
[revision_timestamp] => 1380898459
[revision_uid] => 1
[body] => Array
(
)
[field_date_time] => Array
(
[und] => Array
(
[0] => Array
(
[value] => 1380898800
[value2] => 1380898800
[timezone] => America/Detroit
[timezone_db] => UTC
[date_type] => datestamp

I'm trying to get the value under field_date_time, but trying to get it as an array gives me an error that I am trying to get arrays from a stdClass object.

<?php print_r($entity_fetched['field_date_time']['und']['0']['value']); ?>

So then I try to do this:

<?php print_r($entity_fetched->field_date_time->und->0->value); ?>

and it gives me an error:

Parse error: syntax error, unexpected T_LNUMBER, expecting T_STRING or T_VARIABLE

What am I doing wrong here? How do I get this information?

Correct way to get the value is:

<?php print_r($entity_fetched->field_date_time['und']['0']['value']); ?>

The $entity_fetched is returning an object so to access it values you would need to use -> operator, and than you have array contents which you can access using the array subscript operator [].

Note: You cannot access object members via the array subscript operator [].
For accessing the object members you need to use the -> operator.
And to access the array contents we use the [] operator.


How do I format JQuery in Drupal 8? I'm trying to write a simple JQuery function in order to animate my mobile navigation. However, I'm not sure how to format the .js file. I've looked up some examples online, but I couldn't get my function to work, when I tried to use the example templates. Here's what I'm currently using, which works in Chrome, but FireFox logs an error, which I'll also post below:

My code:

(function ($, Drupal) {
      $(function(){
        $( '#mobile-menu-toggle-button' ).click(function(){
          $( '.mobile-menu-toggle' ).toggleClass( "open" );
        });
        $( '.overlay' ).click(function(e){
          if(e.target != this) return;
          $( '.mobile-menu-toggle' ).toggleClass( "open" );
        });
      });
})(jQuery, Drupal);

FireFox errors:

ReferenceError: Drupal is not defined

I'm thinking my formatting is off. Any help would be greatly appreciated.

D8 makes fewer assumptions about what you need in the page, so the Drupal JS library isn't included unless it's specified.

Just add

- core/drupal

as one of your library's dependancies, rebuild the cache, and all should be well.


How to remove "Submitted by .... on Fri, 06/19/2015 - 22:04" from published content in Drupal 7? How to remove "Submitted by .... on Fri, 06/19/2015 - 22:04" from published content in Drupal 7? Where and what parameters and permissions to change? Thank you.

You can remove it by doing below steps.

Go to content type edit page i.e. /admin/structure/types/manage/page
Now under Display Settings, uncheck the option Display author and date information.


How to define custom date format in page.tpl.php? I would like to add a custom copyright footer to my site e.g. MONTH YEAR. I have set up a »short« date format for English, French and German in admin/config/regional/date-time/locale. Using <?php print format_date(time(), 'custom', t('F Y')); ?> in page.tpl.php is working great.

However I would love to go one step further. How do I print the short date format to page.tpl.php instead of adding them to *.tpl files separately?

You are right using the correct API format_date(). What you need to do is passing correct value to it.

<?php print format_date(time(), 'short'); ?>

According to the API doc, the function signature is:

format_date($timestamp, $type = 'medium', $format = '', $timezone = NULL, $langcode = NULL)

And it explained how you should handle the translation.

  $langcode: (optional) Language code to translate to. Defaults to the language used to display the page.

$langcode is handled automatically if you keep it as default value.


Paragraph view reference? I am trying to meet the following requirement:

I want to create a node (custom content type) that contains only a paragraph reference.

I have the following paragraphs in my node

Billboard (large image + Caption)
Testmonial (slideshow sentences)
Body
Here i want to display a view that contains news articles (nodes from the custom news content type)
Call to action

But i can't seem to do this properly?

I can create a block display for my view and attach it to the page by path, but then the view is located below my paragraphs, where I want the view to be one of the paragraphs, since there is a call to action that needs to be located below the view.

Anyone ever tried this?

All suggestions welcome!

If you have a solution that does not use paragraphs, I am also happy to hear!

Many thanks in advance

EDIT:
After some additional searching, it seems that for D7, this module seems to be capable of doing this: https://www.drupal.org/project/entityreference_views_formatter more information can be found here: https://www.drupal.org/node/2756315

Still no solution for D8 though...

Using hook_entity_view, you can insert the view into the field's build array.

function mymodule_entity_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {

  if ($entity->getEntityType()->id() == 'node' && $entity->bundle() == 'example_content_type' && $view_mode == 'full') {
    $node_id = \Drupal::routeMatch()->getRawParameter('node');
    $index = 0;
    foreach($build['field_paragraph_field'] as $key => $value) {

      if (is_numeric($key) && $value['#paragraph']->bundle() == 'body') {
        $news_view = [
          '#type' => 'view',
          '#name' => 'my_news_feed',
          '#display_id' => 'block_1',
          '#arguments' => [$node_id],
        ];

        array_splice($build['field_paragraph_field'], $index + 1, 0, [$news_view]);

      }
      $index++;
    }
  }

}


how to filter nodes that match url of current node or particular field of current node For my contenttype 'cars' i use a panel node-view.

Each 'car' node has fields 'categorie' and 'type'
Each 'car' node has url 'categorie/type/model' e.g.
'car/toyota/yaris'

In my 'car' panel node-view i like to insert a view.
This view should filter nodes  that match the field 'type' or part of the url 'type'

Without succes i have tried to pass the node id as an argument from my view (master) to my panel. Then using node id as a contextual filter.

Ok managed to create a working view:

Under contextual filter:
-Content: Has taxonomy term ID

Configured:

Provide default value - Type:

Taxonomy term from url - load default filter from term page (checked)

Specify validation criteria (checked)

Validator: taxonomy term (selected)

Check term in vocabulary list

Filter type: term name converted to term id (selected)


How to calculate number of submitted webforms? I want to show the number of submitted webforms in a block in the front page of my website.

I searched and found (( function webform_get_submission_count )) . But I'm absolute beginner: I know it is inside webform.submission.inc, but then where shall I call it? How to place it in a block like in the following image:

Any help would be greatly appreciated.

Another option would be to use Views to create a view of webform submissions, and display the count from that.


How to make the Charts module use the Highcharts legend option "useHTML" (required for RTL)? I tried using the Charts module with Highcharts as my charting library (engine). And this for a block view in a multilingual site that flips between LTR and RTL.

I found out that the legends and tooltips break in RTL. The legends labels overlap the colored boxes and the text within the labels is pushed outside of the tooltip box.

I managed to make the tooltips presentable through the use of $chart['#tooltips_use_html'] = TRUE; (in 'chart_alter'). Although the text is aligned wrongly the out of box issue disappeared.

However I found no similar option for the legend. I looked at the Highcharts documentation where I found a useHTML option for fixing this issue with legends. But I am unsure about how to apply it with the hooks provided by the Charts module.

Here is a picture of it:

You should be able to get this to work using the approach as described in the issue about Pass library-specific options via existing #raw_options, AFTER you apply the patch in comment nr 4 of this issue.

Disclosure: I'm a (co-)maintainer of this module.

PS 1: Would be nice/great if you could confirm that this patch also worked for you.

PS 2: after a similar patch becomes available to Google charts also, both patches will be committed.


FAQ page access denied for anonymous users I've installed the FAQ module and created some FAQ content. The FAQ page is found here: http://www.inadaydevelopment.com/faq-page

I have given Anonymous users the "View FAQ pages" permission, but anonymous users still cannot view the FAQ content of the above page. It shows the header block which I configured to appear only on that page, but the body of the page shows Access Denied.

What am I missing?

It looks like I needed to flush my cache, the page was cached with old permissions and so anon couldn't see it last night when I made the change, but can see it now.


Override view-list and get items properties I'm currently working on Bartik theme and i'm trying to create a custom template for the Content-Recent block available in Drupal 8
For your information, i would like to create the following block view :

For that, I've followed these steps :

In Drupal 8 back-office, I've added the block view "Recent content" (Machine name : views_block__content_recent_block_1)
In my source code, I've created a new file in my templates folder and named : views-view-list--content-recent--block-1.html
I've added a static text : "Hello world", just to check if the template has been override, and it's OK for this part.

But now, I'm stuck because I don't know how to retrieve item properties (Title, Date, Description)
I've tried to find some informations with kint() and dump() but I'm bit lost :/

This is the default template for a views-view-list.html.twig. Basically you've overwritten this template when you've created views-view-list--content-recent--block-1.html.

{#
/**
 * @file
 * Default theme implementation for a view template to display a list of rows.
 *
 * Available variables:
 * - attributes: HTML attributes for the container.
 * - rows: A list of rows for this list.
 *   - attributes: The row's HTML attributes.
 *   - content: The row's contents.
 * - title: The title of this group of rows. May be empty.
 * - list: @todo.
 *   - type: Starting tag will be either a ul or ol.
 *   - attributes: HTML attributes for the list element.
 *
 * @see template_preprocess_views_view_list()
 *
 * @ingroup themeable
 */
#}
{% if attributes -%}

    {% endif %}
    {% if title %}

{{ title }}

    {% endif %}

    <{{ list.type }}{{ list.attributes }}>

    {% for row in rows %}

{{ row.content }}

    {% endfor %}

</{{ list.type }}>

{% if attributes -%}

{% endif %}

What you could do is try adding something like this inside your "for" loop:

{% set item = row.content['#view'].style_plugin.render_tokens[ loop.index0 ] %}
{{ item['{{ title }}'] }}
{{ item['{{ field_date }}'] }}


Why does file_validate_extensions fail to validate? I'm using the following code for validating and uploading a file from a form:

function request_form_submit($form, &$form_state) {
    $validators = array('file_validate_extensions' => array('png'));
    $file = file_save_upload('spectrum', $validators);
    if ($file) {
        //do stuff
    }

Uploading works, but I want to allow only png files to be uploaded. The validation part does not work at all, file uploading is always successful no matter which extension the uploaded file has.

I also tried giving a space separated list of extensions to file_validate_extensions as mentioned in the documentation, but that didn't change anything.

Any idea what I'm doing wrong here and why this doesn't work at all?

$form['#attributes']['enctype'] = 'multipart/form-data';
$form['survey']['file-upload'] = array(
  '#type' => 'file',
  '#prefix' => '
',
  '#suffix' => '

',
  '#description' => 'Image type PNG/JPG Max Size:2Mb.',
);

function create_survey_form_validate($form, &$form_state){
$save = file_save_upload('file-upload', array('file_validate_extensions' => array("jpg png")),"public://user_sheets",FILE_EXISTS_RENAME);
  if($save == null){
    form_set_error('file_upload', 'Please select a file');
  }
  else if($save == FALSE){
   form_set_error('file_upload', 'Error in file upload');
  }
}


Change input method of "Description field" in "File" type I have added a "File" field in a Content type. Now I can mark the option " Enable Description field". This "Description field" only let use direct input. I need to change this to a select field. I'm not expert in hooks use. I'd like to set it as a dropdown or autocomplete. Which is the best option? create a taxonomy list or a hand made term list? I have to use only in one content type. Thanks

One way to do it without coding might be to create custom entities with Entity Construction Kit and insert them to your content type using Inline Entity Form. Using ECK, you can add the dropdown/autocomplete field and the file field.

You may then need to use something like Automatic Entity Label to prevent the user from needing to enter description/title themselves (The site won't allow me to insert a third URL here, but an internet search for "automatic entity label drupal module" will bring it up).


imagefield and temp files? I am using imagefield and D6 with filepaths to upload images to a custom directory using a custom token.

I'd like to validate whether an image that was uploaded is the same as another image in the repository.

I see that imagefile appears to be uploading the file to: default/files/, then deleting it there and saving in the directory I specify using my custom token.

Is default/files where imagefield is saving the file as a "temp" file until validation passes? I would think it would save a temp file in the temp file location specified by php.ini. If the later is true, can I get a hold of the tmp name in $form_state? I believe with image module, I could get the temp name of the file from $form_state, but I don't see that info using imagefield. Thanks in advance.

In file settings you specify a temp path and a files path, which is what is used by Drupal.

The temp path which could be /tmp, but it could also be default/files that is entirely up to you. the temp file folder is where files are uploaded to after being submitted in a form. After validation checks, file_save_upload should be used to save the file. There is no reason for the file to be saved to the default/files folder and then be moved, as it can be saved directly to whichever folder you want. I do believe that is how the imagemodule does it..


How to automatically create subitems based on node entries? I have a content type called "brand", and about 30 brands. I want them to automatically appear as a list of items below a main parent menu item. Is there something that does this already?

Try the Content Menu module.

This module provides an easy way to add existing nodes (content) as a sub item  to menu.

  Content menu module improves Drupal's default menu management interface for tighter integration of content authoring and menu management, so content can be created and edit right from the menu interface (e.g. creating content for a menu item that has been just created.
  See the screenshot


Drupal method to retrieve all existing roles and all users of a specified role I wish to retrieve the list of all users that belong to a particular role.

The query is to know:

if there's any drupal method that provides list of all available roles created under Admin >> User Management (admin/user/roles) similar to retrieving all node types using node_get_types method.
if there's a drupal method to get list of all users who belong to a particular role.

Though I could get this done by querying the role table and using the result with user_roles table, I felt that there might be some in-built method in drupal which must enable me to achieve the desired result which i might've missed out searching.

I'm aware that it's not ideal to check user permission related stuff with roles and rather user permissions instead from this post.

It'd be great if I could get a definite answer for my above mentioned queries.

You can use the user_roles() function to get a list of the roles in the system. You can even pass in specific conditions, for example if you want to get only the roles that contain a certain permission.

As far as getting a list of users by role, there is no such function, unfortunately; you'll have to write a small helper function yourself. I usually use something like this:

function users_by_role($role_id) {
  $sql = 'SELECT uid FROM {users_roles} WHERE rid = %d';
  $q = db_query($sql, $role_id);
  $uids = array();
  while ($row = db_fetch_array($q)) {
    $uids[] = $row['uid'];
  }

  return $uids;
}

That'll give you the user ids for a given role, after that you can use user_load() to get the user object for each, or simply add a join to the above query and include the data you need directly.


How can I filter related content types in Drupal? I'm building out a project management/project organization site with Drupal. The basic content types will be:

Projects
Milestones (which belong to a project), and
Tasks (which belong to a milestone)

I've built the Project content type. That was easy. I built the Milestone content type, and using the Node Reference module, I was able to access all of the Projects right in the from. Nice! But now Tasks get a bit tricky. Using the same technique, I could reference all of the Milestones in the Tasks form, but I really only want to see the Milestones that are associated with a specific Project. It seems that I would need to employ some kind of filter. How?

What's the best approach here? I have no module restrictions and am using the most current version of Drupal (7.8).

You could populate the second list manually by using the PHP code option to generate the values, the values could be something such as ProjectNid|TaskNid|Task Title.

You could then have a javascript hook so when a project was selected from the dropdown, it reads the nid value and then filters out the tasks where the first element (Project nid) doesn't match.

The other way would be reload the page after the project has been selected, and have the PHP code which populates the task field look at the current active value for Project and pull in the related tasks, or use a view with an argument set to achieve the same result.


User Registration Module for Drupal Drupal uses email for user registration purpose. Instead of the out-of-box Drupal user registration that requires user to specify a username and email address, I want a full-fledged user registration form ( with captcha, user profile etc, like yahoo or gmail registration) for my website.

Is there a module that does that?

There are a couple of options for this.
To get profile fields the most common solution is the profile module included in Drupal core. Go to Administer > Site building > Modules and enable it under core-optional.  Then you can configure the Profile module at Administer > User settings > Profile and in the settings you can say whether the fields will show during registration or not.
To get a captcha during registration you will need one of a couple of modules:
I prefer HCaptcha because it works very well and even can earn you some money, but it sends your content to an external site to do some verification.
There is also Captcha which provides integration with other options.


multiple profile type values I have following requirement

I have user with multiple profile type like main profile, personal profile, and role profile

A role profile has fields like

role paid
role status
role start date
role subscription date

A single user can have multiple role profiles and above fields associated with each role profile

I heard about field collection per field which means we can have multiple values per field , But how can we have set of  multiple profile values

Example :

Role name : Moderator
   role paid : yes
   role status : yes
   role start date : xxxxxx
   role subscription date : xxxxxx

Role name : testrole
   role paid : yes
   role status : no
   role start date : xxxxxx
   role subscription date : xxxxxx

and continues...

I think usage of profile2 module works only with 1 -1 relationship with user to each profile type. Node or custom entity might work better for your use case. Field collection is one way of creating such entity. This article (Creating your own entities) might help, if you replace task -> role_licence and task_type -> role_licence_template.


Redirect node form in D7 It looks like silly question but I'm really confused about redirection after node save and update.

I tried to set $form['#redirect'] - without any success.
I tried to set some other vars for instance: $_REQUEST['destination'] or in $form['buttons']['submit']['#submit'] setting function name to call that sets $form_state['#redirect'] but none of this solution works.

Can you give me some source that explains node forms redirecting in D7?

1.Use hook_node_create and hook_node_update, judge your node type to drup_goto, like:

function hook_node_create ($node) {
  if ($node->type == 'YOUR_NODE_TYPE') {
     drupal_goto('YOUR_DESTINATION');
  }
}

2.Use hook_form_alter change your node form, like:

function hook_form_alter (&$form, &$form_state, $form_id) {
  if ($form_id == 'YOUR_NODE_FORM_ID') {
    $form['actions']['submit']['#submit'][] = 'YOUR_NODE_FORM_ID_ls_submit';
  }
}

function YOUR_NODE_FORM_ID_ls_submit ($form, &$form_state) {
  $form_state['redirect'] = 'YOUR_DESTINATION'; // Not $form_state['#redirect']
}


How to set published status to a static value while importing a CSV using Feeds How can I set the published status of a node created by Feeds to unpublished for every node it imports?

I am using a manually uploaded CSV file.

Add a new column to your CSV, fill it with 0, and import that as Published Status.


Hide language flag on this language page? I have 2 languages on my Drupal 8 site and use Language Icons module for them:

Latin and
Celtic

I think it is not convenient to have both flags on each version. But D8 does not add language code class in body and I cannot hide flag.

Please where is solution?

if you want add class language to body. You can use hook_preprocess_html with code:

function Your_Theme_preprocess_html(&$vars){
  $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
  $vars['attributes']['class'][] = $language;
}

class current language will add to body.


Can I make the Omega theme to either be or not to be responsive depending on the capability of the device to properly scale the site I have a site which needs to be responsive to several devices (mobiles and tablets)

I will do this using the Omega theme. Then I have the option to make the theme Responsive. In this way the general layout of the site changes based in the size of the screen device.

So far so good.

I need to change this behavior in this way: if the device is capable of scaling and showing the site in an acceptable way (ex: like the iPhone(iOS) and Galaxy S2(Android) do) then the theme should no behave like responsive and show the site in its normal layout.

My question: Can I make the Omega theme to either be or not to be responsive depending on the capability of the device to properly scale the site?

I'm pretty sure you can trigger contexts on specific devices using mobile tools, and you can probably turn Omega's responsiveness off with Delta.

I've never pulled such configuration, so please try out and give some feedback ;)


Encrypting db password stored in settings.php The db password in settings.php is stored as plain text.
Is there any way to encrypt that password?

My client says its a security risk even though the file permissions is as should.

This is not a Drupal question specifically. Depending on the OWASP security standards you're following keeping the password in plain in settings.php could be considered a risk (in a normal, usual Drupal environment it won't be the case)

This thread on Information Security Stack Exchange discusses the topic, but in my opinion is a little paranoid and most of the options will slow down your site.


Hook_schema and multiple databases Possible Duplicate:
  How do I specify in which database my schema should be created?

I would like to create an entity module which discuss with another Drupal database.

In my module.install, this is ok :

db_set_active('otherdb');
if (!db_table_exists('mytable')) {
$result = db_query("CREATE TABLE mytable (
     id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
     title VARCHAR(255)
   );");
drupal_set_message("LOG :Creation of table mytable ok");
}
db_set_active();

but this can't be done with hook_schema  :

$schema['mytable'] = array (
'description' => 'The main store for our entity',
'fields' => array(
  'mytable_id' => array(
    'description' => 'Primary key for our table of mytable',
    'type' => 'serial',
    'unsigned' => TRUE,
    'not null' => TRUE,
  ),
  'title' => array(
    'description' => 'The mytable title',
    'type' => 'varchar',
    'length' => '255',
    'not null' => TRUE
  ),
),
'primary key' => array('mytable_id'),
);
db_set_active('otherdb');
return $schema;

Any ideas ?

I think another angle to attack the problem would be to implement hook_schema the normal way, as if there was only one database. And then tell Drupal to use another database for some tables in settings.php. Your module will not have to be run on seperate databases and all that external database stuff is taken care of by Drupals database layer.


Images referring wrong path I uploaded some images in content. the images are uploaded to "sites/default/files". but in node page the images are referring "sites/default/files/styles/large" path. how to change it?

Images refering wrong path

I would say, Image is not referring any wrong path and there is nothing wrong in what you are seeing. Whatever you are seeing is by design in Drupal.

If you defined the Image style, the corresponding files automatically gets prepared in the folder. Hence if you upload an image the image gets uploaded at one default place which is for original images, But if you have defines the image style for that content type, then images gets saved at other place also. Hence In your case both "sites/default/files" and "sites/default/files/styles/large" are true. You can see the same image at two places.

For Example,

I just uploaded the image in Article and article content type has the image style Large. So that image gets uploaded at two places, as below in my folder.

FOR ORIGINAL IMAGE - sites/default/files/field/image/exampleImage.jpg
FOR LARGE IMAGE STYLE - sites/default/files/styles/large/public/field/image/exampleImage.jpg

So, same way, if I declare new Imgae style, like Medium Or Thumbnail, the new file with that name gets created and image gets saved there.

Hence, I am not getting why you want to change the path. There is nothing wrong in path. It is by Drupal's default desing. Hence, you not have any problem in your folders.

Hence for image, There is not a concept of changing path here. There is a concept of changing the Image style and image style choose their own folder automatically which is path.

So, you can go to Structure/content type/exampleType/Manage Display/ and from there you can change the Image style which you want and that image style will create/choose its own folder automatically.


Get future node id (nid) of nodes being programmatically created (future node) I want to create multiple nodes using one form, but I'd like to have connection between them stored in Entity Reference, so I need to know their nids. But they aren't created yet, so they hasn't nids.

Question: Is there a way to predict future nodes nids and preserve them for a while or do something similar to deal with task above?

Unfortunately, there's no a clean way to do that!


Is there a way to add managed_file field to theme-settings.php? Anytime I add a managed_file field to theme-settings.php, the field works, however, it gets saved with a status of 0 in the database.

When I add a submit handler to the theme settings form, I get a " Call to undefined function" error.

Of course, when I remove the managaed_file field, the undefined function error goes away and the submit handler fires as normal.

Has anyone tried doing this? Is there another way around this problem?

thanks!
david

The theme-settings.php is included from system_theme_settings(), which executes the following code.

// Call engine-specific settings.
$function = $themes[$key]->prefix . '_engine_settings';
if (function_exists($function)) {
  $form['engine_specific'] = array(
    '#type' => 'fieldset',
    '#title' => t('Theme-engine-specific settings'),
    '#description' => t('These settings only exist for the themes based on the %engine theme engine.', array('%engine' => $themes[$key]->prefix)),
  );
  $function($form, $form_state);
}

foreach ($theme_keys as $theme) {
  // Include the theme-settings.php file.
  $filename = DRUPAL_ROOT . '/' . str_replace("/$theme.info", '', $themes[$theme]->filename) . '/theme-settings.php';
  if (file_exists($filename)) {
    require_once $filename;
  }

  // Call theme-specific settings.
  $function = $theme . '_form_system_theme_settings_alter';
  if (function_exists($function)) {
    $function($form, $form_state);
  }
}

Unfortunately, the file is not loaded from Drupal before any validation/submission handlers for that form are invoked.

When form_cache_get() is called, the following code is executed.

    foreach ($form_state['build_info']['files'] as $file) {
      if (is_array($file)) {
        $file += array('type' => 'inc', 'name' => $file['module']);
        module_load_include($file['type'], $file['module'], $file['name']);
      }
      elseif (file_exists($file)) {
        require_once DRUPAL_ROOT . '/' . $file;
      }
    }

As form_get_cache() seems called before a form is validated/submitted, you could use the following code. (Replace mytheme with the short name of your theme.)

function mytheme_form_system_theme_settings_alter(&$form, &$form_state) {
  $theme = $GLOBALS['theme_key'];
  $themes = list_themes();

  $form_state['build_info']['files'][] = str_replace("/$theme.info", '', $themes[$theme]->filename) . '/theme-settings.php';
}


Can I somehow edit libraries.yml files from the backend using the admin panel? In my Drupal project, we load custom CSS for some of our specific pages. Right now I do all of these modifications programmatically.

But what our manager wants is to create it manually in the admin panel. Uploading the CSS file in the new content type I'll create.

I'm a bit worried because I add these custom CSS we had in the libraries.yml like this:

Is there anyway they can edit this yml file in the admin panel? Or is there any better ideas I can do when adding custom CSS?

EDIT: I need to setup an advanced rule. In our project, each of our articles contain categories. And we apply different CSS files in some special categories. So basically what I'm doing is I query the categories of the article and inject the custom CSS. I attach the CSS like this in the page_attachment.inc:

To directly answer your question, yes, you can edit config with the devel module. Install it, then configure it to display the Config Editor.

To answer your question pragmatically, I need to point out that making direct edits to configuration on a regular basis is a recipe for disaster. I think you would be better served using the Asset Injector module, which will allow you to add CSS and JS on the fly, without tinkering with configuration files.

If it is an absolute necessity to modify the library definition, then I think that hook_library_info_alter() is what you need. However, as leymannx points out, libraries aren't intended to be constantly manipulated on the fly. This brings me back to using the Asset Injector. The CSS injector portion is pretty much perfectly suited to your use case; it allows for adding and editing CSS through the admin interface. The CSS injector allows for multiple rules, and these can each be targeted based on path and/or theme.

If you combine this with custom classes attached to the page, then you can use those classes in your CSS rules. You can implement hook_preprocess_page() to do this:

myproject_preprocess_page(&$variables) {
  $node = $variables['node'];
  if ($node) {
    // Assume that the Taxonomy Vocabulary machine name is "category".
    /** @var \Drupal\taxonomy\Entity\Term[] $terms */
    $terms = \Drupal::entityTypeManager()
      ->getStorage("taxonomy_term")
      ->loadByProperties(["vid" => "category"]);
    // Get all categories present on the current node.
    $categories = $node->get('field_category')->getValue();
    // Get just the TIDs as a simplified array.
    $categories = array_column($categories, 'target_id');
    // Ensure that there is a class array.
    $variables['attributes']['class'] = $variables['attributes']['class'] ?? [];
    foreach($categories as $category) {
      // Craft a HTML-compliant class name based on the label.
      $variables['attributes']['class'][] = \Drupal\Component\Utility\Html::cleanCssIdentifier($terms[$category]->label());
    }
  }
}


how to get email of welcome messge with drupal 7? After creating new account with Drupal 7 I am getting the message.

  Thank you for applying for an account. Your account is currently
  pending approval by the site administrator.In the meantime, a welcome
  message with further instructions has been sent to your e-mail
  address.

But when I check my email account I am not getting that welcome email.

Follow below steps to solve problem !

Check your server smtp log or mail log
Check your spam folders in mail box.
Make sure smtp or mail server are up & running in your hosting server or local server.
Check drupal recent log entries for any errors related to same !


Mollom and Spamicide are not slowing down spam registrations I have a drupal 6 site. I'm using both Mollom and Spamicide.

Mollom is doing a great job at stopping spam comments but spambots are registering at an extremely high rate over 6 per minute.

Registration uses a captcha from Mollom and Spamicide but they seem to be going right through both. Spamicide slowed them down for about half a day but now that seems to be doing nothing.

Additionally, about 80% of the spambot accounts are validating their accounts through email - they create tons hotmail accounts with generic names.

Any ideas or recommendations on stemming the tide?

I've been trying to find a way of automatically blocking IPs that are throwing a high number of registrations or other suspect activity.

You can still try to use CloudFlare service, coupling with Mollom it's very effective.

Also, I'm not sure that they (bots I mean) are creating account e-mail to validate their account. The problem with Drupal 6, its has an algorithm to create the validation link that it's easier to reproduce (much harder with Drupal 7 as its has a secret key when you install).

Well, if with CloudFlare it doesn't slow down your spam problem, you can either change the validation algorithm or upgrade to Drupal 7.


Allow users to choose which layout to be applied Is there any way to allow users to choose which layout to be applied (Omit the given media queries) for the Omega theme?

For example, ESPN has a switcher for choosing the layout: When browsing in iPad, it has a link to switch to desktop.

Do you have any idea on how achieving such functionality with the Omega theme?

Responsive designs usually rely on media queries to apply the styles, but you could make a copy of those styles and prefix its selectors with body.desktop. Then, when you want iPad users to see different styles, just add the class to the body element (using jQuery). CSS preprocessors like SASS will help you mantain those styles without duplicating the code — Zen 7.x-5.x has awesome out-of-the-box support to SASS/Compass and responsive designs. See the Sassy module as well.

There is also the adaptive design approach: it relies on browser sniffing to return device-specific markup and styles. The mobile tools module will surely help should you choose this approach.


Use theme function to change the search form input type I use the default search block provided by Drupal.
I want to change the type of this search text box from "text" to "search." How do I do this using a theme function?

There is no way to change the type of the search box form item with a theme function, but here's a theme friendly answer :-)

By default the Search input type isn't supported in Drupal 7, so you can't use any kind of hook_form_alter to change it out of the box.  You can do the following though to give you the ability to do what you want though:

Download and enable the Elements module from the awesome Dave Reid.
Add the following to your template.php file (you can omit the size - I just put it there to make the box a bit shorter):

function THEMENAME_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'search_block_form') {
    $form['search_block_form'] = array(
      '#type' => 'searchfield',
      '#size' => '20'
    );
  }
}

This could also me done easily in a custom module, but I know you asked about theming specifically.


How to construct a content type that would be useful for creating a "When is this store open" view I would like to create an hours content type that could be attached to an individual location.  The goal is to create a page that a customer could visit to find which of the stores are open today, along with the times that they are open.  This would also reflect closures for holidays.

Unless you've got a system managing alot of stores and open hours, it's probably easiest to just have a static "Page" with the store open hours on it. A basic page can be easily content managed.


Conditionally enable/disable #autocomplete from client side js I have a custom search field which searches for a type of content depending on the radio box selected. I have applied autocomplete functionality to the field using hook_form_alter but only want the autocomplete functionality to be available for one of the search types.

Is it possible to conditionally detach the Drupal.behaviors.autocomplete from the text field using my own js?

Update:
I have managed to disable the autocomplete functionality by unbinding the events, but I do not know how to add/bind it again:

// update search box text when search type is changed
$(SI_SEARCH.radio).change(function() {
  // get search type
  SI_SEARCH.search_type = $(this).val().trim();
  switch(SI_SEARCH.search_type) {
    case 'course' :

      break;
    case 'university' :
      // disable autocomplete
      $('#edit-search').unbind('keydown keyup blur');
      break;
  }
})

Ok I managed to achieve this after digging into misc/autocomplete.js

To disable the autocomplete you can do the following:

$('#edit-search').unbind('keydown keyup blur');
$('#[AUTOCOMPLETE-ELEMENT-ID]-autocomplete-aria-live').remove();
$('#[AUTOCOMPLETE-ELEMENT-ID]-autocomplete').removeClass('autocomplete-processed');

To enable the it again:

Drupal.behaviors.autocomplete.attach(document);

My js ended up as:..

// update search box text when search type is changed
$(SI_SEARCH.radio).change(function() {
  // get search type
  SI_SEARCH.search_type = $(this).val().trim();
  switch(SI_SEARCH.search_type) {
    case 'course' :
      // re-attach autocomplete
      Drupal.behaviors.autocomplete.attach(document);
      break;
    case 'university' :
      // disable autocomplete
      $(SI_SEARCH.search_form).next().removeClass('autocomplete-processed');
      $(SI_SEARCH.search_form).unbind('keydown keyup blur');
      $('#edit-search-autocomplete-aria-live').remove();
      break;
  }
})


Uncaught TypeError: $(...).dialog is not a function: How do I include dialog? I have added this code in my JavaScript file.

$( "#sponsor_dialog" ).dialog({
      autoOpen: false,
      height: 'auto',
      width:  520, resizable: false,
      show: {
        effect: "blind",
        duration: 1000
      },
      hide: {
        effect: "explode",
        duration: 1000
      }
    });

    $( "#sponsor_opener" ).click(function() {
      $( "#sponsor_dialog" ).dialog( "open" );
    });

I get the following error:

  Uncaught TypeError: $(...).dialog is not a function

In the module_name.libraries.yml I have added this.

sponsor_form:
  version: 1.x
  js:
    # For some reason, you need to put the js directly under 'js'.
    js/sponsor_form.js: {}
  dependencies:
   - core/jquery
   - core/drupal.ajax
   - core/drupal
   - core/drupalSettings
   - core/jquery.once

I am checking it when a user is logged out. Does this affect it in any way?
I have the same problem when I am logged in, though.

Drupal does not assign "$" to jQuery. That is because there may be libraries, which want to do something different with "$".

So you have to do this yourself:

(function ($) {
$( "#sponsor_dialog" ).dialog({
      autoOpen: false,
      height: 'auto',
      width:  520, resizable: false,
      show: {
        effect: "blind",
        duration: 1000
      },
      hide: {
        effect: "explode",
        duration: 1000
      }
    });

    $( "#sponsor_opener" ).click(function() {
      $( "#sponsor_dialog" ).dialog( "open" );
    });
})(jQuery);


Add a Module Form to a front page region As the title reads, I'm attempting to add a custom made module (simple contact form) into a region on my front page (this may be used other places as well, but for not just the front page). Could some one lend me their eyes/advice on how to do this correctly. The region on my page is labeled sidebar_first. I have attempted to add it via a hook_block_view() functionallity, however nothing seems to be taking.

.module

function honey_front_page_form_menu(){
global $user;
//Main Page Call Back
$items['front_page_form'] = array(
    'page callback' =>'_honey_front_page_init',
    'access arguments' => array('access content'),
    'title' => t('Honey Contact page Form'),
);

}

function honey_front_page_form_admin_form(){

  $form['front_form'] = array(
        '#type' => 'fieldset',
        '#title' => t('Admin Menu'),
);

  $form['front_form']['name'] = array(
    '#type' => 'textfield',
    '#attributes' => array('placeholder' => t('name')),
    '#required' => TRUE,

  );

  $form['front_form']['email'] = array(
    '#type' => 'textfield',
    '#attributes' => array('placeholder' => t('email')),
    '#required' => TRUE,

  );

  $form['front_form']['phone'] = array(
    '#type' => 'textfield',
    '#attributes' => array('placeholder' => t('phone')),
    '#required' => TRUE,
    '#maxlength' => 15

  );
    $form['front_form']['comments'] = array(
    '#type' => 'textfield',
    '#attributes' => array('placeholder' => t('comments')),
    '#required' => FALSE,

  );

  $form['front_form']['submit'] = array(
    '#type' => 'submit',
    '#value' => 'SUBMIT NOW',
    '#field_prefix' => '<h3>',
    '#field_suffix'=> '</h3>'

  );

}

function honey_front_page_form_block_view($delta = ''){
//ensures form is only called on the front page.

// if (!drupal_is_front_page()){
//     return NULL;
// }

    if($delta == '1'){
        $form = drupal_render( drupal_get_form('honey_front_page_form_admin_form'));
    $block = array(
        // 'subject' => t('Subject'),
        'content' => $form,
    );

    return $block;

}
}

Take a look at the Drupal block APIs. You need to use hook_block_info to define a block. Then use hook_block_view to return the rendered content of the block. You will still need to include the block, ether programmatically, or by using admin/structure/block.


How to add nodereference link to a view I have two content types.

Images
Question

The question content type is meant to allow users to ask questions about the photos in the images content type.

I added a node reference field with "reference from url" type selected to the question content type. I checked "create link on the full view" during the setup. This works correctly if I go to an "images" node.

However, I am displaying the "image" type in a view. So far I can not figure out how to get a link to the question content type to show on the view. I have tried this using a "references" display type of the view, but still nothing.

Set up the relationship:

Under the Relationships section in advance settings. click + to add a relationship.
Under "Add relationships" you will see all fields listed.
Drop down the Groups menu and select "Content".
Locate your node reference field, for example 'Content: Reference question (field_reference_question)'. Check the box to the left of it.
Click the Add button.
Check the box labeled 'Require this relationship', and click the Update button.

Add a field:

Click + next to Fields. Under Groups, select Node, and choose Node: Title. Under Relationship, select your node reference field, e.g., Reference question, click Update.


drupal_to_js() and anonymous functions I'm using the flot module to create some graphs in Drupal. Generally, it is working pretty well. However, I have come across an issue which is more general.

I am defining a settings array, which works for most things, but some flot settings allow for anonymous functions:

  xaxis: {
    transform: function (v) { return Math.log(v); },
    inverseTransform: function (v) { return Math.exp(v); }
  }

How could I encode this in PHP so that it will be output correctly? The flot module uses drupal_to_js(), and I can't put it outside of quotes as PHP will try to interpret it. If I put it inside quotes it will be treated as a string.

From my googleing it looks like json_encode() also doesn't support this.

A little more explanation: drupal_to_js() takes a PHP structure and transposes it to JavaScript.

  $top = array(
    'a_string' => 'A string will convert fine',
    'a_number' => 123 // as will a number,
    'an_array' => array('a' => 'nested arrays work fine too'),
  );

This will be transposed to something like

 [ a_string: 'A string will convert fine', a_number: 123 ...

I want to transpose a function; the following code will give me the string 'function (v) { return Math.log(v); }'.

  $top = array(
    'a_string' => 'function (v) { return Math.log(v); }',
  );

The following code will give me a PHP parse error (as it should be).

  $top = array(
    'a_string' => function (v) { return Math.log(v); },
  );

I want the text in the string to be used as a JavaScript literal, but I don't think it can be done.

Has anyone found a good way round this? I could output some raw JavaScript, but then I will lose a lot of functionality.

This guide can be used as a work around http://echodittolabs.org/blog/2011/04/setting-js-callbacks-drupal-json-and-some-jquery-sauce-jcarousel-controls

We are looking for a generalized solution to this here http://drupal.org/node/1148204


Alter drupal 8 views in for each row I have a view and I want to alter the output in each row.
So I have tried hook_views_pre_render(), and hook_preprocess_views_view(), but with no luck. In both of the above hooks I got data in $view->result, but there seems to be no way to change the rendered output.

After a long a research and development, I came to an conclusion that this could be the answer:

foreach ($view->result as $result) {
  $result->_entity->set('field_name', array(0 => 'value'));
}


Show menu on specific page I created a menu with one specific menu entry. I want to show the menu only on one page.

Does exist a module which places a menu like a block?

Yes, the aptly named Menu Block module.

  ...provides configurable blocks of menu trees starting with any level of any menu.


Active menu trail for multiple menu item with the same path It is possible to have menu items that point to the same node and have the active state dynamic?

If I click the link 'List item A1' I would like to become active the link 'List item A'.

If I click the link 'List item B1' I would like to become active the link 'List item B'.

 - List item A (node/1)
 --  List item A1 (node/2)

 - List item B (node/3)
 --  List item B1 (node/2)

You can use the module menu-position for this. When you add a new rule, just choose the option Mark the rule's parent menu item as being "active" on the settings page. You probably have to create a css rule for your theme, too.


3 columns with main content in front page I am very new in Drupal and therefore I need your help please.

I would like to have 3 columns in my front page for the main content. Let's say the columns are: NEWS, EVENT and SPOTLIGHT.

When I create an article, I would like to be able to choose in which column I am going to publish the article. I need also to be able to theme the columns... How can I do this?

thank you.

Gilles

Panels module would help you in this regard. In Panels you can place nodes, views blocks, general blocks. All these things can be themed independently.

Panels are themselves nodes and blocks(mini panels).


Is the current faceted search effective for SEO? Seems that the url generated by faceted items are not good for SEO (unfriendly to search engines) eg. I have a facet that transforms the url to this format : http://localhost/mysite/property-for-sale/residential-sale?f[0]=field_property_type%3A71

I don't know how i can make it more friendly to search engines as this is automatically generated by the faceted links...

any suggestions, is this possible with the current version of facet search apis?

There is a module for it: Facet API Pretty Paths. But I didn't try it yet.

Here is a quote about it (from the module's project page):

  Enables pretty paths for searches with Facet API. You will likely use this module in combination with either Search API or Apache Solr Search Integration.


Add field(s) to menu link? Is there a way to add field(s) to menu links in Drupal 8? Like an image field to output above certain links?

Add this code to your custom module:

function my_module_entity_base_field_info(\Drupal\Core\Entity\EntityTypeInterface $entity_type) {
  if ($entity_type->id() === 'menu_link_content') {
    $fields['menu_link_image'] = BaseFieldDefinition::create('image')
      ->setLabel(t('Menu link image'))
      ->setDescription(t('Upload the image related to this menu item'))
      ->setDisplayOptions('form', array('type' => 'string', 'weight' => 0));

    return $fields;
  }
}

Then use hook_update_n to update the schema of the menu_link_content_data table. Run update.php, flush caches and the new field should appear on all the Add/Edit menu item form.

In case someone wants to simply add a text field, boolean etc, simply edit BaseFieldDefinition::create('image') and change it to BaseFieldDefinition::create('string') or BaseFieldDefinition::create('boolean') etc


Theme image broken link I am recreating an existing website and part of the process is enabling a theme from the same existing site on my new version.
The theme is called microsite and has an image located in /microsite/images/.
In the original site, the image from the above directory is loaded and displayed in a block.
I copied the code from the block of the original site, pasted and saved in a block of my new site. The HTML markup is the following.

Using the exact HTML markup in my recreated site with the same theme and path to image shows a broken image link. The link shows up as    http://192.10.10.1/sites/all/themes/microsite/images/image.jpg instead of
http://192.10.10.1/mysite/sites/all/themes/microsite/images/image.jpg.
To resolve this, I set $base_url in settings.php to http://192.10.10.1/mysite, but the link is still broken.
Can anyone help, please?

You should remove the first slash from src in your theme to

<img src="sites/all/themes/microsite/images/image.jpg" />

That first slash is indicating that it is relative to your web root rather than your Drupal root.


Context Filters Views Taxonomy Parent I have a taxonomy list like this.

- House
 --Large house
   --- Large white house
   --- Large green house
   --- Large pink house
 --Medium house
 --Small house

I have a view url that looks like this

<url>/categories/large-house

My contextual filter depth is set to 1. So when I go to the above URL it displays all the nodes that have Large house and Large house children attached. What I want to achieve is to exclude all nodes that are attached to the Large house parent term directly and display nodes that are attached to Large house children.

Under Filter Criteria I thought this would work. My thinking is display all nodes except the nodes that have parent term Large house.

(term) Taxonomy term: Parent term (!= 0)

Any help would be great

That's quite tricky because the taxonomy system doesn't seem to like looking for children.  You might need to use Page Manager and the ctools context system to achieve this.

Create a 'page' (url) at /categories/%term-id that has the term currently being viewed as a context
Create a view pane that requires a context of parent term id which shows all nodes that have the taxonomy term subordinate to the parent term
use the view pane in your 'page' and set the context to the term being viewed

There's a rather good example of a similar use case here (watch the whole series, it's really good).


Accessing User Fields in Rules I have added a custom field (taxonomy reference) to my users.  Now I want to run a rule based on the values in that field, but the field does not show up in the available items on the "data selection".

Any ideas on why the field does not show up in rules or how to make it show up in rules is greatly appreciated.

field configuration:

langcode: en
status: true
dependencies:
  config:
    - field.storage.user.field_workbench_access_groups
    - taxonomy.vocabulary.intranet_units_committees_and_gr
  module:
    - user
id: user.user.field_workbench_access_groups
field_name: field_workbench_access_groups
entity_type: user
bundle: user
label: 'User's Workbench Access Groups'
description: ''
required: false
translatable: false
default_value: {  }
default_value_callback: ''
settings:
  handler: 'default:taxonomy_term'
  handler_settings:
    target_bundles:
      intranet_units_committees_and_gr: intranet_units_committees_and_gr
    sort:
      field: name
      direction: asc
    auto_create: false
    auto_create_bundle: ''
field_type: entity_reference

Reaction Rule:

langcode: en
status: true
dependencies: {  }
id: sync_existing_user_workbench_access
label: 'Sync Existing User --> Workbench Access'
events:
  -
    event_name: 'rules_entity_update:user'
description: ''
tags: {  }
config_version: '3'
expression:
  id: rules_rule
  conditions:
    id: rules_and
    conditions:
      -
        id: rules_condition
        context_values:
          type: user
        context_mapping:
          entity: user
        context_processors:
          type:
            rules_tokens: {  }
        provides_mapping: {  }
        condition_id: rules_entity_is_of_type
        negate: false
      -
        id: rules_condition
        context_values:
          field: field_workbench_access_groups
        context_mapping:
          entity: user
        context_processors:
          field:
            rules_tokens: {  }
        provides_mapping: {  }
        condition_id: rules_entity_has_field
        negate: false
  actions:
    id: rules_action_set
    actions: {  }

As @anonymous pointed out, it is answered in Access user profile data.  Since that post is not well labeled in connection with rules, I will also post the answer here.  In short, instead of verifying Entity is of Type, verify that entity is of bundle.  Entity of Type should work, but that it does not is (apparently) a known bug with Rules 8.x-3.x as of this time.


Ajax callback values not saved on submit I added an Ajax callback to Add to cart form on two fields : quantity and a date line item field, because I need customers to choose the product id depending on these values (see study case if you wish more details).

Everything works fine... except that Ajax values, especially product_id, aren't saved in cart on form submit :(

Relevant parts of code

Add to cart form alter

/**
* Implements hook_form_alter().
*/
function vts_commerce_form_alter(&$form, &$form_state, $form_id) {

  if (strstr($form_id, 'commerce_cart_add_to_cart_form')) {
    //line item field callback
    $form['line_item_fields']['field_date_de_d_part_line_item']['und'][0]['#ajax'] = array(
      'callback' => 'vts_commerce_liberte_addtocart',
     );
    //wrapping $form['product_id']
    $form['product_id']['#prefix']='
';
    $form['product_id']['#suffix']='
';

    // ... SOME CODE setting $options

    //overwriting native $form['quantity'] to have a select with specific options
    $form['quantity']= array(
      '#type' => 'select',
      '#title' => t('Number of participants'),
      '#default_value' =>  1,
      '#datatype'  => 'integer',
      '#size' =>  1,
      '#weight' => 45,
      '#prefix' => '
',
      '#suffix' => '
',
      '#options' => $options,
      '#ajax' => array(
        'callback' => 'vts_commerce_liberte_addtocart',
        'wrapper' => 'qty',
        'method' => 'replace',
      ),
    );
  }
}

Ajax callback

function vts_commerce_liberte_addtocart($form, &$form_state) {

  $commands = array();

  // ... SOME CODE setting $pid and other stuff, messages...

  //TRYING TO UPDATE PRODUCT ID with drupal_render
  $form['product_id'] = array(
    '#type' => 'select',
    '#options' => array(
       $pid => 'product title: '.$pid, // TODO retrieve product title
    ),
    '#default_value' => $pid,
    '#weight' => 0,
  );
  $commands[] = ajax_command_replace('#liberte_pid', drupal_render($form['product_id']));

  //TRYING TO UPDATE PRODUCT ID with $form_state['values']
  $form_state['values']['product_id'] = $pid;
  $form_state['rebuild'] = TRUE;

  return array('#type' => 'ajax', '#commands' => $commands);
}

Either $form['product_id'] and $form_state['values']['product_id'] are changed by the callback, but when I submit the form, it takes the product id selected on page load instead of the one passed through  the callback.

With or without $form_state['rebuild'] = TRUE; in my callback doesn't changes anything...

As an alternative (or complement), I also noticed that product_id's callback is  commerce_cart_attributes_refresh_alter(), which updates the values given to cart, but I don't know how/where to call or trigger it in the ajax process ?

So, product_id was rendered but its value not passed to the commerce_cart_add_to_cart_form. This is how I solved it.

Add to Cart Form Alter

if (strstr($form_id, 'commerce_cart_add_to_cart_form')) {

  $form['product_id']['#type']='hidden';
  $form['product_id']['#prefix']='
';
  $form['product_id']['#suffix']='
';
  //...

Ajax callback

$form['product_id']['#value'] = array(
  $pid,
);
$commands[] = ajax_command_replace('#liberte_pid', drupal_render($form['product_id']));

It's quite simple once you know it : before calling ajax_command_replace() you don't need to rebuild the full form element, just set the wanted attribute, and drupal_render($form['form_elt'])) will do the magic :)


Cannot call function leftJoin on a SelectQuery object? $query = db_select('drupal5users', 'udf');
$query->leftJoin('drupal5users_roles', 'ur');
$query->fields('udf', array('uid','name','pass','mail','created','access','login','status','language','init'));
$query->fields('ur', array('rid'));

The above gives me the following error:

PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') subquery' at line 1.

If I comment out $query->leftJoin and the second $query->fields line, it works, so the problem lies with leftJoin. What am I doing wrong here?

$query->leftJoin('drupal5users_roles', 'ur', 'udf.uid = ur.uid');


How to change the title of the page dynamically? I created a basic page in my drupal 7 site.

On that page I have some jquery tabs. When I click on tab1 its content displays and hides the contents of other tabs, and when I click on tab2 its content displays and hide other contents and so on.

So I want to change the title of the page in the content area according to the tab selected. If tab1 selected and its content are showing then title of the page in content area should be changed according to the tab content(for example Tab1) and similarly for others.

Is this possible?

I have tried drupal_set_title("Tab1") but it does not change the title of the page. and also it will not help me because it will change the title once and I want dynamic based on the tab selected.

You need to add an onclick() event handler for all tabs.
Assuming UL LI layout http://jsfiddle.net/k7Gkm/

$(".my_tabs").click(function(){
 $("#header").html($(this).html());
});


Strict warning: Creating default object I am getting this error on my website.

  Strict warning: Creating default object from empty value in theme541_preprocess_html()

I found a patch https://www.drupal.org/node/1242362 by Damien McKenna but I don't know how to apply the patch that fixes the error.

Applying patches is not actually a drupal specific issue and would be better on stack exchange, however there is a drupal documentation page so...

Check out the applying patches documentation.

However having said that, if you read that issue then you can see that patch was committed to that module 3 years ago and if you are using the latest release of the boron module (7.x-1.4) then that patch is already in there.

If you are applying the patch to something that isn't the boron theme then it will likely not work.


How can i programmatically trigger a Lightbox window using Drupal I'm creating a new module for a Drupal 7 site, and I was wondering if it is possible, using Drupal's AJAX functionality, to trigger a Lightbox window programmatically with PHP.

I have looked into the ajax_command_invoke() function, but unfortunately it doesn't seem to do what I need.

Edit: I would either like to run a custom function which would trigger the lightbox via  $('#id').ceebox().trigger('click'); or using another way to programmatically achieve this. (This is an example I have taken off from a non-Drupal project.)

I achieved this by using ajax_command_invoke(NULL, 'nameOfCustomFunction', array('select')); with the following JavaScript code:

(function($) {
  $.fn.nameOfCustomFunction = function(data) {
    alert(data);
  };
});


Filter users by roles I've a page showing the users. I wanted to categorized them, so I created roles and I'm grouping all the users according to their role.
Now, I want to have a filter in the view to give the opportunity to the users to select the different types of users, example: employee, student, etc. The view will display the users according to the filter value.

How can I accomplish this?

Have a look at the view People (User) view, which is located at relative path /admin/structure/views/view/user_admin_people.

This view has a User role exposed filter. You only need to implement the same filter in your view.

You need to select the same filter in screenshot below.


How to decide wich responsive base theme is better for a certain project? I know that each project is different and there´s no such a thing as one size fits all. BUT, when you want a responsive theme, you have the choice to start it from scratch or use a base theme.
The Omega Theme and the adaptive theme are both responsive and very popular. Afetr you tried both maybe you select one according to your personal tastes, but what do you keep in mind yo actually make that choice? Wich features?

Thanks for your insight!

Note: I´ve updated the post to add the Adaptive Theme instead of the mothership. I´ve checked and it seems Omega and Adaptive are very popular responsive grid themes. (Thanks Clive!)

Yes, it really does depend on your needs.  I went through this exercise last year.  These were my considerations.

Since we are a web design/development shop, we needed a base theme that we could potentially use for the majority of future Drupal 7 work.  For Drupal 6, we had been using Zen, but decided to start fresh with D7.

At the time, the decision really boiled down to Omega, Adaptive Theme, and Boron.  From here, I worked out what my dream requirements were (in no particular order):

Uses 960.gs seamlessly
Responsive layouts
As much config as possible via the UI
HTML5 starter templates
Works well with Panels

#1 and #5 are debatable pluses, but were hard requirements.

Something that works well with Context was also nice, but not a hard requirement because we leverage Panels so much.  Mobile integration was not a requirement for us, beyond the response layouts, also due to Panels.

At the time, Omega was the only real match.  960.gs can be added to any base theme, but the UI control over the grid and grid assignments is a huge bonus for us (allows clients and non-technical people to change layout without needed to bug the developers).

Now that we have several Omega-derived sites deployed, I still think we made the right decision and am glad we put a lot of thought into the process.


Showing two colorbox windows side by side...or within one main frame? I have a site that I've created for some fellow musicians to learn new songs. Generally we have a link to a Youtube video of a song then a link that opens up the tab (chords, lyrics, etc) for the song. Right now I have links that open those things up individually in colorboxes. Works fine.

What I'd like to do is have one colorbox, or frame, or iframe, etc -- that opens up and in the left side I have the Youtube video and on the right side the tab colorbox ... so as I listen to the song I can scroll down at the same time and look at the tab. Here is a link to the site: http://practice.3cnorth.com/?q=all-songs

Thanks for any ideas.

ER

One simple approach would be to just create a content type that includes both items. For instance, "songs". Then, you could:

Embed each youtube video within their corresponding tabs node.
Then, you could use a module such as Display Suite to display one next to each other (E.g. video on the left column and tabs on the right column).
After this, if you want the tabs to be "scrollable", just set a fixed height in CSS and a "scrolled" overflow. E.g.

.views-field-body pre {
    height: 300px;
    overflow-y: scroll;
}

That should do the trick, the colorbox will open one node, instead of 2 as currently.


Best way to create HTML meta tags? Issue

Users will input text that need to be copied into (hidden) meta tag fields when the user have written them into normal fields on the input node.

What I am looking for is either a module to help me with this, a user guide to doing it or an alternative solution to the issue described in the background.

Background

I need to use Meta tags quick to annotate user submitted content on my website.

The user submit article information in normal fields (ie for example an Author field exposed on any node with the article content type). My plan is to to use the Meta tags quick module to create hidden fields and then have those fields filled in by copying content from the user input fields.

An alternative is of course to use the Metatag module but I find it harder to work with and I also need to copy some other fields.

You can metatags from fields on the node with

hook_preprocess_html

e.g

/**
 * Implements hook_preprocess_html
 */
function THEME_preprocess_html(&$variables){
  // Only add on node pages
  if($node = menu_get_object('node')){
    // Read node fields, wrapper requires entity api module
    $wrapper = entity_metadata_wrapper('node', $node);
    if(isset($wrapper->field_some_field)){
      if($some_content = $wrapper->field_some_field->value()){
        $element = array(
          '#tag' => 'html_tag',
          '#type' => 'meta',
          '#attributes' => array(
            'name' => 'some-metatag',
            'content' => $some_content,
          ),
        );
        drupal_add_html_head($element, 'some_metatag');
      }
    }
  }
}


How to get product variations inside webforms? I have a product, A, B, C ... variations foo, bar, tar...

I am showing all three products in a url like drupal.dev/all-products.

I managed to display all three products via a webview. Now below these products I am making a webform to handle submissions, and in this webform I  would like to be able to show all product variations, but there seems to be no way to fetch product variations in webforms.

How can I go about doing this?

You should be able to use the hook_form_alter() to achieve this in a custom module. As long as there is a relationship between the product and its variations you can use the hook_form_alter to add and remove variations from the form. You could also use the module controller to generate a custom twig template that renders content pull from the DB.

hook form alter -
 https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Form%21form.api.php/function/hook_form_alter/8.4.x

custom twig template -
https://www.drupal.org/docs/8/theming/twig/create-custom-twig-templates-from-custom-module

custom webform twig template -
How to access webform elements in webform.html.twig


How to style answers from the Answers module to make them look as in the demo site? The voting element of the Answers module does not look as in the following screenshot:

What should I do to make them appear as in the screenshot?

First you should enable vote_up_down Field module too, so you can add it to your preferred content-type (e.g answers), while adding it, in settings it asks which kind of widget to use; set it as default, then it will be like in your picture, without any need of altering the used CSS styles. If you still dont get your desired look, it must be the CSS styles that are overwritten. Inspect the element, and look for it.