Trying to access and print the values from the fields within Paragraph I'm having trouble trying to access and print the values manually within the Paragraph. This is a snippet from the paragraph field template I have created. I wanted to access and print values manually instead of Drupal generating the markup using {{ slides.content }} so that I could customize the markup myself

{% for slides in items %}
    {{ slides.content['#options'].entity.field_label.value }}
{% endfor %}

Here's what worked for me to manually get parts of a field in a paragraph template.

This is in a field template for the actual paragraph, so for me field--field-paragraph.html.twig. I have an image field with the machine name field_image. This prints just the alt text of that image.

{% for item in items %}
  {{ item.content['#paragraph'].field_image.0.alt }}
{% endfor %}

I looked here for working with paragraph templates: https://www.drupal.org/project/paragraphs/issues/2662766#comment-12528934 and here for general drupal 8 field-getting: https://blog.usejournal.com/getting-drupal-8-field-values-in-twig-22b80cb609bd


How to use custom tokens in view header Drupal 8 I make custom token which i use in view filter but now i want to use in view header.The custom token doesn't show in view header Global: Unfiltered text (Global: Unfiltered text) or how i make "Available global token replacements" to use in view header Global: Unfiltered text (Global: Unfiltered text). Thanks in advance.

One possible soliton is to simply when declaring your custom tokens in hook_token_info()

use $info['tokens']['view']

Ex:

$info['tokens'] = [
    'view' => [
       'my-custom-token' => [
          'name' => t('Custom Token'),
          'description' => t('A custom token I created.'),
       ],
       // 'my-second-custom-token' => [...
    ],
];


How to generate a styled image with out actually creating it? There is a content type in my website called image and it has an image field. There are about 16GB images in my website and people have uploaded very high quality images.

There is an image style in my website which uses the original image plus a watermark. This causes double space consuming. People are only allowed to download this version. The number of images in my website is growing very fast and it needs lots of space.

I need to show the styled version to the user with out creating it in \styled directory.

Is there any way to handle this problem? Is there anyway to keep the site working like now, but instead of creating a separate copy of the original image, display the styled image and generate download link to the user in any other way?

Thanks.

The only way would be to use CSS and put a div with a background transparent image of the watermark overlay on top of the actual image using the z-index: attribute.

You would risk that people could inspect element or view page source and find the direct link to the image, or use a tool to strip all css and then save the image.

For total security, I'm pretty sure there is no other way than having the watermark on the image itself.


Preprocess function for node.tpl.php file I've watched a million videos and read a million tutorials trying to figure out how to create a new variable for use in a version of a node.tpl.php file by utilizing preprocessing functions, but can't figure out what I'm doing wrong.

First, I copied the node.tpl.php file, renamed it node--nameofnodetype.tpl.php, and saved it in my theme folder. Then, I edited the template.php file, trying different variations of the following code.

function theme_preprocess_nodename(&$variables, $hook) {
  $variables['link_name'] = 'link content';
}

I flushed the cache, and when I tried printing the new variable in the new node file, I got nothing. Can anyone tell me what I'm doing wrong?

To create a variable for any type of node you should use yourtheme_preprocess_node() function, and in this fuction you should specify a type of node.

Example:

/**
 * Override or insert variables into the node templates.
 *
 * @param $variables
 *   An array of variables to pass to the theme template.
 * @param $hook
 *   The name of the template being rendered ("node" in this case.)
 */

function YOURTHEME_preprocess_node(&$variables, $hook) {

  //$variables['sample_variable'] = t('Lorem ipsum.');
  // Optionally, run node-type-specific preprocess functions, like
  // YOURTHEME_preprocess_node_page() or YOURTHEME_preprocess_node_story().
  //$function = __FUNCTION__ . '_' . $variables['node']->type;
  //if (function_exists($function)) {
  //  $function($variables, $hook);
  //}

  // define $node object, so it's be easier to use it
  $node = $variables['node'];

  // add variables to node--nameofnodetype.tpl.php file
  if ($node->type == 'nameofnodetype'){

      // $variables: an array with variables
      // you need to add one, so just define it
      $variables['my_variable'] = 'whatever';

      // also you can rewrite those variables which already exists
      // for example variable: $title
      $variables['title'] = t('The new title');
  }
}

In your node--nameofnodetype.tpl.php file:

// check if your new variable exist
print $my_variable;

 * Don't forget replace 'YOURTHEME' to your theme name


Turn off webform preview message Before submitting a webform a warning is displayed:

  Here are the details you are about to report.

It appears the default text may be altered in:

Home > Administration > Structure  > Webforms > Preview settings

However, can the message be turned off, completely, via the user interface?

Fixed! Issue #2917263 There is no way of turning off the preview message


Field revision_default must be updated After installing 8.4, updated step by step to 8.5.3, now I have in Status Report the following error: Field revision_default must be updated at several entity types, Node, Media, etc.
Checking the database, I have that field in the tables *_field_data and *_field_revision but not in the tables *_revision, though apparently it should be there.

drush entity_updates lists these error but does not fix them.

Searching several hours I did not find any solution. We have a lot of content and media so uninstall and install again is not an acceptable solution.

Any idea?

you have to update your database by using the drush commands :

drush updb -y

and

drush entities-update

If you dont have drush, you can use the /update.php page.
Regards,


`drush cc all` command takes too long time, what can I do? On a site of mine drush cc all takes more than 4 mins to run. The site db is a few GBs. However, I cannot see a clear reason as to why it takes too long. What can I do to locate the bottle neck?

The clearing cache it-self doesn't take a long time, since it's just truncating cache tables. What takes time the most is rebuilding the cache registry after that. Usually it's theme registry which scanning for all new hooks and all your Drupal folders for new template files, system which scanning files for the new modules and class files, and similar.

You can always clear specific cache by specifying drush cc theme-registry or any other.

It's highly recommended that you use PHP caching mechanism (e.g. OPCache, XCache, etc.) to speed up the processing. And memory-base cache to replace heavy usage on SQL tables (e.g. memcached or redis), so clearing cache would take no time, just by flushing the cache (e.g. echo flush_all > /dev/tcp/127.0.0.1/11211 in Bash).

Alternatively you can always clear cache manually, e.g. by:

echo "SHOW TABLES LIKE 'cache%'" | $(drush sql-connect) | tail -n +2 | xargs -L1 -I% echo "DELETE FROM %;" | $(drush sql-connect) -v

Debugging

To check what's taking the most time specifically, you need to debug/profile it (e.g. XDebug, XHProf, phpdbg, dtrace).

On OS X/Unix, this can be achieved by dtrace (after running drush):

sudo dtrace -qn 'php*:::function-entry { printf("%Y: PHP function-entry:\t%s%s%s() in %s:%d\n", walltimestamp, copyinstr(arg3), copyinstr(arg4), copyinstr(arg0), basename(copyinstr(arg1)), (int)arg2); }'

On Linux, use strace, e.g.

strace -e trace=sendto,recvfrom -s1000 -p $(pgrep php)

To look for some specific things, try adding e.g.: strace ... 2>&1 | grep -C5 UPDATE.


view access permission I have a problem with view permission, when I make a view in drupal 7 there is an option "access" when I specify the option eg:"view published content" all users that has the role of published content can see all the content that are belongs to that view. But I want some thing else, I want to give the permission for users to access just his/her own published content not all published content that are belongs to that view.
cheers

You can add a contextual filter "Content: Author uid" which defaults to "User ID from logged in user". Or you could also try to add a relationship to the author of the content and compare it's uid to the uid of the logged in user.


Is there an AJAX command I can use to debug PHP variables without breaking AJAX call? I know the list of Ajax framework commands. Every one of them is doing something useful. But sometimes I want, for debug, include a piece of debug data in my AJAX response. I want it to be unobtrusive, so var_dump is out. I need to wrap my debug data in some kind of command. On the other hand, I will view it using JS console, so I don't want it to actually change anything on my page. And changing something hidden with CSS is not feasible - I'm not in charge of CSS here. So it leaves me with commands approach.

Which command could I use for this purpose?

I was thinking about ajax_command_append with selector that will never be found, but I don't want to introduce any additional errors in my JavaScript Console.

Debugging it with xdebug is not, currently, possible, and I would rather avoid spending time and resources on creating VM, when what I need is something I can do with simple var_dump on non-AJAX pages.

As far as I know, there isn't such logging or "nulling" Ajax command. That doesn't mean you can't build any! I for example, have created some custom Ajax commands, and also a eval() so I can run some quick codes.

1: Define the JS action

You need to add a new JS  file, or merge as necessary. Note this document.ready event is important (this is just the definition, so no need to be a behavior).

(function($){
    $(function() {
        Drupal.ajax.prototype.commands.js_eval = function(ajax, data, status) {
            eval(data.script);
        };
        Drupal.ajax.prototype.commands.console_log = function(ajax, data, status) {
            console.log(data.var);
        };
    });
})(jQuery);

2: The Ajax render array

Assuming you are aware of the ajax_render() and JS renderable arrays, it's time to create your own custom command.

function mymodule_ajax_command_js_eval($script) {
  return array(
    'command' => 'js_eval',
    'script' => $script,
    'my_custom' => 'my custom value',
  );
}
function mymodule_ajax_command_console_log(&$var) {
  return array(
    'command' => 'console_log',
    'var' => $var,
  );
}

Above PHP function is not really a hook, and can be any name you want. For the sake of convention, I'm using ajax_command in the function name.  In the return array, command will be called from Drupal.ajax.prototype.commands scope. You can pass additional variables, and they will be in the data for JS to access (data.my_custom, data.script, likewise.)

3: Now call it!

Now that you have the JS and PHP ends, time to call the function!

$output = array();
// $output[] = ajax_command_append('#some_random_id_that_you_d_normally_use', $html);
$output[] = mymodule_ajax_command_js_eval("alert('Big Bang Theory S8!)");
$output[] = mymodule_ajax_command_console_log($stuff_you_d_normally_dpm);

print ajax_render($output);
exit;


Media and cache keys I'm using images inside of a Paragraph, and trying to use checkboxes in the Paragraph to control whether to display the credit and/or caption of the images.

The problem is that the image gets cached the first time it loads and subsequent instances ignore the checkbox values.

I'm trying to set that cache keys so that each Paragraph + image gets its own cache instance, but keep getting errors saying that I'm not allowed to set cache keys.

I've tried in hook_media_preprocess, hook_paragraph_preprocess, hook_entity_view, hook_entity_view_alter, but no luck.

Could someone point me in the right direction?

Thanks,

Luca

This might sound like a dumb solution, but the simplest and fastest solution of hiding fields would be hiding with CSS depending on a parent (paragraph) attribute or class. E.g. in paragraph preprocess

if ($paragraph->get('your_field')->value == "hide credit") {
  $variables['attributes']['class'][] = 'paragraph--credit-hidden';
}

and in CSS

.paragraph--credit-hidden .field--credit {
  display: none;
}

Other options would be either additional view modes for media entities (if not to many permutations), additional cache contexts (depending on the case, given your problem description most likely not a good solution), corresponding to your host paragraph settings. But given your description I'd go the KISS way and avoid the coding overhead.


How do I add tags to the taxonomy data via node and the fields? I need to store the tags which newly created in the taxonomy_term_data table, and also in the node field. I created the node field as field_beaches_tags (term reference) using "Select list" as widget.

I need to store the value in this and also in the taxonomy term data table with reference vid as the tags. I have the location name field in the form; when I submit the form the location, I must store the tags in the taxonomy table and also in the node field.

 function My_beaches_create_submit($form, &$form_state) {
    $node = new stdClass();
    $node->language = LANGUAGE_NONE;
    $node->promote = 0;
    $node->uid = 1;
    $node->type = 'content_type';
    $node->taxonomy[1] = $values['location_name'];
}

1 is the vid of the tags in the taxonomy, but I am able to store the value in the database table.

In drupal 7, Taxonomy terms are attached as regular fields. So $node->taxonomy is no longer a standard property that Taxonomy module picks up.

If your field name is field_beaches_tags, assign tags to the node as below.

$node->field_beaches_tags[$node->language][]['tid'] = 23;

Note that the 23 above is the term ID of the taxonomy term.
If you have an array of terms, you can assign all of them like below:

$terms = array(23, 45, 678, 1212);
foreach ($terms as $tid) {
  $node->field_beaches_tags[$node->language][]['tid'] = $tid;
}

Keys in the $node->field_beaches_tags[$node->language] array will be used as delta values of the field.

Create a new taxonomy term

$term = new stdClass();
$term->name = ‘My New Term Name’;
$term->vid = 'vocabulary_id';
taxonomy_term_save($term);

Now, $term->tid will be populated with the new term ID that you can use.
See taxonomy_term_save() for the API doc.

taxonomy_get_term_by_name() can be used to load terms by a given name.

$term = taxonomy_get_term_by_name('my existing term name', 'beach_terms');
// $term->tid will now be in place.

Your overall code can be like the following.

$terms_given = array('Miami', 'Colombo', 'Pizza');
$node = new stdClass();
$node->language = LANGUAGE_NONE;
$node->promote = 0;
$node->uid = 1;
$node->type = 'content_type';

foreach ($terms_given as $term_name) {
  $terms_matched = taxonomy_get_term_by_name($term_name, 'beach_terms'); // "beach_terms" is the machine name of vid 1.
  if ($terms_matched) {
    //We blindly use the first match. Not very elegant.
    $first_term = current($terms_matched);
    $node->field_beaches_tags[$node->language][] = (array) $first_term;
  }
  else {
    $term = new stdClass();
    $term->name = term_name;
    $term->vid = 1; // Vid from the question.
    taxonomy_term_save($term);
    $node->field_beaches_tags[$node->language][] = (array) $term;
  }
}


Is Node a superclass of all content type? I have been trying to understand drupal 7 internals. It seems to me that the concept of node is like a superclass in OO languages. All other content types are the derived classes of Node.

Please let me know if this wrong.
Thanks.
DB

From drupal.org: An Introduction to Entities

  If you come from an OOD/P background and are trying to better
  understand what these key D7 concepts are, the following suggested
  mapping might help (albeit not strictly true from a purist’s
  perspective) :-

An entity type is a base class
A bundle is an extended class
A field is a class member, property, variable or field instance
    (depending on your naming preference)
An entity is an object or instance of a base or extended class

  All these four OOD/P concepts are special in that they are
  serialisable (stored - e.g. to a database or file). Serialisation
  takes place via the Entity API.


Is there a hook for custom line item before rules price calculation? I have a complex calculation for item price in a custom line item that I'd like to keep in code rather than rules. Is there a hook that gets called before cart calculation so I can set unit price?

Where is cart pricing calculation done in commerce? trying to find where it's run in source.

Drupal 7 (using kickstart 2)

As Clive mentioned, there's hook_commerce_product_calculate_sell_price_line_item_alter() that lets you manipulate the line item prior to the sell price calculation process executing on it. However, whatever unit price you set via that hook may be overridden by Rules that you weren't intending to apply to those line items. In my opinion, the best thing to do would be to write a custom Rules action to encapsulate your pricing and call it in a sell price calculation rule.


Images not displaying after transfer to temporary site ~username I had my site running on my local machine w/ DAMP.

I transferred (FTP) to hostgator shared server under my temporary site url http:// Address/~username. Running drupal 6.28.

My images that are under sites/default/files are not displaying.

Here's what I've done

Full html was checked
Ran update.php
Ran Cron
File permissions checked and set
Cleared cache
Reviewed status report to check issues there
Added the base_url to my settings.php file
updated my template so that it prints the base_url file
Checked file system settings
Commented out, deleted .htaccess (under files)
cleared my cache
Site is not in maintenance mode

It seems that if there has been a solution thrown out there, I've tried it. Any solutions someone could provide would be greatly appreciated.

Sorry, I just re-read the question and realised I misread it before.

Try setting your base path in the .htaccess file and also the base path in the settings.php file. (actually I think I'm confusing myself. I'll leave this here anyway.)

Previous answer

Are you talking just image style images or all images?
Can you look in the source of your page and give an example of one of the file paths that is not loading properly?

I know you have stated you have already done some of these, but this is what I would try.

Check a few images by looking at their path in the source and checking on the server that they exist in that place.
Try going in your browser, directly to one of the files, for example yoursite.com/sites/default/files/yourfile.png or whatever it is.
Check permissions of files directory and also the temporary files directory, which must exist and be writable (the status page should alert you to these anyway).
Try saving your image styles to force them to regenerate your images, and clearing your caches again.
Check files .htaccess
Check your watchdog logs for any errors that might be related (any unrelated errors should be investigated too.


Displaying values on hook_form I'm displaying a form on admin url :admin/settings/custom. In the page argument I pass array('custom_admin_form'), to the menu item. In the form function I'm writing form elements to display folder and file names present in the public folder. I get those values through the code below:

$dir_path = variable_get('file_public_path', conf_path(). '/files') ;
$fileslist = glob($dir_path . "*.*");
$dirs = glob($dir_path . '/*' , GLOB_ONLYDIR);
foreach($dirs as $directs){
     $names = explode('/', $directs);
     $fnames[] = end($names);
}

How can I display the results in the form function? I tried it using print, echo, drupal_render but nothing is working. I've also used #markup element, but it was displaying array(), not the values of array.

You can try something like this:

 $form['sample'] = array(
     '#type' => 'item',
     '#markup' => print_r($sample_values, TRUE),
 );

or simply just

print_r($sample_values);

or install Devel module and use dsm function.

dsm($sample_values);

UPDATE:

Try this:

$form['sample'] = array(
    '#type' => 'item',
    '#markup' => print_array_values($sample_values),
);

Then declare the function below:

function print_array_values($sample_values){
    $content = '';
    foreach($sample_values as $val){
            $content .= '<div>' . $val . '</div>';
    }

    return $content;
}


How do I render a field template? I have problems with rendering twig templates inside my block theme.
Is it possible to display default template for a field that I've fetched with entity manage query?

I've got a custom carousel slider module which uses 'Banner' node type. It has a banner image, link URI fields.
Everything works fine, but I would like to display the responsive image template instead of building my own HTML.

Here's how I do it right now.

        <span class="glide__arrow prev" data-glide-dir="<">&lt;
        ">&gt;

            {% for item in baners %}

                        {% if item.field_url.uri %}

                                    {% if (item.field_description.value) %}
                                        {{ item.field_description.value }}
                                    {% endif %}
                                    {% if (item.field_url.title) %}

{{ item.field_url.title }} &gt;
                                    {% endif %}

                        {% endif %}

            {% endfor %}

I am fetching banners this way.

$storage = \Drupal::entityManager()->getStorage('node');
$nids = $storage->getQuery()
    ->condition('type', 'baner')
    ->condition('status', 1)
    ->execute();
return $storage->loadMultiple($nids);

What I would like is to find a way to display a responsive image, such as in the following way.

{{ responsive_image(item.field_baner) }}

Or render them in module class so I could display them in my template.

$banerBuildParams = [
      '#theme' => 'responsive_image',
      '#width' => $variables['width'],
      '#height' => $variables['height'],
      '#responsive_image_style_id' => $variables['responsive_image_style_id'],
      '#uri' => $variables['uri'],
  ];
  //render template
  $template = $this->getTemplate($banerBuildParams);

[edit]

I think I've found a solution to render all the view I can use this code to pretender nodes (not sure it's the best approach to the problem):

node_view($baner, 'teaser');

The problem I've still got is that I use external jquery library which requires some specific html formatting which not comply with the default generated tags. Maybe somebody more experienced with Drupal could suggest something?
I know I can create my own plugin for field type. It seems a lot trouble for just one not reusable element.
What if I need to group two fields in specific DIV and some others in different one?
Using node_view I am loosing the way my code looks like:/

In general, you don't access templates directly as an API, you build render arrays. To get the render array of a field, each field item and item list class has a view method. That method accepts either the name of a view mode and uses that configuration or you can also directly pass in the configuration you want to use (Basically the array that you have in view display config entities for each component).

You can try calling that from twig directly, e.g. {{ item.view('teaser') }} or prepare it in preprocess of your template.


How to retrieve last MySQL INSERT ID from db_merge() I am using db_merge for inserting or updating new records in my table.
I want to get the last inserted record id from this table, Thank you.

While there is RETURN_INSERT_ID which can be used with db_query(), I could not find a way to use with db_merge().

<?php
  $query = "INSERT INTO {table_name} (col1, col2) VALUES (:arg1, :arg2)";
  $args = array(':arg1' => $val1, ':arg2' => $val2);
  $last_id = db_query($query, $args, array('return' => Database::RETURN_INSERT_ID));
?

I think you will have to retrieve the last ID with another query, but you would need to check with MergeQuery::STATUS_INSERT.

$status = db_merge('example')
  ->key(array('name' => $name))
  ->fields(array(
      'field1' => $value1,
      'field2' => $value2,
  ))
  ->execute()

if( $status == MergeQuery::STATUS_INSERT ) {
      $last_id = db_query("SELECT LAST_INSERT_ID()")->fetchField();
}


Is Drupal 4.7 compatible with Mysql 5.1 and PHP 5.3 I am having some strange problems with Drupal 4.7.11 on my local machine. Before I get into it I should give you some context. I am running PHP 5.3.4 and MySQL 5.1.54.

If I try to run Drupal 4.7 without any DB info it comes up to a screen that asks me to put in the DB connect info. Once I do that I get a white screen in my browser and in terminal running cron.php I get a DB connect error.

Now as I was writing this I realized that PHP 5.3 is probably a problem here. But I might as well ask anyway.

So thoughts on compatibility?

UPDATE: I realized that my machine is running two different versions of PHP because I am on a Mac and it has 5.3. However, my Apache is running from Zend Desktop which is 5.2. So the site is setup in 5.2 right now.

I think that both may be an issue. PHP definitely is. I'm not sure about Mysql.

Drupal 4.7 is quite a few versions out of date and it is no longer being maintained. You really should be looking to use a more recent version.


How to escape a string so it does not get replaced by Token::replace() I have a string that is being sent into the replace method of the token service that looks like a token, but it is not.

Here is an example of the string: "['key:value']"

Is it possible to escape this in a way that the replace function will not think it is a token that it needs to replace?

The "clear" flag in the replace function is set to true, so this string always just gets removed, but I want it to ignore this string entirely. Thanks!

Token::replace() allows you to use a callback to replace extra tokens no module define, but that is called after the tokens have been replaced; plus, it gets a array as array($original_token => $replacement) which makes things slower since you would need to replace each token one by one.

I would rather set 'clear' to FALSE, and then replace all the tokens that have not been replaced with an empty string. Since the strings you need to keep follow a specific pattern, it would be easier to remove the unreplaced tokens with preg_replace().


How to customize the markup of radio buttons in the edit/create node view? So I have a content type with several fields.
One field is a set of two radio buttons. The output code while content creation/moderation looks like this:

    Group content visibility *

            <input type="radio" class="form-radio" checked="checked" value="1" name="group_content_access[und]" id="edit-group-content-access-und-1">
            Public - accessible to all site users

            <input type="radio" class="form-radio" value="2" name="group_content_access[und]" id="edit-group-content-access-und-2">
            Private - accessible only to group members

Now I want it rather to be something like this:

  <input type="radio" class="switch-input" name="group_content_access[und]" value="1" id="Public" checked>
  Public
  <input type="radio" class="switch-input" name="group_content_access[und]" value="2" id="Private">
  Private

How can I change this markup? (I run Display suite and tried to ajust it somehow with DS settings; did not work out.)

Troubleshooting

Issue #1

In how far is $output not used anymore for radio buttons?

Issue #2

How do I add  after my second radio-button-label? (See the example above.)

Issue #3

The front page shows the following message.

  Notice: Undefined variable: output in themename_form_element() (line 309 of D:\root\sites\all\themes\themename\template.php).

You can alter the output by overriding the following Drupal theme functions: theme_form_element, theme_radios, and theme_radio. (You won't need theme_radio unless you want to make changes to the <input> tag.)

Copy these functions into your theme's template.php file and replace "theme" in the function name with the name of your theme. Customize as needed. You will have to clear your cache in order for the changes to take affect.

In theme_form_element(), if you want to limit your changes to radio elements, you can add this condition:

if ($element['#type'] == 'radios' || $element['#type'] == 'radio') {
  // your stripped down mark-up here
}
else {
  // default mark-up
}

You can also check against other criteria such as #name and #id:

if (strpos($element['#id'], 'edit-group-content-access') !== FALSE) {
  // This form element has an id of 'edit-group-content-access-und-1' or 'edit-group-content-access-und-2'.
}

A real world example that only prints the wrapper for elements that ARE NOT radio elements (only alter the code that is shown and leave the rest as-is):

BEFORE

function mytheme_form_element($variables) {
  // ...
  $output = '
' . "\n";
  // ...
  $output .= "
\n";
  // ...
}

AFTER

function mytheme_form_element($variables) {
  // ...
  $output = '';
  if ($element['#type'] != 'radios' && $element['#type'] != 'radio') {
    $output = '
' . "\n";
  }
  // ...
  if ($element['#type'] != 'radios' && $element['#type'] != 'radio') {
    $output .= "
\n";
  }
  // ...
}

Bonus tip :): If you just want to alter the attributes of the wrapper, not remove it entirely, see this example.


How do I modify the text on a breadcrumb? How do I modify the text on a breadcrumb?

Is there a way to hook this generically so that I can change the text of any breadcrumb that is shown, regardless of the page?

See How to get rid of the "/blog"-page that displays all user-blogs (or change the breadcrumb-link)? I think that you will find an example on how to change a specific text of your breadcrumb.

For example, in your template.php file you can use phptemplate_breadcrumb() to search and replace text:

function phptemplate_breadcrumb($breadcrumb) {
  if (!empty($breadcrumb)) {
    $breadcrumb = preg_replace("/old text/", "new text", $breadcrumb); // This line will search and replace text.
    return '
'. implode(' >> ', $breadcrumb) . '
';
  }
}
?>


How to fix the Feeds import error when trying to import a price field? I have a little problem with Feeds module, I read a lot on forums how to fix this error but I can't find a fix...

I'm importing products to the shop, this module can import thing pretty well but when I add list_price or sell_price to the mapping the import is stuck.

I get this error:

  SQLSTATE[HY000]: General error: 1366 Incorrect decimal value: '' for
  column 'list_price' at row 1

Yes I use CSV files, with utf8 encoding.

Don't know why I get this error I just write into the column for the price: 20.10

array(
  'név' => '100% BEEF Concentrate 1000g',
  'cikkszám' => '1',
  'description' => 'Tartalom',
  'image' => 'scitec_100_beef_concentrate_1000g_caramel_vanilla.png',
  'catalog' => 'Proteíny',
  'gyártók' => 'Scitec Nutrition',
  'nyelv' => 'sk',
  'súly' => '1000',
  'mértékegység' => 'g',
  'listázási ár' => '21.00',
  'akció' => 'uncheck',
  'kiemelt' => 'uncheck',
  'újdonság' => 'check',
)

Is this possible to fix somehow?

Another small question is that how can I check and uncheck chechboxes with feeds? What should I write into the CSV column?

you should remove single quotes form decimal value and replace uncheck/check to false/true based on value.


What is the proper way of using existing fields? I'm a Drupal beginner. I'm a bit confused about adding fields to content types.

Case 1: Suppose if I have three content-types Book, Article & White Paper. I created Authors vocabulary which contains list of all Authors.

Now, Should I create "Written by" field (term-reference to Authors) for each content-type or create the field for one content-type and use it in other content types?
What are advantages/disadvantages of either methods?
What happens if I delete a reused-field from one content-type? Does it get deleted in all others?

Case 2: I've follwing content-types: (with specified field requirements)

+--------------+----------------------+
| Content Type | Field Required       |
+--------------+----------------------+
| Book         | Year of publication  |
+--------------+----------------------+
| Presentation | Date of Presentation |
+--------------+----------------------+
| Article      | Date of Publication  |
+--------------+----------------------+
| Event        | Held On              |
+--------------+----------------------+

What should I do? Should I create a single field for one content-type & use it for all other content-types or create field for each content-type?

Help me understand clearly when & how to appropriately re-use existing fields.

Should I create "Written by" field (term-reference to Authors) for each content-type or create the field for one content-type and use it in other content types?

If you need to collect the same information for different content types, you should use a single field. Your "Written by" field sounds like the perfect case for that. If you had different vocabularies for your authors, say "Book author", "Article author", etc, you'd want (and need) to use separate fields for each.

  What are advantages/disadvantages of either methods?

One advantage is that you can query all content types by the one field. So if you find yourself wanting to view all content written by a single author, or even all content written by all authors, it will be easy to create a view to do that. But that's only useful if you need it, obviously. I suppose the main point is that the use case of the field itself will actually dictate the relative advantages/disadvantages of either method.

Also, whenever you create a field, you create two database tables (one for current data, one for revision data). There are, shall we say, "mixed" feelings about whether this method of storage is the best idea from a performance standpoint, and some people prefer to keep the number of tables down.  When you attach an existing field to another content type, the same database table is used for all of them, so that box gets ticked. Again though, this only makes sense when your data can be separated.

  What happens if I delete a reused-field from one content-type? Does it get deleted in all others?

The field will only be deleted once it has been detached from all content types. Data that belongs to the content type from which you detached the field will be moved into a deleted data table, and purged during cron runs.

On to case 2, and just ask ask yourself this...

Keeping in mind that you can have different labels for each content type's instance of the same field, will that give you enough of a visual (or data-led) cue to let you know the differences between the data?

If so, use a single date field to gain the advantages mentioned above. If not, then it makes more sense to your data design to have separate fields.

It all comes down to what's appropriate for your particular website, but hopefully the above will give you some sort of way forward.


How to make the custom module effect on the node and only one content type? The following code is used to output five images, according to what's number contained in $fen. I want to put the button in nodes of a specific content type (e.g. "company").
Which code should I use in my module to get this?

<form action="" method="get">
<input type="submit" name="fen" />
</form>
<?php
  $star = getStar($_GET['fen']);
  echo "<img src=\"xing_$xin.jpg\" />";

  function getStar($fen) {
    if ($fen < 10) {
        return 1;
    }
    elseif ($fen < 100) {
      return 2;
    }
    elseif ($fen < 1000) {
      return 3;
    }
    elseif ($fen < 10000) {
      return 4;
    }
    else {
      return 5;
    }
  }
?>

If you want to add content to nodes, you can in drupal 6 use the hook_nodeapi where op is view.

As you get the node object, you can detect the node type ect. You would need to add something like this to your module

module_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  switch($op) {
    case 'view':
      if ($node->type == 'node_type') {
        // $a3 indicates if teaser
        // $a4 indicates if page
        $node->content['my_additional_field'] = array(
          '#value' => 'HTML', // create html with theme or form function.
          '#weight' => 10,
        );
      }
      break;
  }
}


How to check for entity access when displaying views fields? I have a custom entity. There is an access callback defined in hook_entity_info() and it is called when I access the entity. Also in views when I select to display rendered entities, the entity is only shown when the user is allowed to see the entity.

However when I change the view to show 'fields' instead of 'rendered entities', the access callback is no longer called and users can see all fields (and properties) of the entity, regardless of any permissions. Looking at the executed query this makes sense, the field values are joined in and the entity is never really loaded.

So, how should one implement entity access for views when displaying fields (in Drupal 7)?

I've found How to check for entity type in Views when using hook_field_access?, but I assume that only works for joined fields and not for base entity properties, so that would be only a part of a solution.

Presuming your entity providing module has Views integration already setup, and you're not worried about pagination, you can
invoke hook_views_pre_render() to iterate over the results and invoke your access callback for each entity in your base table and filter out entries that the user doesn't have access to:

/**
 * Implements hook_views_pre_render().
 */
function MYMODULE_views_pre_render(&$view) {
  global $user;

  // Iterate over View results for our custom entity
  if ($view->base_table == 'my_entity_base_table') {
    foreach ($view->result as $index => $row) {

      // Presuming eid is the entity PK
      $results = entity_load('my_entity_machine_name', array($row->eid));
      if (!empty($results)) {
        $entity = $results[$row->eid];

        // If the custom access callback returns FALSE, remove from results.
        if (!MYMODULE_my_entity_access_callback('view', $entity, $user)) {
          unset($view->result[$index]);
        }
      }
    }
  }
}

If pagination is a concern, it's a tougher problem; adjusting the view results break consistent offsetting (e.g. page 1 might return 4 results, page 2 might return 10 results). Plus, the results of SQL query can't adjust for information that is only known by executing PHP.

In those instances, you'll have to adjust your method (e.g. hook_views_query_alter() if the access callback is DB query based, altering your View pager options, etc.) to accommodate for the access callback manipulating the view.


Multi-site variables table for shared variables (extending variable_set) I have a multi-site setup with some shared tables using db_prefix. The variables table is NOT shared. Sharing ALL variables would cause lot of trouble, but sharing only some selected variables wont.

The picture below visualizes my problem:

The entries in the green box are shared and available on all multi-sites. Whereas the selected entry information is part of the config and stored in variables. Changes in the red box are not shared and lead to inconsistency when changed on one multi-site.

At the moment I use "drush @sites variable-set ..." to make consistent changes on all multi-sites. But to keep it more simple, I want to integrate it into Drupal's backend.

I found out that there was a failed patch request already. See issue here. The patch modifies variable_get() and variable_set() with an extended query-statement, if a defined variable is set in an array. I am aware of the fact, that the patch is for drupal 5, but it could be easily adapted to drupal 7.

The workaround in the patch modifies the core, but i cannot touch it. Overwriting variable_get() functionality is quite an easy job. You just have to hook_boot() or hook_init() and replace the desired values in $conf array with your custom values.

Whats the deal?

I need to extend variable_set() and variable_del() functionality without touching core. Any ideas how i get into that?

Reading is possible, but may be costly

Code for variable_get() is:

function variable_get($name, $default = NULL) {
  global $conf;
  return isset($conf[$name]) ? $conf[$name] : $default;
}

So you need to set:

global $conf;
$conf['shared_variable'] = your_function_to_obtain('shared_variable');

Where to put it?

If your function uses other site variables, including ones provided via UI, best place seems to be a hook_boot(). You need to make sure your hook_boot() is called first. To get your module to run first, use hook_module_implements_alter() or easier and less reliable way - Modules weight module.

If you don't use any values provided via UI, you can (maybe should) put it in settings.php instead. You don't need to use global in settings.php.

Writing is way more trickier

Code for variable set() is:

function variable_set($name, $value) {
  global $conf;

  db_merge('variable')->key(array('name' => $name))->fields(array('value' => serialize($value)))->execute();

  cache_clear_all('variables', 'cache_bootstrap');

  $conf[$name] = $value;
}

As you can see, there are no hook calls, nothing. It just saves data altogether. variable_del() shares that problem.

What you can do is to override very forms, providing your own save handler that will copy data to shared table. This will not solve the issue of saves and deletes outside form submits, if they happen in module in question. Other approach would be to use triggers directly in RDBMS to synchronize tables - more reliable, but harder to maintain.

Advanced PHP debugger

A bit hardcore approach is to override built-in functions. Yes, you can do it without touching core.

You need PECL apd >= 0.2

In your settings.php (or in your module's *.inc, but include in settings.php) implement override_function($function_name, $function_args, $function_code) for variable_del and variable_set. Do not attempt this for reads, unless you want huge performance hit.


Show taxonomy children in parent I have a block view that only displays the taxonomy terms in a vocabulary. However I would like to have a link generated in that block with an "ALL" option. So I created a new taxonomy entry, which is the parent of all other terms.

However if I go to the taxonomy parent, the children aren't shown, only if the nodes are set to the parent value explicitly.

For example:

All (tid=1)
-Shirts (tid=2)
--Small (tid=3)
--Big (tid=4)
-Shoes (tid=5)

So if I were to go to http://mysite.com/taxonomy/term/1 I want it to show all nodes in terms 2 and 5 (would be ideally to have 3 and 4 show up also, but not mandatory).

I am using Drupal 7.x

Have you tried using taxonomy_get_children()?

  Finds all children of a term ID.


How to get selected term ID from drop down while ajaxing? I can't get name or ID from selected drop down during ajaxing. I was trying with code below:

if(isset($form_state['values']['submitted']['company_name'])){
    $company_ID = $form_state['values']['submitted']['company_name'];
    $form['submitted']['company_name']['#value'] = $company_ID;
}

Why is $company_ID empty?

I wasted too much time on this tiny task. However, I have done what I wanted.

Actually, I had to add $form_state['rebuild'] = TRUE; in my callback_function.

if(isset($form_state['values']['submitted']['company_name'])){
    $array_id[0] = $form_state['input']['company_name']; //$form_state['input']['company_name'] array holding the number I wanted.
    $company_ID = $array_id[0];
    $form['submitted']['company_name']['#value'] = $company_ID;
}


Pay order only after it been placed and validated I need to create a following workflow for the store checkout:

The user adds a product(s) to a cart.
The user goes to checkout.
During checkout, the user can register or authenticate on site. This is required and there is not possible to checkout as a guest.
Then it goes to the pane with contact information and payment information (? not sure do I need it at this step).
Then the user sees the last step of checkout — review.
Then the order is placed.

What I need is to send this order to validation by the store manager to ensure the product can be crafted or already exists.

I thought about CheckoutFlow plugin at first, but this does not exactly solve the problem. If I set order state in onStepChange()  differ from 'place' the order is messed. There is no order ID on complete step and order as well listed in cart.

I also thought about special CheckoutPane that blocks further checkout before the manager is change order status. But this also not looks like a good idea, and limit order numbers to the single.

The obvious solution here is let the user finish checkout as soon as possible, then he got the message that order is only set to validate now. And only after additional manual actions from the store manager, there will be possible to pay for the order (it can took days, so there will be additional emails).

I think I will use custom .workflows.yml for further order processing. When the manager is set status "validated" next to it will be a "payment" state. During this state, I want to show payment form on the user order page (entity.commerce_order.user_view) or maybe better create a special route with order_id and generate form there (in this case it also will be possible to send this link in the notification email).

Also, I will add EventListener for commerce_order.order.paid to change state from "payment" to "fulfillment".

Maybe there is a better solution and I don't see it? Did I choose the right direction to solve the issue? Are there any drawbacks to manage payments manually or behaviors I need to take into account?

UPD

I didn't mention in the original post but it seems to be very important in that case - the order can be edited after or during validation in some cases, so total amount will change and as I understand, previously authenticated payment with gateway will be invalid.

The standard approach here is to use the payment information to create an authorization for as much as you will need assuming the order is to be placed. If it's for $100 of custom merchandise, you authorize a $100 charge on the customer's credit card and then capture it after manual review. This is very typical and in many places a requirement - the idea being you can only authorize payment during checkout and capture it once the order has been shipped.

How the authorization + prior authorization capture flow works will depend on your payment gateway and the methods of payment you're accepting, but most should support this. (I don't have direct experience with Russian payment gateways if you're developing this for a Russian merchant, though.)

In your case, you might just include a message on the checkout form that the customer will see the payment authorization but will not have funds debited from their account until the order has been manually approved by an administrator. There is no automation that I'm aware of in Commerce 2.x core for capturing prior authorizations on specific state transitions, but that's something you should be able to include in your site's customizations module. Again, the exact process there will be very dependent on your payment gateway's API.


Using Views API to create a status field based on other field values (Sortable and Filterable) I need a status field to appear in a view with a table format that has values like "Needs Attention", "Awaiting Payment", "Not Interested", etc...

These values are based on values of other fields attached to the node such as a date field indicating the last time of interaction, payment received toggle, etc...

This field needs to be sortable and filterable for good reporting; so, I've started reading-up on the Views API to create custom Views Data, but I'm having trouble figuring-out where to attach the SQL expression that calculates the value.  I've seen some tutorials that are close, but they talk more about getting your custom SQL table into views and using expressions on those, but not one working with existing node field values.

Does anyone know how and where to set this up, or has anyone found something on the web describing this?

I had started in the right direction this morning Thanks to this article:  Drupal 7: Using SQL Expressions in Views 3

This afternoon, after some digging, I found that you can manually join the tables that you need to work with in the same handler as mentioned in the article, and this expression field can be added to the "views" index of the data variable, and it will still be added to the base query.

So in, mymodule.views.inc

function mymodule_views_data() {
    $data = array();

    $data['views']['student_status'] = array(
        'group' => 'Content',
        'title' => t('Student Status'),
        'help' => t('The current status of a student based on when they we last interacted with, paid, etc...'),
        'field' => array(
          'handler' => 'mymodule_views_handler_field_expression',
          'click sortable' => TRUE,
          'expression' => "
                CASE
                    WHEN
                        field_data_field_some_table.field_some_value = 1
                    THEN 'Registered'

                    WHEN
                         DATEDIFF(NOW(), field_data_field_last_interaction_date.field_last_interaction_date_value) > 30
                    THEN 'Needs Attention'

                    ELSE 'Unregistered'
                END
            ",
      'expression_alias' => 'student_status',
    ),
   'filter' => array(
     'handler' => 'mymodule_views_handler_filter',
     'allow empty' => TRUE,
   ),
    'argument' => array(
      'handler' => 'mymodule_views_handler_argument',
     'allow empty' => TRUE,
    ),
   'sort' => array(
     'handler' => 'views_handler_sort',
   ),
  );

 return $data;
}

And then in mymodule_views_handler_field_expression.inc

class mymodule_views_handler_field_expression extends views_handler_field {
  var $expression_alias = 'unknown';
  var $expression = NULL;
  /**
   * Construct a new field handler.
   */
  function construct() {
    parent::construct();
    if (!empty($this->definition['expression'])) {
      $this->expression = $this->definition['expression'];
    }
    if ( !empty($this->definition['expression_alias']) ) {
      $this->expression_alias = $this->definition['expression_alias'];
    }
  }

  /**
   * Called to add the expression as a field to a query.
   * Overrides and based on views_handler_field->query().
   */
  function query() {
    // Make sure the table is available, and get the alias.
    $table_alias = $this->ensure_my_table();

    // Boilerplate from views_handler_field->query().
    $params = $this->options['group_type'] != 'group' ? array('function' => $this->options['group_type']) : array();

    //HERE'S THE NEW STUFF
    $this->query->add_table('field_data_field_last_interaction_date');
    $this->query->add_table('field_data_field_some_table');

    // Insert the table alias into the expression and its alias, and use the add_field method of the underlying query object.
    // See add_field() in views_plugin_query_default.inc
    $this->field_alias = $this->query->add_field(NULL, $this->expression, $this->expression_alias, $params);

    // More boilerplate.
    $this->add_additional_fields();
 }

}

ALSO NOTE:
In order to use this custom field in the Context Filter and Filter Criteria, I had to create custom argument and filter handlers to replace the WHERE statement with a HAVING statement, as well as, clean-up the alias that it uses.

Argument

class mymodule_views_handler_argument extends views_handler_argument {
     /**
   * Set up the query for this argument.
   *
   * The argument sent may be found at $this->argument.
   */
  function query($group_by = FALSE) {
    $this->ensure_my_table();
    $this->query->add_having('Content', $this->real_field, $this->argument);
  }
}

Filter

class mymodule_views_handler_filter extends views_handler_filter_string {

     /**
   * Add this filter to the query.
   *
   * Due to the nature of fapi, the value and the operator have an unintended
   * level of indirection. You will find them in $this->operator
   * and $this->value respectively.
   */
  function query() {
    $this->ensure_my_table();
    $field = $this->real_field;

    $info = $this->operators();
    if (!empty($info[$this->operator]['method'])) {
      $this->{$info[$this->operator]['method']}($field);
    }
  }

  function op_equal($field) {
    $this->query->add_having($this->options['group'], $field, $this->value, $this->operator());
  }

  function op_contains($field) {
    $this->query->add_having($this->options['group'], $field, '%' . db_like($this->value) . '%', 'LIKE');
  }
}


how to change views pager links? I am using the full pager in views module. I am displaying 40 items per page.
The full pager display links like this

1 2 3 4 5 next last

I want to change it to this

1-40 41-80 81-120 next

How will I do this? Any idea about this?

You need to override theme_pager function in your template.php

You need to do couple of changes,

Use global $pager_limits variable, use in pager list rendering links to alter text data

Use below code which works

function YOURTHEMENAME_pager($variables) {
  $tags = $variables['tags'];
  $element = $variables['element'];
  $parameters = $variables['parameters'];
  $quantity = $variables['quantity'];

  global $pager_page_array, $pager_total, $pager_limits;

  // Calculate various markers within this pager piece:
  // Middle is used to "center" pages around the current page.
  $pager_middle = ceil($quantity / 2);
  // current is the page we are currently paged to
  $pager_current = $pager_page_array[$element] + 1;
  // first is the first page listed by this pager piece (re quantity)
  $pager_first = $pager_current - $pager_middle + 1;
  // last is the last page listed by this pager piece (re quantity)
  $pager_last = $pager_current + $quantity - $pager_middle;
  // max is the maximum page number
  $pager_max = $pager_total[$element];
  // End of marker calculations.

  // Prepare for generation loop.
  $i = $pager_first;
  if ($pager_last > $pager_max) {
    // Adjust "center" if at end of query.
    $i = $i + ($pager_max - $pager_last);
    $pager_last = $pager_max;
  }
  if ($i <= 0) {
    // Adjust "center" if at start of query.
    $pager_last = $pager_last + (1 - $i);
    $i = 1;
  }
  // End of generation loop preparation.

  $li_first = theme('pager_first', array('text' => (isset($tags[0]) ? $tags[0] : t('« first')), 'element' => $element, 'parameters' => $parameters));
  $li_previous = theme('pager_previous', array('text' => (isset($tags[1]) ? $tags[1] : t('‹ previous')), 'element' => $element, 'interval' => 1, 'parameters' => $parameters));
  $li_next = theme('pager_next', array('text' => (isset($tags[3]) ? $tags[3] : t('next ›')), 'element' => $element, 'interval' => 1, 'parameters' => $parameters));
  $li_last = theme('pager_last', array('text' => (isset($tags[4]) ? $tags[4] : t('last »')), 'element' => $element, 'parameters' => $parameters));

  if ($pager_total[$element] > 1) {
    if ($li_first) {
      $items[] = array(
          'class' => array('pager-first'),
          'data' => $li_first,
      );
    }
    if ($li_previous) {
      $items[] = array(
          'class' => array('pager-previous'),
          'data' => $li_previous,
      );
    }

    // When there is more than one page, create the pager list.
    if ($i != $pager_max) {
      if ($i > 1) {
        $items[] = array(
            'class' => array('pager-ellipsis'),
            'data' => '…',
        );
      }
      // Now generate the actual pager piece.
      for (; $i <= $pager_last && $i <= $pager_max; $i++) {
        if ($i < $pager_current) {
          $items[] = array(
              'class' => array('pager-item'),
              'data' => theme('pager_previous', array('text' => ((($i - 1) * $pager_limits[0]) + 1) . "-" . $i * $pager_limits[0], 'element' => $element, 'interval' => ($pager_current - $i), 'parameters' => $parameters)),
          );
        }
        if ($i == $pager_current) {
          $items[] = array(
              'class' => array('pager-current'),
              'data' => ((($i - 1) * $pager_limits[0]) + 1) . "-" . $i * $pager_limits[0],
          );
        }
        if ($i > $pager_current) {
          $items[] = array(
              'class' => array('pager-item'),
              'data' => theme('pager_next', array('text' => ((($i - 1) * $pager_limits[0]) + 1) . "-" . $i * $pager_limits[0], 'element' => $element, 'interval' => ($i - $pager_current), 'parameters' => $parameters)),
          );
        }
      }
      if ($i < $pager_max) {
        $items[] = array(
            'class' => array('pager-ellipsis'),
            'data' => '…',
        );
      }
    }
    // End generation.
    if ($li_next) {
      $items[] = array(
          'class' => array('pager-next'),
          'data' => $li_next,
      );
    }
    if ($li_last) {
      $items[] = array(
          'class' => array('pager-last'),
          'data' => $li_last,
      );
    }
    return '
' . t('Pages') . '
' . theme('item_list', array(
        'items' => $items,
        'attributes' => array('class' => array('pager')),
    ));
  }
}

And the result you can see below.


Cannot display a custom user field in php in Drupal 7 I added an array field with three possible values to the user. It is called field_user_school_category.  I am using Drupal 7.

I want to extract the field value for the current user and use it in a page in an if statement (in php text format). I just can't get the extract code to work. I can't even get the value to print - see code below. What am I doing wrong?!

The field is currently set up to accept multiple values. (I know I need to probably loop through to extract any other values later on). I have also tried using $school['und'][0]['safe_value'] instead of $school[0] amongst a myriad other things.

Any ideas or help would be very gratefully received.

Thanks Sheila

<?php
global $user;
$account = user_load($user>uid);
$school = field_get_items('user', $account, 'field_user_school_category');
$schoolcat = field_view_value('user', $account, 'field_user_school_category', $school[0]);
print $schoolcat;

Some problems, and their solutions:

Never use the PHP input filter.
When you are developing code, ensure that you have proper error reporting on. This would show you that you have a problem on the $account = line.

PHP 5.3: E_ALL | E_STRICT
PHP 5.4: E_ALL.

Your general problem is not in code per se, but in not understanding how to debug code.
If you have devel installed, you can dpm() values on a line per line basis, in an attempt to nail down the problem.
If you were to do that, you would quickly notice that $account does not contain the values you expect. $user>uid is actually a mathematical operation, and will not return the users uid. What you want is $user->uid.
field_view_value() will, as the documentation suggests, return "a renderable array", it's not going to actually give you meaningful output, and since it's an array, you can't print it.

I'm guessing what you actually want is:

<?php
global $user;
$account = user_load($user->uid);
$school_cats = field_get_items('user', $account, 'field_user_school_category');
foreach ($school_cats as $school_cat) {
  print $school_cat['safe_value'];
}


How to make a menu like this one? This menu looks really nice. Im trying to do one similar. Any suggestions on how to start and what modules should I use.

There is a module for that.  Its called TB Mega Menu.  It allows you to add markup and stuff to a menu.  It's pretty robust, if this is not what you are looking for then you will need to look into a custom solution such as a module or using views.


Removing text from main page In the main page I've got text "The front page". I managed to change that text but unfortunately I don't rembember appropriate place.

How can I remove that text?

"Find Content" (/admin/content) then Edit the node.


Overriding admin settings form from bootstrap sub theme I need a little help here. I am creating a sub theme of bootstrap theme and I need to add an additional fieldset under "Bootstrap Settings" form (similar to Components, Advanced etc which are currently present) which appears under Appearance->Settings-><THEME NAME> page. I think we can use hook_form_alter() for this but the problem is that hook_form_alter() is being always invoked with $form_id set to "search_form" and never "system_theme_settings". Thus any form updates I am making under this hook are getting applied to search box instead of admin settings form.

I referred code under bootstrap_form_alter() in alter.inc file in bootstrap theme and tried to replicate it in sub theme but it doesn't seem to work. In order to ensure that I am not making any mistakes while creating subtheme I also tried using other available subtheme such as one created by Adam Balsam (he has provided details on this in response to a question here.

Any help/pointers would be greatly appreciated.

I am listing below my code from template.php file of the bootstrap_ignitor sub theme

function bootstrap_ignitor_form_alter(&$form, &$form_state, $form_id) {
  drupal_set_message('<pre>'.print_r($form_id,TRUE).'</pre>'); ***<= this always prints as search_block_form***
  $form['actions']['submit']['#attributes']['class'][] = 'btn';
  _bootstrap_ignitor_settings_form($form, $form_state);
}

function _bootstrap_ignitor_settings_form(&$form, $form_state) {

  // Advanced settings.
  $form['themealter'] = array(
    '#type' => 'fieldset',
    '#title' => t('Theme Alter'),
    '#group' => 'bootstrap',
  );

  $form['themealter']['local_cdn'] = array(
    '#type' => 'fieldset',
    '#title' => t('NewBootstrapCDN'),
    '#description' => t('Testing...'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
  );

}

You need to create theme-settings.php in your theme directory & add following function in that to add new fields as shown in code below:

<?php
function <THEME_NAME>_form_system_theme_settings_alter(&$form, &$form_state) {
    $form['campaign_pages'] = array(
        '#title' => t('Campaign Pages'),
        '#type' => 'textarea',
        '#description' => t('Specify pages by using their paths. Enter one path per line.'),
        '#default_value' => theme_get_setting('campaign_pages'),
    );

}

Here theme_get_setting stores the value of your field.


Upload Image browser widget for drupal 6 I need the following combined options, to browse and choose images from previous uploads (or) upload new image from hard drive. Currently I configured with default upload widget(file->Image), so I can choose image from hard drive only, but I don't want to upload the same(duplicate) image again and also it will save lot of space. I want to avoid same image upload, Is any module available with both options ?

Try FileField Sources module

  FileField Sources is an extension to the FileField module. The
  FileField module lets you upload files from your computer through a
  CCK field. The FileField Sources module expands on this ability by
  allowing you to select new or existing files through additional means,
  including:

  Re-use files by an auto-complete textfield
  Attach server-side files uploaded via FTP
  Transfer files from a remote server (cURL required)
  Paste a file directly from the clipboard (Drupal 7 only)
  Select existing files through the IMCE file browser

the first one is what youre looking for.


Adding Node-Fields to query with db_select(); I am building a query using db_select(); Now I need to sort my result by a field that a added using fields. Is there some nicer way than to join field_data_field_fieldname, and revision?

I was hoping for something like $query->addFieldData("field_foo", "myfoo"); so i can simply $query->orderBy('myfoo', 'asc');

I am also wondering why there is no example in the API that joins node-fields.

To my knowledge, db_select() isn't aware of entities or fields (fields, in the context of field that are added to nodes etc.)

I imagine you'd need to do the joins to field tables yourself. I found a little example from dbtng_example--dbtng_example.module, but as per my hunch and comments below - EntityFieldQuery is actually the only correct way to do this. Fields can define their own storage which would completely break your db_select, so...

With a bit of a performance hit (which is negligible for most) you really should do it the Drupal 7 way...

Drupal 7 now has Fields in core, and with that came the EntityFieldQuery which is a querying class for finding entities (like nodes, terms, etc) by their properties (like published status) or fields (like field_page_photo or any other fields you add via UI or otherwise)

or from API:

  This class allows finding entities
  based on entity properties (for
  example, node->changed), field values,
  and generic entity meta data (bundle,
  entity type, entity id, and revision
  ID).

Some good examples and discussion here:

What's the proper use of EntityFieldQuery?

and I find myself referencing Do we need an EntityFieldQuery example? as well.


Change default tab for Media browser Is it possible to change the default tab for Media browser (Media module) in Drupal 7?
Currently I have:
Upload, Web, Library and My Files.

I would like to open Library by default, instead of Upload.

This is what you are looking for:

http://jimbir.ch/blog/changing-order-drupal-7-media-module-file-browser-tabs

I just tried and it works perfect:

  Blockquote

  Here is the original order of the file browser:

  In order to change the order and hook into this function, I created a simple custom module, mediamenu.  In this module, I will be able to hook into the media module using the hook Brandon showed me, and change the weight of the tabs, re-ordering them. The module has a folder named mediamenu, and inside two files, named mediamenu.info and mediamenu.module.  You can view and download these files from this github repo.
  mediamenu.info

  The .info file contains information about the module, name, description, version, which version of Drupal, and where to group it on the modules page.

name = Media Menu
description = This module organizes the tabs on the Media browser.
version = "7.x-1.0"
core = "7.x"
package = Media

  mediamenu.module

  In the .module file, we hook in and change the weights of the tabs, which will re-order them, the heaviest weight/lowest number first.

  The first two items here are provided by the Media module, and the Media Browser view (Machine name: media_default).  The two tabs are made by the two displays of the view,  media_browser_1 and
  media_browser_my_files.  The media_internet tab is provided by the module of the same name.  Upload is provided by the media module.

< ?php
/**
 * Change Order of Media Browser Tabs
 *
 * Implements hook_media_browser_plugin_info_alter().
 */
function mediamenu_media_browser_plugin_info_alter(&$info) {
  $info['media_default--media_browser_1']['weight'] = '-10';
  $info['media_default--media_browser_my_files']['weight'] = '-9';
  $info['media_internet']['weight'] = '-8';
  $info['upload']['weight'] = '-7';
}

  You may have additional tabs provided by other modules. You can find their machine name but looking at the source markup of the page, and looking for the data-tabid of the tab.


How to make Paragraph label configurable Drupal version 8.4.4

I have a paragraph type defined (For example Links), which only has one field of type link.

And I have Entity reference revisions field in my node edit form.

When I view the node i see the referenced field Label, How to make this label configurable?

You have a few options:

As commented, either make it a non-paragraph field
Implement some custom form alter, change the the label there
Use two different paragraph types with a different label, allow only one of the two on each node type.


How to keep Ajax refresh action when 'Use Ajax' option is disabled? I have disabled 'Use Ajax' because I don't want AJAX pagination. Unfortunately other Ajax functionality stopped working.

How to ajaxify View programmatically?

@sumit madan's approach then is the best, leave your view ajaxified, and remove the paging, simplest seems to me by overwriting this method of the behavoir in your theme:

/**
 * Attach the ajax behavior to each link.
 */
Drupal.views.ajaxView.prototype.attachPagerAjax = function() {
  this.$view.find('ul.pager > li > a, th.views-field a, .attachment .views-summary a')
  .each(jQuery.proxy(this.attachPagerLinkAjax, this));
};

just make it an empty function (add this code in your theme behavoir)

Drupal.views.ajaxView.prototype.attachPagerAjax = function() {};

this function also needs to be overwirtten:

Drupal.views.ajaxView.prototype.attachPagerLinkAjax = function() {};


will be any problem with my website if I empty all the cache tables from Database? I'm trying to move my website from localhost to a server. the size of DB is too big and from what I saw the cache tables have big size. is there any problem (for my localhost version of site) if I empty all of them? (specially cache_form)

besides that when I was trying to import the DB into server the server reported an error when it was inserting cache_views table; it is very important for me to empty this table to avoid insertion error in the future.

thanks

As per the drupal community doc for clearing the cache you can manually TRUNCATE the tables (empty, not remove) starting with cache_ and there shouldn't be any problem doing so as on visiting any page the cache is rebuilt.

However I would recommend to either use the drush, or clear the cache from the /admin/config/development/performance page.

If you want to clear the cache from code than you may try the following:

// clear cache
drupal_flush_all_caches();

Also its always safe to keep the Backup of database before making any manual operation on database.


Extract the database abstraction layer If it's possible, how can I go about extracting the database abstraction layer to use in a non-Drupal site?

If you want to use the Drupal database code in a website, without bootstrapping Drupal, you need the following files:

includes/database/database.inc
includes/database/sqlite/database.inc
includes/database/mysql/database.inc
includes/database/pgsql/database.inc

The code in those files needs to be changed, as:

The code uses the DRUPAL_ROOT constant. You could remove the code using that constant, and replace it with code that automatically loads the include file containing the class. For example, the following code uses DRUPAL_ROOT because Drupal cannot use its code registry until there isn't a database connection active, as its code registry uses a database table.

// We cannot rely on the registry yet, because the registry requires an
// open database connection.
$driver_class = 'DatabaseConnection_' . $driver;
require_once DRUPAL_ROOT . '/includes/database/' . $driver . '/database.inc';
$new_connection = new $driver_class(self::$databaseInfo[$key][$target]);
$new_connection->setTarget($target);
$new_connection->setKey($key);

It could be rewritten as follows, if you register your own function with spl_autoload_register().

$driver_class = 'DatabaseConnection_' . $driver;
$new_connection = new $driver_class(self::$databaseInfo[$key][$target]);
$new_connection->setTarget($target);
$new_connection->setKey($key);

The functions use the global $databases, which is normally defined in the settings.php file. You could replace that variable with a static property of the Database class.


How do I add custom primary menu using CSS and HTML I have a Drop down mega menu using a CSS file and a HTML file.    I want to use this instead of the Drupal primary menu.   I have been advised to change the HTML in the page-header.inc file but I don't know how to do this?

On looking at the page-header.inc file, do I place the code under the file or in the header?   I have no idea! Do I have to change this section?

<?php if (isset($primary_links)) : ?>
    <?php print theme('links', $primary_links, array('class' => 'links primary-links')) ?>
<?php endif; ?>

Any advice would be great, I'm new at this.

You could alter the menu attributes using template.php file and its functions exclusively for menu.


Displaying multiple File entity types in a view, when they have different fields to display Working with the Media module, I want audio and video files to show (user uploaded/selected) preview images when displayed in areas throughout the site (instead of the default soundwave and film clip image.) So, I added fields to those files type entities, but since Image can be it’s own preview, I didn’t add that field (since it would seem odd to make the user upload/choose the image again.) This has become a GIANT pain when trying to figure out how to show all the file types together in a single view. (I want it to show field_image for audio and video, but the file for images.)

Does that sound undoable? Nothing I've been able to try with views and relationships gets me what I need. I tried customizing the preview display mode for each, then display the "rendered entity" (which got me what I needed for displaying the images), but left me with other issues, since I was displaying field_image fields for some, but file fields for others.

Slight Update: I tried adding the field_image field to the image file type, but that seems to cause some kind of infinite loop/server error when viewing/editing that file anywhere.

What I ended up doing was just add custom tpl.php files for each of the types I was interested in (audio/video/images; e.g. file--image.tpl.php). Then, in the views, just say to render the entity instead of using fields.

I'd have liked a more elegant way, since I now have 3 more tpl.php files to worry about, but it DID fit the bill.


Pass arguments to a node How do you pass an argument from a menu to an existing node? I've read many articles on hook_menu but they seem to all talk about creating a page which references the arguments.

for example:

function myModule_menu(){
  $items['node/123/%'] = array(
    'page arguments' => array(1),
    'access callback' => TRUE,
  );
  return $items;

In my Navigation menu, I'd want to use a menu item with: node/123/option1

How would I get the argument 'option1' available to me in for example, the node.tpl.php file to manipulate the rendering of node/123 ?

At the end of the day, I'm trying to do is execute some jquery code based on a menu's argument, but the initial hurdle, how do I get access to these optional arguments on the url?

The easiest way is to use $argument = arg(2) but more formal and much better way will be to create new menu item based on node/%node:

function yourModule_menu() {
  $items['node/%node/%'] = array(
    'page arguments' = array(1, 2), // Here you can specify which parts of url are page callback arguments (starting with 0)
    'page callback' = 'yourModule_node_with_option',
    'access arguments' => array('content access'), // Try to avoid access callback = TRUE
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function yourModule_node_with_option($node, $option) {
  // build your new page here.

  // $option is your extra parameter.
  $output = $node->nid . ' ' . check_plain($option);

  // This will show you node id and value of parameter
  return $output;
}


Alter webform messages found in WebformMessageManager List item

Is there a way to change the hardcoded webform messages from /webform/src/WebformMessageManager.php?

for example, the one on line 284

  case WebformMessageManagerInterface::DRAFTS_PREVIOUS:
    $t_args = [':href' => $this->requestHandler->getUrl($webform, $source_entity, 'webform.user.drafts')->toString()];
    return $this->t('You have pending drafts for this webform.') . ' ' . $this->t('View your pending drafts.', $t_args);

The beauty about Services is that they can be overridden to your liking.

So all we have to do is extend the WebformMessageManager so we inherit all of it's properties and methods and simply alter the method you need to modify.

my_module/src/CustomWebformMessageManager.php

<?php

namespace Drupal\my_module;

use Drupal\webform\WebformMessageManager;
use Drupal\webform\WebformMessageManagerInterface;

class CustomWebformMessageManager extends WebformMessageManager implements WebformMessageManagerInterface {

  /**
   * {@inheritdoc}
   */
  public function get($key) {
    // Get custom message from settings.
    if ($custom_message = $this->getCustomMessage($key)) {
      return $custom_message;
    }

    $webform = $this->webform;
    $source_entity = $this->sourceEntity;

    // Get custom message from settings with arguments.
    switch ($key) {
      case WebformMessageManagerInterface::PREVIOUS_SUBMISSION:
        $webform_submission = $this->entityStorage->getLastSubmission($webform, $source_entity, $this->currentUser);
        $args = [':href' => $this->requestHandler->getUrl($webform_submission, $source_entity, 'webform.user.submission')->toString()];
        return $this->getCustomMessage('previous_submission_message', $args);

      case WebformMessageManagerInterface::PREVIOUS_SUBMISSIONS:
        $args = [':href' => $this->requestHandler->getUrl($webform, $source_entity, 'webform.user.submissions')->toString()];
        return $this->getCustomMessage('previous_submissions_message', $args);
    }

    // Get hard-coded messages.
    switch ($key) {
      case WebformMessageManagerInterface::ADMIN_PAGE:
        return $this->t('Only webform administrators are allowed to access this page and create new submissions.');

      case WebformMessageManagerInterface::ADMIN_CLOSED:
        $t_args = [':href' => $webform->toUrl('settings-form')->toString()];
        return $this->t('This webform is closed. Only submission administrators are allowed to access this webform and create new submissions.', $t_args);

      case WebformMessageManagerInterface::ADMIN_ARCHIVED:
        $t_args = [':href' => $webform->toUrl('settings')->toString()];
        return $this->t('This webform is archived. Only submission administrators are allowed to access this webform and create new submissions.', $t_args);

      case WebformMessageManagerInterface::SUBMISSION_DEFAULT_CONFIRMATION:
        $t_args = ['%form' => ($source_entity) ? $source_entity->label() : $webform->label()];
        return $this->t('New submission added to %form.', $t_args);

      case WebformMessageManagerInterface::FORM_SAVE_EXCEPTION:
        $t_args = [
          ':handlers_href' => $webform->toUrl('handlers')->toString(),
          ':settings_href' => $webform->toUrl('settings')->toString(),
        ];
        return $this->t('This webform is currently not saving any submitted data. Please enable the saving of results or add a submission handler to the webform.', $t_args);

      case WebformMessageManagerInterface::HANDLER_SUBMISSION_REQUIRED:
        $t_args = [':href' => $webform->toUrl('handlers')->toString()];
        return $this->t('This webform\'s submission handlers requires submissions to be saved to the database.', $t_args);

      case WebformMessageManagerInterface::DRAFT_PREVIOUS:
        $webform_draft = $this->entityStorage->loadDraft($webform, $source_entity, $this->currentUser);
        $t_args = [':href' => $webform_draft->getTokenUrl()->toString()];
        return $this->t('You have a pending draft for this webform.') . ' ' . $this->t('Load your pending draft.', $t_args);
      case WebformMessageManagerInterface::DRAFTS_PREVIOUS:
        $t_args = [':href' => $this->requestHandler->getUrl($webform, $source_entity, 'webform.user.drafts')->toString()];
// ALTER THE LINE YOU WANT
        return $this->t('MY CUSTOM VIEW PENDING DRAFT MESSAGE.') . ' ' . $this->t('MY CUSTOM VIEW PENDING DRAFT MESSAGE..', $t_args);

      case WebformMessageManagerInterface::SUBMISSION_UPDATED:
        $t_args = ['%form' => ($source_entity) ? $source_entity->label() : $webform->label()];
        return $this->t('Submission updated in %form.', $t_args);

      case WebformMessageManagerInterface::SUBMISSION_TEST:
        return $this->t("The below webform has been prepopulated with custom/random test data. When submitted, this information will still be saved and/or sent to designated recipients.");

      case WebformMessageManagerInterface::TEMPLATE_PREVIEW:
        $t_args = [':href' => $webform->toUrl('duplicate-form')->toString()];
        return $this->t('You are previewing the below template, which can be used to create a new webform. Submitted data will be ignored.', $t_args);

      case WebformMessageManagerInterface::PREPOPULATE_SOURCE_ENTITY_TYPE:
      case WebformMessageManagerInterface::PREPOPULATE_SOURCE_ENTITY_REQUIRED:
        return $this->t('This webform is not available. Please contact the site administrator.');

      case WebformMessageManagerInterface::PREVIOUS_SUBMISSION:
        $webform_submission = $this->entityStorage->getLastSubmission($webform, $source_entity, $this->currentUser);
        $args = [':href' => $this->requestHandler->getUrl($webform_submission, $source_entity, 'webform.user.submission')->toString()];
        return $this->getCustomMessage('previous_submission_message', $args);

      case WebformMessageManagerInterface::PREVIOUS_SUBMISSIONS:
        $args = [':href' => $this->requestHandler->getUrl($webform, $source_entity, 'webform.user.submissions')->toString()];
        return $this->getCustomMessage('previous_submissions_message', $args);
    }

    return FALSE;
  }

}

my_module/my_module.services.yml

services:
  webform.message_manager: # The service ID you want to alter
    class: Drupal\my_module\CustomWebformMessageManager // Your Custom Class
    arguments: ['@current_user', '@config.factory', '@entity_type.manager', '@logger.channel.webform', '@renderer', '@messenger', '@webform.request', '@webform.token_manager']

  Important: Make sure you give your module a higher weight
  than webform so your service alter runs.

You could use the Modules weight module.

OR

In Devel's execute php, execute module_set_weight('my_module', 10);


Adding Price Attributes I am searching how to add price values to existing product attributes in Drupal Commerce 2.X

For Example:
T-shirt price = $10.00

A product variation/color = Red = +$2.00

A product variation/size = Large = +$3.00

Choosing the Red would increase the price to = $12.00

And Choosing the Large would increase the price to = $15.00

Is there a way to accomplish this in Drupal 8?

In Drupal 7 there was a module called Commerce Product Attributes that allowed the Admin to add ADDITIONAL pricing after choosing an attribute to the already set pricing.

Ex. Set Price = $10.00 // Selecting a Product Attributes with a price value of $5 would then increase the total cost due at checkout to $15.00

Seems now you know the answer :)

https://www.drupal.org/project/commerce_bulk/issues/3035971


Show a field only once if the value is the same I have a content-type with a field "Shooting Date" of type "date".

I have a block-view which collects all nodes of this type.

I sort these nodes by "Shooting Date".

I now want to display the year at the top, then all elements in this year.

E.g.:

2017

-Node 1

-Node 2

-Node 3

2016

-Node 4

What I have by default ist:

2017
-Node 1

2017

-Node 2

2017

-Node 3

2016

-Node 4

Can anyone tell me how I can show the year only once if the value is the same?

You might want to use the "Grouping field".

Add your date field to your views.
Click the "Format Settings"

Select your date field in "Group Field".

Tick the "Use rendered output to group rows".
Tick the "Remove tags from rendered output".
Change the date format to "Y".

Save.


Limiting nodes returned per group in a view Using Drupal 7, I've created a view to render a list of most recent content types grouped by taxonomy. I can set a global limit for items returned but I'd instead like to limit it per group. So if I've got the terms "Apples", "Bananas" and "Carrots" I'd like to get the top three Apples, top three Bananas and top three Carrots. Currently I'm getting results such as top two Apples and one banana or top three apples.

UPDATE

I actually found a way to do it without creating multiple views. There's a module called Views Grouping Row Limit that does exactly that I'm looking for!

If I were trying to accomplish this, I'd create multiple views attachments to do this. Then you can limit the number for each easily in the pager settings.


View of file entities, sorted by upload date, reorders when updating a file I have a view of file entities, sorted by upload date. When I edit one of the fields attached to one of my files the upload date of the file gets updated. The view now shows the last modified file first and no longer the last uploaded. Is this the normal behavior? Is there a way to actually sort my view by upload date?

A quick check with drupal_get_schema() confirms that file entities have only one associated time column called timestamp; there is no separate "upload" and "modified" date. So that timestamp, presumably, gets updated every time the file entity gets saved.

This makes sense from a certain standpoint because editing a file entity could involve updating the file itself.

I decided to take a crack at a custom module that would add a new "upload date" column to the file entity table. This may be completely wrong, and I haven't tested it, so do NOT try to use it on a production website until you're sure it works, but it might just give you what you're looking for.

In mymodule.install:

function mymodule_install() {
  // Add a column to the file table for your new creation date field.
  db_add_field('file_managed', 'upload_date', array(
    'type' => 'int',
    'unsigned' => TRUE,
    'not null' => TRUE,
    'default' => 0
  ));
  // Load all existing files and set their upload date to be equal to their current timestamp.
  $files = entity_load($file);
  foreach($files as $file) {
    $file->upload_date = $file->timestamp;
    file_save($file);
  }
}
// Drop the new field if the module is uninstalled.
function mymodule_uninstall() {
  db_drop_field('file_managed', 'upload_date');
}

In mymodule.module:

// Set the upload time field to the current time when the file is first saved
function mymodule_file_presave($file) {
  if(!isset($file->upload_date) || $file->upload_date == 0) {
    $file->created_date = time();
  }
}
// @TODO make the upload date field editable.

In mymodule.views.inc:

// Add a field handler for your new field.
function mymodule_views_data_alter(&$data) {
  $data['file']['upload_date'] = array(
    'title' => t("Upload date"),
    'help'  => t("The date the file was first uploaded."),
    'field' => array(
      'handler' => 'views_handler_field_date',
    ),
  );
}

Assuming that I didn't screw up, once the module is installed you'll need to add the upload date field to your view and use it for sorting.


Admin block listing showing unwanted debug info Suddenly my Drupal 8 admin panel is displaying some unwanted objects/arrays in different places. Below is a screenshot of the block layout page.

This is a localhost site that is not available to public.

That looks like someone put a print_r or similar debugging call into your copy of Seven. If you are using git (which your project should be) you will be able to see the change in that tool and undo it.  The other solution would be to download a fresh copy of Drupal and replace the files in the core directory with the ones in the fresh copy.

If there are multiple people working on the project, ask around about who was testing out ideas and ask them to undo the changes to the admin theme.


Content type or taxonomy term? When we want some specification for a content, how should we decide whether to make that specification a separate content type or a taxonomy term?

For example, I had to build a music store site. The main content was music tracks, albums, label, music director, and producer. I made a content type (Music Tracks) and albums, label, music director, and producer were taxonomy terms which were given as entity references in the Music Tracks. Then, I was suggested to make the site scalable and thus making album, producer, and label a separate content type.

So how do content types help in making the website scalable?

There are also other solutions to your problem.

Field Collection

You can use field collection and field collection views modules to store and organize contents. Using this approach the Issue and Magazine are going to be Field Collection type, Issue is a field of Article and Magazine is a field of Issue. I have experience of implementing such structure. In my case the requirement was a Library that should contain books (with Title, Publisher and ... fields), Every book contains multiple volumes (Number of pages, translator, ... ) and each volume also contains unlimited number of some other items (like the scan of some pages that are not the same among the books).

I implemented this using Field Collection approach and it is very nice. You can easily create a link to edit every individual items of every field collection and you can also filter by items of field collection. I posted an answer to Group items in Views by value in Field Collection which shows how to work with Field Collection Views

Entity View Attachment

Also known as EVA module.

  "Eva" is short for "Entity Views Attachment;" it provides a Views display plugin that allows the output of a View to be attached to the content of any Drupal entity. The body of a node or comment, the profile of a user account, or the listing page for a Taxonomy term are all examples of entity content.

You can use EVA to display only fields values for a particular piece of content, giving incredible control over the display and formatting flexibility of the fields. For example you may desire to have two fields concatenated in some special way. You can add your fields to your EVA display, set the contextual filter to NID, add a Global: Text Field, and using tokens format your fields with HTML. Don’t forget to exclude your fields from display if you are going to use them together in a Global: Text Field. Example: You may have a city, state, and zip fields. You can combine them in a Global: Text Field in Views to display as “City, State ZIP”. When you manage the display for your content type add the EVA just created to the display and whenever a node the type is displayed it will pass its nid to the EVA and the EVA will return the fields you select, formatted as you desire. (source : EVA and Entity Reference Use Case How-to)

This module is perfect, It attaches a View as a field to nodes of a content type. I used this module to create an Album. The album contains singer (with some information about each one) and songs that contains a File, Title, Rate and ... . So I created a View of type EVA and I attached it to a node. So on the node page of every Singer, I displayed this View which gets it's appropriate information from the node. The Views with Entity Reference is a perfect tutorial of how to use this module.

Taxonomy Terms V.S Entity Reference

I recommend you to read Entity reference vs. taxonomy and Are there any benefits/caveats with using Entity Reference over Term Reference? , As it says Taxonomies are best used when organizing similar items in a hierarchical fashion. Like tags.

Taxonomy allows you to use free tagging (it can be disabled using Content Taxonomy module), which enables the creation of new tags on-the-fly. It is very easy to modify the skeleton of contents. Using this approach, regular or at least some authenticated users (who have no knowledge of programming) can change this skeleton. Hierarchical Select module is perfect example of such approach.

Even though Taxonomy is easy to use but I myself prefer Entity Reference, it opens up lot's of possibilities and scalability and allows of creation very complex structures. The concept of entity in this context is not limited to content. It can be comments, users, taxonomies and ... . It is much more scalable so you will not be worry about the customizing content types, or modifying it in the future (as it was pointed out in Entity reference vs. taxonomy). I believe the Entity approach is more powerful than Taxonomy.

There are also some other combinations of these approaches which it is unnecessary to mention them.

Anyway I recommend you fully understand Entity approach and it's related modules. If you use it in multiple projects, despite of it's complexity it will be very easy to you to use it. Not only in the yours current requirement but also in the future it is going to be a Very Reliable Tool for you.


Disable price field when checkbox is checked (node add form) I would like to disable 2 price fields when a checkbox is checked. This could be easier with webform by I want to implement that on the node add form (admin).

Thank you in advance.

For D7 you can go for
Conditional Fields

Define dependencies between fields based on their states and values.
Conditional Fields for Drupal 7 is an user interface to the new States
API, plus the ability to modify fields appearance and behavior on
certain conditions when viewing content.

Field Conditional States
The Field Conditional State module can be used when:

you have a text field you only want to be enabled when a certain checkbox is checked
you want to show a different set of fields depending on the value(s) selected in a certain select list


Migrating a Drupal 7 domain to another domain while keeping dynamically generated URLs intact? I currently have a website that does repairs and web development.

I want to separate the repair section of the website into its own domain name while also keeping the old domain's URLS intact. Since I have many pages generated by views I'm not sure how to go about doing this.

What I was thinking was clone the current site and remove what is unnecessary on the new site.. then the old site would redirect all those links to the new domain.

What is a good solution to such a migration problem?

If the two websites should be identical but available at separate domains and you use relative URLs throughout your site this is actually quite simple. This is assuming you want all links available at both domains.

Direct the new domain name to point your Drupal install.

Depending on your system configuration there are several ways you may need to do this.  If you have a dedicated IP you can simply point your domain to the appropriate IP and ff you use virtual hosts you may need to setup a symbolic link.

ln -s /var/www/example.com /var/www/newdomain.com

All relative URLs should inherit the currently loaded domain name.

I believe for this to work though you will need to leave $base_url commented out in settings.php.

/**
 * Base URL (optional).
 *
 * If you are experiencing issues with different site domains,
 * uncomment the Base URL statement below (remove the leading hash sign)
 * and fill in the URL to your Drupal installation.
 *
 * You might also want to force users to use a given domain.
 * See the .htaccess file for more information.
 *
 * Examples:
 *   $base_url = 'http://www.example.com';
 *   $base_url = 'http://www.example.com:8888';
 *   $base_url = 'http://www.example.com/drupal';
 *   $base_url = 'https://www.example.com:8888/drupal';
 *
 * It is not allowed to have a trailing slash; Drupal will add it
 * for you.
 */
 # $base_url = 'http://www.example.com';  // NO trailing slash!

Using this method I rarely have to make custom edits. This includes views output. Just make sure you always use relative URLs.

If you want the content split up between the sites or want to make change the theme or layout you may need to do something a bit more complex.

There are other more robust and complicated ways to separate out your content. A few modules and concepts that come to mind include...

Domain Access
Multi-Site (Added for reference, does not meet your requirements.)
Virtual Sites (Disclosure: I haven't used this.)
Duplicate your sites (As you mentioned in your question)

I will try to update my answer to be more appropriate with your feedback. Feel free to add details about your hosting environment and how and if the content will be split.


Export and import modules of an installation In almost every drupal installation I set up, I use a package of modules. So my question is simple. Is there any way or module or something like that that will do this in an easy way?

To be more specific I am searching for a tool or something like that that will export a list of selected modules from one drupal installation. Then after a fresh installation, I would import this list and the modules would be automatically installed.

Is there any tool/module that can achieve what I described?

Thx in advance

It sounds like you are describing two kinds of workflows.

One way is to use Features - where you package functionality into modules. In your case, you would create a Feature, select modules as dependencies as well as any configuration you want to carry forward. When the feature is enabled, all those modules are enabled.

Another way is defining dependencies with Composer (8.x) and combine that using Features and build tasks to automate this further, where nuking and reinstalling Drupal returns to the same state, kind of like an install profile in a sense.


Where does the variable for the left sidebar get set in Drupal 6? I have a Drupal 6 site where I've added a submenu for a new set of products:

products
-old products set 1
-old products set 2
-new products set
--new product 1
--new product 2
--new product 3

that goes to a page where that link then becomes a main menu item:

new products set
-new product 1
-new product 2
-new product 3

I found the code:

$variables['layout'] = 'none';
if (!empty($variables['left'])) {
  $variables['layout'] = 'left';
}

in the template_preprocess_page function in the theme.inc file.

On the main menu page, the left sidebar appears with the menu block in it ($variables['left'] is turned on) but on the submenu page, it is not appearing ($variables['left'] is turned off).  The menu block has both pages listed on the 'page specific visibility settings'.  I'm trying to figure out why the difference but the problem is I cannot find where $variables['left'] ever gets set prior to that in the code.  Any idea ??

I ended up changing the menu block settings from having the 'fixed parent item' at the top level with 'starting level' set to 2nd to having the 'fixed parent item' at 'new products set' with 'starting level' to 1st. Now they both work fine.