Unable to render title field on node template For my content type - Article I have a template

node--article.tpl.php

I currently render other fields such as the body text just fine. However the title cannot be displayed.
I'm using

print render($content['title']);
print render($content['body']);

But only the title is displayed. To make sure I'm using the right machine name, I looked at the content type configuration.

Is there something missing? Or is there something special I have to do to to the 'title' field?

I was able to print the title using

print $title;


Do 'edit node' redirect via custom PHP code? I have a rule for returning users to finish creating a cck form. I need to 'Do' custom PHP code to redirect the user to editing/finishing their cck form (node limiter limits user to only one PPE content item). The following does not work:

function ppe_edit_user_login(&$edit, $account) {
  global $user;
  $nid = db_query('SELECT nid FROM {node} WHERE uid = :uid', array(':uid' => $user->uid))->fetchField();
  drupal_goto('node/' . $nid . '/edit');
}

What am I missing?

Here is the right code, or at least code that works:

$nid = db_result(db_query('SELECT nid FROM {node} WHERE uid = %d', [account:uid]));
$_REQUEST['destination'] ='node/' . $nid . '/edit';


Exposed Form Block results on another Panel page Using Drupal 7.16 and Panels 7.x-3.3: I have created a View and exposed it's form in a Block. Then I have created two Panel Pages:

/search which displays the Exposed Form Block
/results which displays the View's Content Pane

Now whenever I submit the Exposed Form Block, it redirects to the root page (/). I am aware of the "Inherit Path" setting, but that changes nothing to me. As far as I understand, this setting isn't what I'm looking for, anyway.

How do I get the Exposed Form Block to submit its query to the page where the corresponding View Content Pane is placed? Is modifying the code the only way to achieve this?

In my theme's template.php I did the following which seemed to work

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

  // change the main search form
  // see http://drupal.stackexchange.com/questions/28404/easiest-way-to-add-x-webkit-speech-to-the-search-blocks-input-element
  // see http://adaptivethemes.com/html5-placeholder-text-for-your-drupal-7-search-field
  if ($form_id == "views_exposed_form" && $form['#id'] == "views-exposed-form-site-search-page"){
    // dsm($form);
    // redirect to a panels page with an embedded search_api view with facets.
    $form['#action']='hello';
    $form['site-search']['#type'] = 'searchfield';
    $form['site-search']['#attributes'] = array(
      'class' => array('search-site'),
      'placeholder' => t("I'm looking for..."),
      'speech x-webkit-speech spellcheck' => 'false',
      );
    // change form submit button
    //$form['submit']['#type'] = 'button';
    //$form['submit']['#value'] = '';
    $form['submit']['#attributes'] = array('class' => array('search-button'));
  }
}

Notice the part $form['#action']='hello'; ?
Make sure your using the right formid and also change "hello" to whatever page you want the results to go to

Maybe that will lead you in the right direction?


can't change the value of ONE button (search page SEARCH button) I have succesfully changed the search button text of the block but can't seem to get to do this on the search page

on the following form_alter both forms enter it and are set but only search_block_form gets affected

function MODULE_NAME_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if(in_array($form_id,["search_block_form","search_form"])) {
    $form['actions']['submit']['#value'] = "Custom Search Value";
  }
}

I have also tried doing it with function hook_preprocess_input($vars){ and also tried to set the weight of the module to run later than others

function MODULE_NAME_install(){
  module_set_weight('MODULE_NAME', 1000);
}

but I see no difference I had to resolve this using javascript
what am I doing wrong ?

Did not realize the search page is structured different than a block search here is the solution that worked posting for anyone might have the same problem

function MODULE_NAME_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if(in_array($form_id,["search_block_form"])) {
    $form['actions']['submit']['#value'] = "Custom Search Value";
  }
  elseif(in_array($form_id,["search_form"])) {
    $form['basic']['submit']['#value'] = "Custom Search Value";
  }
}


Displaying Taxonomy Term Field for Multiple Entries on a Taxonomy Term List View I'm using a view to override my taxonomy term pages to display content fields.  One of those fields is another taxonomy term (applicable divisons).  Displaying the titles of terms applied to the content is no problem (multiple field settings).

The problem comes in here.  I need to display icons that represent each of those terms that is an image field in the term itself (division icon).  I added a relationship to the view (Content:Taxonomy Terms on node).  I can then add the field, but it limits it to one of the terms/icons and it doesn't have a "multiple field settings" area.

I've searched for this quite a while and it's probably an obvious answer, but it's one I can't find or figure out.

Answer:
This isn't pretty, but it's getting me the data I want.  It needs to be cleaned up.  Thanks for the help!

<?php
foreach($data->field_field_applicable_divisions as $mydata) {
    if (isset($mydata['raw']['tid'])) {
        $term = taxonomy_term_load($mydata['raw']['tid']);
        echo "
";
        echo "field_division_icon['und'][0]['uri']) . "' title='" . $term->field_division_icon['und'][0]['field_file_image_alt_text']['und'][0]['value'] . "' alt='" . $term->field_division_icon['und'][0]['field_file_image_alt_text']['und'][0]['value'] . "'class='term-image' />";
        echo "
 ";
    }
}
?>

Also, to get a legend in the header or footer:

<?php
foreach(taxonomy_get_tree(7) as $icon) {
    $term = taxonomy_term_load($icon->tid);
    echo "
";
    echo "field_division_icon['und'][0]['uri']) . "' title='" . $term->field_division_icon['und'][0]['field_file_image_alt_text']['und'][0]['value'] . "' alt='" . $term->field_division_icon['und'][0]['field_file_image_alt_text']['und'][0]['value'] . "'class='term-image' /> - " . $term->field_division_icon['und'][0]['field_file_image_alt_text']['und'][0]['value'];
    echo "
 ";
}
?>

You are going to have to adjust this to your own use case, but the approach I would use is a little different.

First, delete the relationship.

Add (or configure) the term reference field (field_divisions?) in your query. Set it to no label, and exclude from display. Rewrite the output to [field_tags-tid] . This will give you a list of term id's.

Install and enable the Views PHP module.

EDIT:

The $row variable does not play well with multiple values, so we will switch to the $data variable.

In your view, add a Global:PHP field, and in the Output code box enter something like:

<?php
  // Select your field object.
  $obj = $data->_field_data;
  // Then get your field array
  $divisions = $obj->field_divisions[LANGUAGE_NONE]
  foreach($divisions as $division) {
    if ( is_numeric( $division['tid'] ) ) {
      $term = taxonomy_term_load($division['tid']);
      $icons= $icons. "
";

      if (isset($term->division_icon['und'][0]['uri'] )) {
        $icons= $icons. "
division_icon['und'][0]['uri']) . "' class='term-image' />
 ";
      }
      $icons = $icons . "
";
    }
  }
  print $icons;
?>

Make sure the PHP field follows the term reference field so the $row values are available to the PHP field. Then style your icons to display as you wish.


Stop from going to node on content creation I would like for when I add of piece of content for it to stay on the admin back-end.. right now it forwards the user to the created node with a message saying it's been created, but the rest of the admin interface disappears so it's difficult to get back to adding more, and certain content types look very strange in that view.

I looked at actions/triggers, but I don't see a way to distinguish between content types, and I wouldn't want comments and user posts to forward to the admin interface so I don't see that as a solution.

The Add another module might come in handy for that:

  Add another is designed to save time during repetitive content creation. It allows the content creator to add another node of the same type much faster.

It provides a 'Save and add another' button in addition to the standard 'Save' button on node forms.


button for boolean field during node display I have a boolean field in my content type which takes values either 1 or 0. I want to provide a button instead of just displaying the value of field so that the user can click on it and toggle the value.

Is it possible to doing something like this ?

Maybe you should check out the Flag module. Out of the box this module will give you the boolean field, the ajax button on the node view, and rules integration.

The flag module integrates nicely with views. Here is some helpful documentation. http://drupal.org/documentation/modules/flag

You will no longer need the boolean field on your node though so, depending on existing content may require a migration.

It does have a very large user base too and it may save you some development.


Error while loading / saving taxonomy term on external DB I have 2 different Drupal bootstraps with shared DB, and I'm switching from the "slave" bootstrap with db_set_active('shared') when need to work with the shared DB.

example:

function test_function(){
  db_set_active('shared');
  $term_tid = array_keys(taxonomy_get_term_by_name($term, $vocabulary = 'vocab'));
  if (!$term_tid){
   $term = new stdClass();
   $term->name = $term;
   $term->vid = 1;
   taxonomy_term_save($term);
  }
  db_set_active('default');
}

while using either one of the taxonomy functions, taxonomy_get_term_by_name or taxonomy_term_save giving me this error:

  PHP Fatal error:  Class name must be a valid object or a string in
  /home/user/www/includes/common.inc on line 7618

any help appriciated!

SOLVED!
after long head bashing, what fixed this for me was to manually empty the "cache" tables with PMA on the "shared" DB!

important to notice that Drupal native Clear Caches didn't do the work, it had to be removed from the DB!


Add comments to profiles How do you allow users to add comments to your profile page? I'm already using content profile module but I don't know how to add comments to it

Go to admin > content types, find your content type used as a profile (default is called 'profile') and click edit.  Scroll down to the "Comment Settings" fieldset and expand that and choose "Read/Write" and any other comment options you choose and save the content type.


importing XML file with drupal 6 nodes to drupal 7 I am using Views data export module on my drupal 6 website and created a view with data export page, as export file type i've selected XML file.

When I'm downloading .xml file, I can see quotes replaced with &quot; and rest brackets converted in to a code. How can I make them untouched when doing the .xml export?

I am also using feeds module on Drupal 7 website and cannot import that xml file = "There are no new nodes".

You're best bet would be to download a views data export from drupal 7 and one from drupal 6 and find the difference (it is easiest if the drupal 7 and drupal 6 contain the same data). Then find a way to convert one to the other, either using PHP to transfer all the data into an array then output in the required format or maybe it's as easy as just a few small changes.

Sadly there is no views data export drupal 6 to drupal 7 conversation module.


How to render HTML page with attachments only from the render array? I would like to render a full html page(with html and body tags) with content provided by a render array.

What do I need to do in order to NOT render attachments(CSS, JS, drupalSettings) from active theme or modules but solely from attachments defined in the provided render array?

So far this is quite close but I still see attachments from base theme:

\Drupal::service('bare_html_page_renderer')
      ->renderBarePage(
        $my_render_array,
        'Page label',
        'page',
        []
      );

Using my own, empty, theme hasn't helped.

Ok, I had to duplicate what bare_html_page_renderer did since it attached "default" libraries form the system module. So now with my own theme all looks good but the structure is not right. Seems like the placeholders are not working properly.

My html.html.twig source code looks like:

<!DOCTYPE html>

  <title>{{ head_title|safe_join(' | ') }}</title>
  <css-placeholder token="{{ placeholder_token }}">
  <js-placeholder token="{{ placeholder_token }}">

{{ page }}
<js-bottom-placeholder token="{{ placeholder_token }}">

but the rendered HTML will looks like:

<title>Page title</title>
<link rel="stylesheet" href="..." media="all">

the rendered content

So this is a working solution. The response has getContent() method so it can be used in code and not only as route response.

function renderHtml($some_content) {
    $html = [
      '#type' => 'html',
      'page' => [
        '#type' => 'page',
        '#title' => 'Some page',
        'content' => $some_content,
        '#attached' => [
          // At least one of these have to have value,
          // otherwise the head placeholder won't get replaced.
          'html_head_link' => [],
          'html_head' => []
        ]
      ]
    ];

    $html['page']['#attached']['html_head'][] = [[
      '#type' => 'html_tag',
      '#tag' => 'meta',
      '#attributes' => array(
        'name' => 'Sometag',
        'content' => 'somevalue',
      ),
    ], 'someid'];

    $active_theme = \Drupal::theme()->getActiveTheme();
    $render_theme_extension = \Drupal::service('theme_handler')->getTheme('rendering_theme');
    $new_active_theme = \Drupal::service('theme.initialization')->getActiveTheme($render_theme_extension);
    \Drupal::theme()->setActiveTheme($new_active_theme);

    \Drupal::service('renderer')->renderRoot($html);
    $response = new HtmlResponse();
    $response->setContent($html);
    $response->setMaxAge(0);
    $response = \Drupal::service('html_response.attachments_processor')->processAttachments($response);

    \Drupal::theme()->setActiveTheme($active_theme);

    return $response;
}

Note: when you are using this via ajax callback, you have to unset the ajax_page_state from the post request, otherwise you'll be most likely be missing some libraries.


Inserting a carriage return into t() How can I put a carriage return into the drupal t() function in Drupal 6? I tried using \n and that didn't work, which seems to make sense after reading the documentation for the function.

Never had a usecase for that and no working Drupal 6 installation, but I assume your problem isn't t() related, more PHP related.

<?php

// This does not work!
echo '\n';

// This does work on UNIX!
echo "\n";

// This does work on Win!
echo "\r\n";

Hope this answers your question and helps.


Determine main menu item on front page updating menu--main.html.twig I am trying to write a custom twig for menu--main.html.twig under Drupal 8.3.  When in the menu_links macro while on the home page, the item.in_active_trail is not TRUE.  I tried to compare the path('') to item.url but it never returns true.  I can print out both path('') and item.url and see that they output the same exact text (character for character).  Is there a special way to determine if the item.url is the front page or to string compare URL strings?

{{ path('<front>') == item.url ? 'true' : 'false' }} ==> 'false'
{{ path('<front>') }} ==> '/drupal8_test/'
{{ item.url }} ==> '/drupal8_test/'

To get the path from item.url you would have to use the method toString():

  {{ item.url.tostring }}

Instead of comparing strings a better approach might be to check for the route name of the frontpage:

  {% if item.url.routed and item.url.routename == '<front>' %}
    Front Page
  {% endif %}


can't find node_export_feeds module I want to migrate nodes from a drupal 6 site into a fresh drupal 7 site.
Looking at the node export module, under *Migrating nodes between Drupal versions
* it says you need to enable node export feeds and use the feeds module in D7 to import. Obviously I downloaded and installed the node export module and enabled all the submodules, but there simply isn't any node export feeds module listed within those.

All I'm seeing listed on my sites modules page under node export is:

Node export
Node export DSV
Node export features
Node export files
Node export relation
Node export serialize
Node export XML

You must enable the Node Export Feeds module and the Feeds module on the D7 site and import the nodes via the Feeds user interface from the D6 site.

Make sure you enable the Feeds Import and Feeds Admin UI modules as well on the D7 site


How do I collect an end date when creating a Date field in code? This is my field definition:

'ms_date' => array(
            'field_name' => 'ms_date',
            'type' => 'datetime',
            'cardinality' => 1,
            'settings' => array(
                'cache_count' => '4',
                'cache_enabled' => 0,
                'granularity' => array(
                    'day' => 'day',
                    'hour' => 'hour',
                    'minute' => 'minute',
                    'month' => 'month',
                    'second' => 'second',
                    'year' => 'year',
                ),
                'timezone_db' => 'UTC',
                'todate' => '',
                'tz_handling' => 'site',
            ),
        ),

and the instance definition:

 'ms_date' => array(
        'field_name' => 'ms_date',
        'entity_type' => 'node',
        'bundle' => 'ms_core',
        'label' => $t('date'),
        'widget' => array(
            'active' => 1,
            'module' => 'date',
            'settings' => array(
                'increment' => 15,
                'input_format' => 'm/d/Y - H:i:s',
                'input_format_custom' => '',
                'label_position' => 'above',
                'text_parts' => array(),
                'year_range' => '-3:+3',
            ),
            'type' => 'date_text',
            'weight' => '1',
        ),
        'settings' => array(
            'cache_count' => '4',
            'cache_enabled' => 0,
            'granularity' => array(
                'day' => 'day',
                'hour' => 'hour',
                'minute' => 'minute',
                'month' => 'month',
                'second' => 'second',
                'year' => 'year',
            ),
            'timezone_db' => 'UTC',
            'todate' => '',
            'tz_handling' => 'site',
        ),
    ),

I'm using these structures with field_create_field and field_create_instance respectively.

Currently the "Collect an end date" textfield is missing when I create this field. How do I enable it?

You just need to set the todate under the settings array, I believe the 2 options available are

'todate' => 'optional',

and

'todate' => 'required',


Hide new topic link based on the forum topics My goal is to create a second forum. I created a new content type called forum2 and added taxonomy_forums term reference to it.

Drupal automatically creates links for each content type.

I would like to display links based on the forum topics.
For example ,

namesite/forum/1 - only New topic link is visible
namesite/forum/4 - only link for forum2 is visible

and so on.

here is what I did

function theme_advanced_forum_node_type_create_list(&$variables) {
  $forum_id = $variables['forum_id'];

  // Get the list of node types to display links for.
  $type_list = advanced_forum_node_type_create_list($forum_id);

  $output = '';
  if ($forum_id == 1 || $forum_id == 2)  {

      $output .= '
';
      $output .= theme('advanced_forum_l', array(
        'text' => 'Add to forum',
        'path' => $type_list['forum']['href'],
        'options' => NULL,
        'button_class' => 'large',
        ));
      $output .= '
';

  }
  elseif ($forum_id == 3 || $forum_id == 4)  {
    $output .= '
';
      $output .= theme('advanced_forum_l', array(
        'text' => 'Add to forum2',
        'path' => $type_list['forum2']['href'],
        'options' => NULL,
        'button_class' => 'large',
        ));
      $output .= '
';
    }
  else {
    // User did not have access to create any node types in this fourm so
    // we just return the denial text / login prompt.
    $output = $type_list;
  }

  return $output;
}

Any help would be greatly appreciated

I got it working.
Here is the code

function theme_advanced_forum_node_type_create_list(&$variables) {
  $forum_id = $variables['forum_id'];

  // Get the list of node types to display links for.
  $type_list = advanced_forum_node_type_create_list($forum_id);

  $forum_ids = array(1,2,3,4); // Ids of forum1
  $forum2_ids = array(5,6,7,8,9,10);  // Ids of forum2

  $output = '';

    if (in_array($forum_id, $forum_ids))  {

      $output .= '
';
      $output .= theme('advanced_forum_l', array(
        'text' => 'New topic',
        'path' => $type_list['forum']['href'],
        'options' => NULL,
        'button_class' => 'large',
        ));
      $output .= '
';

  }
  elseif (in_array($forum_id, $forum2_ids))  {
    $output .= '
';
      $output .= theme('advanced_forum_l', array(
        'text' => 'New topic',
        'path' => $type_list['forum2']['href'],
        'options' => NULL,
        'button_class' => 'large',
        ));
      $output .= '
';
    }
  else {
    // User did not have access to create any node types in this fourm so
    // we just return the denial text / login prompt.
    $output = $type_list;
  }

  return $output;
}


how do I export permissions? I have changed a bunch of permission for certain roles. How do I export them?  There doesn't seem to be any yaml file created when I do drush config-export.

Permissions are stored per user role in roles yaml files.

You'll find the permissions for 'Authenticated User', for example, in user.role.authenticated.yml and for 'Administrator' in user.role.administrator.yml


Why does my user signup request have no response back? I have a Drupal website hosted on a LAMP server (dev machine on intranet).

When tried to signup using the registration page (signup page for a user), the page keeps loading with message "waiting for server".

When tried to check using firebug add on in Firefox, I saw in the "network" tab that there is no response back for the signup request.

Does it have to do with the SMTP configuration within the server?

But once logging in  with admin and checking the "people" tab shows that the user is created but there was no email sent to verify the email address

So I believe the next step after user creation (according to code) gets failed due to which there is no response and email not sent. Appreciate any help on this.

was able to resolve this. The problem was with the incorrect configuration of SMTP relay host which was blocking the sending email part while signing up, due to which the request was incomplete with no response. If anyone has the same problem it should probably be with the SMTP configuration settings on the server


How can I attach an image from an existing image field to another multi-value image field? I have the nodes that have the source image field field_old_image_field and the destination image field, field_new_image_field. field_old_image_fieldhas only one image. field_new_image_fieldcan have multiple images and probably does. I need to copy the image from field_old_image_field to field_new_image_field without disturbing the images that are already in field_new_image_field.
Here's my code so far:
foreach ($nodes as $node) {
    if ($node->hasField('field_old_image_field') && !empty($node->field_old_image_field->target_id)) {
      $image = $node->get('field_old_image_field');
      $image_uri = $image->entity->getFileUri();
      $image_alt = $image[0]->get('alt')->getString();
      $image_title = $image[0]->get('title')->getString();

      $node->get('field_new_image_field')->appendItem([
        'target_id' => $image,
        'alt' => $image_alt,
        'title' => $image_title,
      ]);
    }

    $node->save();
  }

But when I run this code in an update hook, I get
In EntityReference.php line 106:

Value is not a valid entity.

I was getting it to work earlier, but I wasn't getting the alt text or the title text copied over. What's wrong with this code and is there an easier way to do this?

The first line doesn't get you an image, it's a field item list:
$items = $node->get('field_old_image_field');

Then you can get the first item
$item = $items[0];

and append the item properties to the new field:
$node->get('field_new_image_field')->appendItem([
  'target_id' => $item->target_id,
  'alt' => $item->alt,
  'title' => $item->title,
]);


Render block programmatically in Drupal 8 returns 0 I create a block at /admin/structure/block/block-content and I want programmatically render it in our custom template files. What I did is

function hook_preprocess_page(&$vars) {

    $block = \Drupal\block_content\Entity\BlockContent::load(2);
    $vars['contact-us-info-block']= \Drupal::entityTypeManager()->getViewBuilder('block_content')->view($block);
    //kint( ($vars['contact-us-info-block']));
    //kint( drupal_render($vars['contact-us-info-block']));
}

and in page template file I try

<p>{{ contact-us-info-block }} </p>

but I only see a "0" in output.

if I use

$vars['contact-us-info-block'] = drupal_render($vars['contact-us-info-block']);

everything is Ok but I find out drupal_render is deprecated in Drupal 8.
Where is problem and how can I render a block at page template programmatically?

For display only your block in your templates with preprocess the best way is

$block = Block::load('my_block_id');
$variables['My_region'] = \Drupal::entityManager()
      ->getViewBuilder('block')
      ->view($block);

And in your page.html.twig or node.html.twig or xxx.html.twig use your variable My_region like this :

{% if page.My_region %}
    {{ page.My_region }}
{% endif %}

And in rendable array (custom module) by exemple into an controller custom in content():

public function content() {
    $block = Block::load('my_block_id');
    $block_content = \Drupal::entityManager()
      ->getViewBuilder('block')
      ->view($block);

          return array(
            '#type' => 'container',
            '#attributes' => array(
            'class' => array("Myclass"),
          ),
           "element-content" => $block_content,
           '#weight' => 0,
  );
}

drupal_render is not usefull drupal already assume the render in D8 and this is deprecated (https://api.drupal.org/api/drupal/core!includes!common.inc/function/drupal_render/8)

it's a bit heavy, it is better to use the maximum area system and does not add load block from the preprocess. In the case of using a controller in your modules this seems a justified use.


Is Drupal Commerce ready for the real world? I'm trying to make a decision between Drupal 6 + Ubercart and Drupal7 + Drupal Commerce... I'd much rather develop in 7 and am excited about Drupal Commerce but, as it is relatively young, have some concerns about its security and stability.

Does anyone have any relevant experience they would be willing to share?

The payment gateway is the key. If your chosen payment gateway is available for Drupal Commerce, I would say yes, go ahead and use it.

Even if not, there are compelling reasons to develop or help to develop the payment gateway.

Drupal 7 is much more advanced, and will continue to be relevant for much longer. Drupal 6 will not be supported when Drupal 8 is released. Suppose Drupal 8 is released in 2 years (nobody knows at this stage but it's a reasonable estimate) and your site takes 6 months to launch. A Drupal 6 site would only have a viable life of 18 months. It's something worth considering!

We're building a reasonably complicated Drupal Commerce site right now and the elements like the order system, cart, checkout and things like entity types are all fairly concrete. It's also slick to use, and offers numerous advantages over Ubercart (products do not HAVE to be nodes, opening up new ways of selling things).


Can't find migrate setting in configuration I have installed Migrate and Migrate Drupal in admin/modules.

But after installing these module, I can't find it in configuration.

Drupal version 8.

Using the Migrate Upgrade UI (easier)

  Migrate Upgrade is a UI for core upgrades from Drupal 6 and Drupal 7
  to Drupal 8. It's still under heavy development, so things may break.
  If something fails for you, check the issue queue first! There may be
  a patch. If not, check with the developers in #drupal-migrate on IRC.

  After installing Migrate Upgrade, visit your Drupal 8 site's /upgrade page. When you do you will see this helpful Home screen.

Source: Executing a Drupal 6/7 to Drupal 8 upgrade

Step 1) Install Upgrade Migrate module

Step 2) Go to yourwebsite.com/upgrade

Worth Noting

  If you have a Drupal 6 or 7 site you want to upgrade, install or update the Upgrade Status module to get a customized, up-to-date report on the status of your modules and themes in Drupal 8. Once you are ready, Drupal 8 core also includes the Migrate module to update existing Drupal 7 and 6 sites to Drupal 8 directly. Migrate is marked "experimental" in Drupal 8.0.0, but will be fully supported in an upcoming release

Source: Drupal 8.0.0 released


How to add collapsible help text to a form? I would like to add some collapsible text underneath my comment forms. Preferably, users can click a small icon, which reveals the help text. After reading https://stackoverflow.com/a/8405715/2625920, I already added a paragraph at the desired position:

function MYTHEME_form_comment_form_alter(&$form, &$form_state) {
  $form['markup'] = array(
    '#markup' => t('
Here is some very useful text.
'),
    '#weight' => -1,
  );
}

(Actually, it surprised me that this works, since #markup is not ticked for forms in the Form API Reference...) Unfortunately, simply adding

'#collapsible' => TRUE,
'#collapsed' => TRUE,

to the array does not work (which is expected according to the Form API Reference). Any suggestions?

What about putting it into a fieldset ?

$form['fieldset'] = array(
 '#title' => 'title',
 '#type' => 'fieldset',
 '#collapsible' => TRUE,
 '#description' => 'desc',
);

$form['fieldset']['some_text'] = array(
  '#markup' => '
Here is some very useful text.
',
  '#weight' => -1,
);


How to convert the Drupal View Query to MySQL query? There are some views in my site. I have configure the setting to fetch the Views query. I want to convert those query to MySQL query to run & getting the result directly.

How can I do this?

Try the Views Show Query  module

This module shows real SQL query in Views UI during live preview.
'Real query' means it is rewritten by query_alter hooks. For instance, node access checks are added, so this requires selecting the user on behalf of which the query is supposed to be executed. So the module adds 'User ID to show final query' field in views preview form. You must enter numeric user ID in this field to view the real SQL query.
This module makes it possible to show SQL query not only during live preview, but when the view is executed normally. You can add footer to the view with the following PHP code:

<?php
$rows = array();
$view->exposed_input['views_show_query_uid'] = 1;
views_show_query_views_preview_info_alter($rows, $view);
drupal_set_message($rows['query'][0]);
?>

OR
There another module called Query Coder which Convert SQL query to Drupal Database abstraction layer code.


How to list nodes posted in current month? I try to list nodes posted in current month, with Views.

I tried to add a Contextual filter: Created: month, but no node appears.

I tried a Filter criteria: Content: post date / Is equal to / An offset ... / "-1 month", but no node appears.

Do you know how can it be done?

Add a filter criteria Content: Post date and select Is greater than or equal to, value type An offset from current time and value -1 month.

Screenshots:


How to use entity field as div background image in Views Slideshow? I have a "background image" field for a particular entity type. I want to be able to upload an image there, and have that image be displayed as a background image in a div created by a View. An example use case would be a Views slideshow where that background image would be the background image of the slide being viewed, and the entity title and any other chosen fields would be laid on top of that.

One thought I had was to rewrite the output of one of the slideshow fields but I'm not sure how I can rewrite the image into a "background image" position.

Is this possible? Any ideas on how to accomplish this?

Thanks!

Make sure to have a look at the Background Images Formatter module. It allows you to define a background-image (and size) for any given CSS-selector, as specified in your view (using an image field).

This actually takes care of the popular demand of using specific background images in views (and avoiding the inline-style method, which is impossible in Views)


How can I check whether cck field's content is changed in node_update hook? I want to check whether cck field's content is changed in node_update

I tried the same with following conditions but it gave me incorrect result.

if($node->field_event_type['und'][0]['value'] == $node->original->field_event_type['und'][0]['value']){
   echo "same";
}else{
   echo "changed"
}

Thanks.

From documentation:

  Note that when this hook is invoked, the changes have not yet been written to the database

So you can use

$old_node = node_load($node->nid);

Then simply compare $node provided to a hook with $old_node obtained from database.


Where is saved the value of the 'help text' of field of content type? I know that you can set help text for any field in the content type, but where this text is saved in databese, because I want to access it in other way not only for tooltip?

Thanks

It's in the field instance settings (stored in the field_config_instance table). The preferred API method to use is field_info_instance():

$info = field_info_instance('node', 'field_foo', 'article');
$help_text = $info['description'];


Assign Fields programatically to custom node defined by custom module Trying to convert a module from Drupal 6 to Drupal 7 which defines its own node type in hook_node_info.

Even though hook_node_info defines has_title and has_body to TRUE, how I can get these fields to appear on the node form? Previously, I used hook_form():

function mymodule_form(&$node, $form_state) {
  $type = node_get_types('type', $node);

  if ($type->has_title) {
    $form['title'] = array(
        '#type' => 'textfield',
        '#title' => check_plain($type->title_label),
        '#required' => TRUE,
        '#default_value' => $node->title,
        '#weight' => -25,
    );
  }

  if ($type->has_body) {
    $form['body_field'] = node_body_field($node, $type->body_label, $type->min_word_count);
    $form['body_field']['body']['#rows'] = 5;
    $form['body_field']['body']['#description'] = 'Enter a short message to present to the user.';
  }

  return $form;
}

In D6, this worked fine for me. In Drupal 7, hook_form has changed, and I am not quite following the documentation of it.

How can I utilize the Body and Title Field in core and assign them to this node type when the module is activated?

Furthermore, how can I define a new Field type to mimic Body (Long text with summary) to something of my choosing?

To add the body field to a content type, you use node_add_body_field(). To add a field that is not the body field, you use field_create_field(), if the field doesn't exist, and field_create_instance() to assign an instance of the field to an entity (e.g. a node or a user object).

As example of how to use those functions, you can look at standard_install(), which is the installation hook of the standard profile, that contains the following code:

  $field = array(
    'field_name' => 'field_' . $vocabulary->machine_name,
    'type' => 'taxonomy_term_reference',
    'cardinality' => FIELD_CARDINALITY_UNLIMITED,
    'settings' => array(
      'allowed_values' => array(
        array(
          'vocabulary' => $vocabulary->machine_name,
          'parent' => 0,
        ),
      ),
    ),
  );
  field_create_field($field);

  $instance = array(
    'field_name' => 'field_' . $vocabulary->machine_name,
    'entity_type' => 'node',
    'label' => 'Tags',
    'bundle' => 'article',
    'description' => $vocabulary->help,
    'widget' => array(
      'type' => 'taxonomy_autocomplete',
      'weight' => -4,
    ),
    'display' => array(
      'default' => array(
        'type' => 'taxonomy_term_reference_link',
        'weight' => 10,
      ),
      'teaser' => array(
        'type' => 'taxonomy_term_reference_link',
        'weight' => 10,
      ),
    ),
  );
  field_create_instance($instance);

The code is adding a taxonomy term field to the content type "Article."


Set entity reference field in form to readonly I am building a custom module to set default values for entity reference fields. To avoid overwriting these defaults, i would like to set the field readonly. While I got the defaults to work, setting it readonly does not work, the field is still editable. Here is my code :

function prepopulate_references_form_alter(&$form, $form_state, $form_id) {
  $query = new EntityFieldQuery();
  $query
    ->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'producttype')
  $result = $query->execute();
  $refobject_ids = array_keys($result['node']);
  // the next line works great:
  $form['field_testreference'][LANGUAGE_NONE]['#default_value'] = $refobject_ids;
  // this line doesn't have any effect:
  $form['field_testreference'][LANGUAGE_NONE]['#attributes']['readonly'] = TRUE;
  // ... and this one neither:
  $form['field_testreference'][LANGUAGE_NONE]['#attributes']['disabled'] = TRUE;

What is the problem here?

Edited:
As Darvanen suggested, dpm() shows that $form['field_testreference']['#access'] = FALSE; works great.

Perhaps it's because you're referencing a language where it isn't necessary, try one of these:

$form['field_testreference']['#access'] = FALSE;

or

$form['field_testreference']['#attributes']['readonly'] = TRUE;


Standards/recommendations for Drush make files included in contrib modules What are the standards/recommendations for Drush make files that are included in contrib modules? Specifically, should these make files be included by default (module_name.make) or not (module_name.make.example)?

If they should be included, what is the recommended/supported method of overriding/ignoring them? Is there any documentation to point module maintainers to when discussing this in their issue queues?

EDIT: Found this post by jhedstrom from June 2012 recommending naming make files with '.example' suffix. Is this still the recommendation, or have things changed since then?
https://drupal.org/comment/6160018#comment-6160018

@jhedstrom recomendation is valid. Modules should not include a module_name.make file, to prevent drush make running them on recursion. Adding module_name.make.example is desired, and is helpful to build makefiles, specially when the module has several dependencies, including libraries.

OTOH profiles do include makefiles. It is a common practice for a different use case, where discovery and recursion is desired.


Forms - Save Draft and unique user access code to Resume (on any computer) Is it possible for the site users to get a unique access code, so that they can resume the form from any computer?

I am currently using the Webform module for its "Save Draft" feature and am wondering if it is also able to provide an access code ...

You could always have users register accounts, use their passwords as the access code, and then use one of the revision management modules (Workbench, Revisioning/Workflow, etc.) to handle draft/publishing.


A custom image style is not working I have created a block view with title and image using fields. When I use the default image styles, they work as they should.
The custom image style I created is a thumbnail (120 x 70) with canvas. When I try using this style in Views, I get the original image size.

Have you checked the image preset is created fine after applying the resize/crop function on
admin>config>media>image-styles

Just check the thumbnail(right one) is created fine by clicking on it.

Now when we add any image field in any view, make sure to use this style for display of this field

Please check with these points.
And it works with Global text fields also.


How to setup Recaptcha on pages cached by Varnish? On a site where a contact form is displayed at the bottom of each page, I implemented Varnish caching. To do so I had to deactivate Recaptcha to avoid 'no cache -must revalidate " headers.

I tried other antispam solutions such as Honeypot or Botcha, but Honeypot is not efficient (at least with time limit  disabled), and Botcha also invalidates cache. I'd really prefer to go on with Recaptcha

I tried also Boost Captcha dev version : as per this related Varnish issue, it should be quite straightforward to make it work for Varnish. But this doesn't help, cache  is still invalidated.

Did anybody could make Recaptcha work with Varnish ?

CAPTCHA and reCAPTCHA modules are incompatible with page caching.


no changes in bg color have inspected element for this site and try as I might changing bg color in body for style.css makes no difference no matter how much caches are cleared.

I want to leave the tiled background and just change the inset white to another color. I didn't see background color in LAYOUT REGION sorry..this has been solved now.

The reason why the color is not showing is because you have this already:

body {
    background: url(images/body.png) fixed;
}

from my_elegant.css.

You have a background image already set. If you want to use a css color then you need to tweak the css for body to something like this:

body {
  background-color: #000;
}

or you can have an image background and a color at the same time:

body {
  background: #fff url(images/body.png) no-repeat center top;
}

If you are using style.css make sure that the file is properly added otherwise it could result to 404 and all the css in that file will not get applied. You can use drupal_add_css() api to add new css file or in the .info of your theme.


Hooking a JS script at node submission to alter data submitted I am building a website in which a lot of the text comes from Word docs.
The problem is that when you copy from a Word doc to WYSIWYG editor, the resulting HTML and CSS is horrible.

I want to implement a JS script that will run whenever a node (Drupal's basic page) is created or updated, to clean and optimize the data.

I've seen that I must create a custom module and use a hook.
Looking through the list of Drupal 7's hooks, I've noticed hook_node_submit() which seems perfect but in it's documentation (here) is written:

  This hook is intended for adjusting non-field-related properties.

So:

Do I have any other method simpler than module?
What is the correct hook I should use?

You can look into either https://www.drupal.org/project/sanitizable or
https://www.drupal.org/project/pasteformat both does the job.

and if you are looking hook based solution, i would suggest you hook_node_presave worth looking their documentation.


Ajax InvokeCommand with custom Callback Primary tabs View(active tab) I tried to do a what described in https://api.drupal.org/comment/56868#comment-56868, but for Drupal 8.

Drupal.behaviors.corsFileAutoUpload = {
  attach: function (context) {
    $(context).find('input[type="file"].s3fs-cors-upload').once('auto-s3file-upload').on('uploadToS3', Drupal.s3fs_cors.uploadToS3);
    },
}

To invoke this from PHP, I used the following code.

$response->addCommand(new InvokeCommand($selector, 'uploadToS3');

But I got an error from core/misc/ajax.js line number of 1266, as the method for the element is not available. On inspecting eventlistener in Chrome, it was very well visible and I was also able to fire it from Browser Console.
I am missing something here. How do we call a custom jQuery function using InvokeCommand?

In the JS side try with this:

(function($) {
  $.fn.uploadToS3 = function() {
    // Your code here.
  };
})(jQuery);

the PHP part looks ok to me.


How to intercept the loading of a field? I have a field called field_price.  How do I get that field on my page to display Free when the value is $0.00, and the actual value every other time?

I tried to intercept the loading of the field by doing things like:

mytemplate_hook_load(){
// do stuff
}

mytemplate_process_field(){
// do stuff
}

mytemplate_preprocess_field(){
// do stuff
}

etc.. etc.. etc..

I tried so many different permutations of the above as modules, template, changing function names etc...  But none of them ever fire.  I know I have the Field module enabled.

What am I doing wrong?

Note: I am using drupal 7

Ok, i figured it out.  I put this code into my template.php of my theme:

function johncustom_field__field_price(&$variables) {
        if($variables['element'][0] == '$0.00') return 'Free';
        else return $variables['element'][0];
}

I also had to clear the cache several times before this function would fire.


Difference between $bundle and bundle() Background information: I'm trying to manipulate the available options of a list type text field, depending on the host bundle:

function wtbase_options_list_alter(array &$options, array $context) {
  $fieldDefinition = $context['fieldDefinition'];
  if ($fieldDefinition->getName() == 'field_aos_cell' && $fieldDefinition->bundle() != 'link') {
    foreach ($options as $key => $value) {
      if ($key == 'link-horizontally-opposing') {
        unset($options[$key]);
      }
    }
  }
}

The $fieldDefinition->bundle part is really confusing. There seems to be a variable  $fieldDefinition->bundle (containing the expected bundle name link) and a function $fieldDefinition->bundle() (containing field_config). But I can't access the variable bundle, because this crashed with Cannot access protected property Drupal\field\Entity\FieldConfig::$bundle.

After some digging I found FieldConfigBase::getTargetBundle(), which did return the expected result and did not crash (yet).

So this leads to two questions:

What is the difference between $bundle, bundle() and getTargetBundle() and which one I'm supposed to use? I'd prefer using variables, because they are visible in Xdebug, while functions are not.

And in a more general point of view, are there some guidelines when to use functions and when to use variables? In the same example as above Xdebug printed the same weird results for e.g. entity_type vs entityTypeId vs getEntityType() vs getEntityTypeId().

--

Update, clarification for question 1:

I know the technical difference between a member property and a member function. But I'm deeply confused that a property $bundle and a function bundle() of the exact same name are returning values from a completely different entities/context. In my example $fieldDefinition->bundle returns a Paragraph bundle name link, while $fieldDefinition->bundle() seems to return the bundle name from FieldConfig. I know this is technically possible... but why would anyone write code like this? I've not yet experienced this behavior anywhere else in Drupal core, usually $entity->bundle and $entity->bundle() return the same result.

bundle is the property on the object. It's where the value is stored. Properties can be assigned one of three ways:

public: these properties can be directly set or read on the object. Example:

$object->key = 'value';
$value = $object->key;

private: These can only be accessed by methods (functions) of the class itself. Nothing else can access it. For example, this will throw an error:

$value = $object->key;

Whereas this would be allowed:

class Example {
  private $key;

  function getPrivateValue() {
    return $this->key;
  }
}

$value = $object->getPrivateValue();

$key cannot be accessed outside of the class, since it is private. This can be used to enforce rules on the types of data to be stored in the property. Checks can be run to ensure it's an allowed data type.
protected: These are like private properties, however if a class extends the class, the extended class can access the property. If the property is private, extended classes cannot access it.

One thing for you to understand is that $node->bundle and $node->bundle() are not the same things. The first is a property, the other is a method. This should help understand, as a (non-real) example:

class Node {
  protected $bundle;

  public function bundle() {
    return $this->bundle;
  }
}

The above class has the property $bundle, and the method (function) bundle(). The method returns the value stored in the property.

Look at the error you are seeing: Cannot access protected property Drupal\field\Entity\FieldConfig::$bundle. This is because you are trying to access the $bundle property, but it is protected, meaning you cannot access it from outside the class.

To get the bundle of a node, you need to call the bundle() method on it, which will give you the bundle type. This is the answer to your question about which to use.

  And in a more general point of view, are there some guidelines when to  use functions and when to use variables?

It's generally thought to be a best practice to not provide direct access to properties on objects, and instead create setter and getter methods (functions) on objects to set and retrieve the property values. That way you can say, enforce a pattern:

class Example {

  protected $username

  public function setUsername($username) {
    if (!is_string($username)) {
      throw new \Exception('Username must be a string');
    }
    elseif (!preg_match('/^[a-zA-Z0-9_-]{3,12}$/', $username)) {
      throw new \Exception('Username must be between 3 and 12 characters, and may contain only alphanumerics, underscores or hyphens');
    }

    $this->username = $username;
  }

  public function getUsername() {
    return $this->username;
  }
}

The above enforces that username is both a string, and is the right length and only contains allowed characters.

Edit: Additional comment from Leigh:

another reason to avoid accessing the property directly is when you have multiple values. e.g. if you have a field "my_field" on a node which has multiple values if you use $node->my_field->value you'll only get 1 value returned


Disable the toolbar module in install profile How do I disable the toolbar module in my make file / profile info / install file?

From an install file perspective, you can use a combination of module_exists and module_disable, in an implementation of hook_enable.

Example:

function MYMODULE_enable() {
  if (module_exists('toolbar') {
    module_disable('toolbar');
  }
}

Module enabling/disabling isn't within the scope of a make file, so that won't work.

Lastly, as far as I'm aware, if a module is not declared as a dependency of a profile, the it won't be enabled.  If I'm mistaken, you can still use the code shown above to disable the module (although I can't 100% confirm where to put it, as I've never made an install profile).


Swap out blocks based on domain name extension We have a European site that is the same exact site for three different domain names. So www.mysite.eu, www.mysite.ie and www.mysite.ch all go to the same site. However, we would like to make very small subtle changes based on which domain extension they come from. Really, I just need to swap out a couple blocks based on the domain.

I know there is the Domain Access module, which we actually use on another site, but I really didn't want to have the huge overhead and configuration and headache of everything that comes with the Domain Access module, just to swap out a couple blocks and that's it. The rest of the site in it's entirety will be exactly the same for all three domains.

I have put a hack in place using JavaScript right now, but it's not the most elegant solution. I was wondering if there is something else I could try besides Domain Access.

If you're still using D7 (there's no D8 port at the time of writing this), you could use Context Domain in conjunction with the Context module, or port the D7 version to D8. There's also option of creating a hook_block_access invocation to control display on a view operation.


Views: how to add rel attribute to multivalue image thumbnail I know about lightbox module, but I need a universal solution working with more than one jQuery plugin.

There is a view with image field displayed as a thumbnail and I'd like to link it to the normal image, and the link should have "rel" attribute.

How to implement it in the simplest way?

In the View->Fields->myfield properties, the first option (Link image to File) won't work because there is no option to insert "rel" attribute.

The second option is to REWRITE RESULTS and "Output this field as a link" and insert "lightbox" as a rel text. But what to write in the "Link path" textbox??

The path to image is: /sites/example.com/files/gallery/img1.jpg

How to obtain the "/sites/example.com/files/" path other than just
hardcode typing it? (it's a public:// stream)
How to obtain the "img1.jpg" image name? I tried [field-image]
replacement token but didn't work and there seem to be no fields that look like the file name.

You can install Image URL Formatter module. This will give you "Image URL" as a formatter option on Views.

So what to do is:

Add the image field, and Exclude from display. Set the formatter as Image URL
Add the same image field again. This one should be outputted as a thumbnail with Image Styles (perhaps), and have the normal "Image" formatter. Rewrite -> Output this image as a link, put the field added in step 1 to the link path.


Taxonomy term name as contextual filter for view In D7 I was able to filter a view according to a taxonomy term name taken from the URL. An example would be this URL

http://www.gbyte.co/tags/drupal-planet/rss.xml

"drupal-planet" would be converted to the taxonomy term ID which then would filter the view results accordingly.

Now I have set up a corresponding D8 view with a contextual filter "Content: Tags (field_tags)", field_tags being the taxonomy field. However the D8 view will only show results when I pass the actual term ID into the URL like this:

http://www.gbyte.co/tags/9/rss.xml

I would like it to also work with the term name like D7 did. Is the functionality missing, or do I need to configure the view differently?

The Term name converted to Term ID filter looks to be missing for D8 Views.

One site-builder workaround, is to add a Relationship, Taxonomy terms on node then to add a Taxonomy Term: Name filter to Contextual Filters using the aforementioned relationship. Checking the Specify validation criteria checkbox, set your Validator to Taxonomy term name & check the appropriate Taxonomy to filter on.


Ajax button strange behaviour when clicked twice I have a form where there is a dropdown with names, a button to add the names to a table and a table showing the list of names.

When clicking the button, an AJAX request is fired, the selection is added to a database table, the html table is reloaded and updated.

Everything works fine for the first click. The assigned ajax callback routine is called.

When I like to add the second name, the ajax callback is NOT called, but the standard submit function is called instead.

Here is some sample code - first the elements for the form:

$form['auctionpersons']['add_person'] = array(
  '#type' => 'select',
  '#title' => t('Select person to add'),
  '#options' => $aPersons,
);
$form['auctionpersons']['add_person_btn'] = array(
  '#type' => 'button',
  '#value' => 'Add person',
  '#description' => 'Click button to add person',
  '#ajax' => array(
      'callback' => 'add_auction_person_ajax_callback',
      'effect' => 'fade',
  ),
);
...
$form['auctionpersons']['ptable'] = array(
  '#theme' => 'table',
  '#header' => $pheader,
  '#rows' => isset($aPersonsTable)?$aPersonsTable:null,
  '#disabled' => TRUE,
  '#title' => 'Users currently assigned',
  '#empty' => t('No users assigned yet!'),
  '#prefix' => '
',
  '#suffix' => '
',
);

Now the function for the ajax callback:

function add_auction_person_ajax_callback($form, &$form_state) {
  dpm('172: add_auction_person_ajax_callback');
  dpm($form_state);
  add_person_to_table($form_state['values']['add_person']);
  $aPersonsTable=get_person_table_rows();
  $form['auctionpersons']['ptable']['#rows']=$aPersonsTable;
  $commands = array();
  $commands[] = ajax_command_html('#ptable_wrapper', render($form['auctionpersons']['ptable']));
  return array('#type' => 'ajax', '#commands' => $commands);
}

Can anyone see the problem?

Problem solved!
The button must be of type "submit" instead of "button"! So the correct code is:

$form['auctionpersons']['add_person_btn'] = array(
  '#type' => 'submit',
  '#value' => 'Add person',
  '#description' => 'Click button to add person',
  '#ajax' => array(
      'callback' => 'add_auction_person_ajax_callback',
      'effect' => 'fade',
  ),
);

Thx for viewing this question :-)


Change aspect of node add form (not only via css) I need to recreate graphically the "node add form" (my client has passed me via PSD the final version of the node add's form design). Is there a way to manipulate the node add form design that is not the usual change using CSS?

Ok I think that I have found the solution:

Theming Node Forms in Drupal 7 --  http://drupal.org/node/1092122

M.


How do I configure the Block Access module? I want to use the Block Access module, but I don't know how to configure the module. I tried to find some tutorials or user manuals but I couldn't. I installed and enabled the module end I can change the permissions in the /admin/people/permissions page. I want to allow permission to a specific user role to  Edit own block content.

How can I give the block ownership to a specific user role?

This module is an administrative level module. You can use it to configure who can create/administer/view/etc blocks. For instance, what I did to realize what the module does, logged in as admin:

Install and enable the module Block Access
Create a new role, lets say testadmin, and grant to it every permission
Create a new user, lets say testuser, with that role
Log in with user testuser and create a dummy block
Log in again as admin
Edit the permissions of the role testadmin and deselect the permissions "Administer block access settings" and "Create blocks", under the section "Block Access" (these permissions are added by the Block Access module)
Log in again as testuser and try to create another dummy block
End of the exercise, because now the user testuser can't create blocks...

In this exercise I only used two permissions, but the module Block Access implements a lot more!


Allowed memory size exhausted after importing PO file I have a problem after importing the PO of the Drupal core 7.28 (I tried with French and Arabic), whenever I try to create a new feature or open the modules page, I will get an error:

  Allowed memory size of 268435456 bytes exhausted (tried to allocate
  5126472 bytes) in .../includes/form.inc on line 3906

After the import, it is consuming a lot of memory and time I tried debugging, this is the path I could trace:

menu_execute_active_handler -> drupal_get_form -> drupal_build_form -> features_export_form -> _features_export_form_components -> _features_export_build

This is as far as I could get while debugging. The last function _features_export_build takes a lot of time but I couldn’t know what is wrong inside.

Generating/exporting Feature modules takes a lot of memory, depending on amount of components which you're trying to export. The Features module is constantly improving, so please check the recent stable version if that makes the difference.

Otherwise you've to increase your PHP memory limit either in your php.ini or before the import, temporary add this line into your settings.php file:

ini_set('memory_limit','1G');

If you would like to debug what takes so much memory, then you need to use PHP profiler such as XDebug (xdebug.profiler_enable=1) or use XHProf.


How can I get Beautytips Module to work with Views field output? I have uploaded the module Beautytips, and enabled it as usual. I have a content type called Solicitation. From among many fields I have the two main fields (Title and Remarks). I listened to a tutorial video, but it seems it takes one too far than my simple needs. I have a view in which I made the Remarks field to be excluded from view and I followed that field with the title and and I set  option ( Output this field as a link) and I filled the the (Alt text:) with [field_remarks_value] . I have a block view. When I hover on the title I get only ordinary tooltip, while in the setup I selected the Transparent style. I guess I am missing something that I must fill like a selector that I must fill somewhere. Can someone with expertise in this help me. I would be much appreciating.

You can do this with the BeautyTips module but its not the default behaviour as it does not have Views integration built-in. Fortunately, your BeautyTips use case is rather simple so the approach outlined here will work for you. Specifically, you want to edit your 'Title' field to rewrite it to add a custom trigger class like this:

[title]

and then add this to the header of the view:

<?php
drupal_add_js (
  '$(document).ready(function()
  {
    $(".btytp").bt();
  }); ',
    'inline');
?>

However, by doing this you're effectively bypassing the BeautyTips module altogether and won't be using the built-in styles the module provides. Fortunately, this is easy to fix. If you look in the modules file, you'll see all of the styles defined as Arrays that are then converted into a javascript array and used to instantiate the beautytips instance. So for example, if I were using the Hulu style, I would find this array:

  $styles['hulu'] = array(
    'fill' => '#F4F4F4',
    'strokeStyle' => '#666666',
    'spikeLength' => 20,
    'spikeGirth' => 10,
    'width' => 350,
    'overlap' => 0,
    'centerPointY' => 1,
    'cornerRadius' => 0,
    'cssStyles' => array(
      'fontFamily' => '"Lucida Grande",Helvetica,Arial,Verdana,sans-serif',
      'fontSize' => '12px',
      'padding' => '10px 14px'
    ),
    'shadow' => TRUE,
    'shadowColor' => 'rgba(0,0,0,.5)',
    'shadowBlur' => 8,
    'shadowOffsetX' => 4,
    'shadowOffsetY' => 4,
  );

All of the values here are what you need to pass to javascript when you invoke it on your own. So, to do this using the code we already have with the Hulu style, that would look like:

<?php
drupal_add_js (
  '$(document).ready(function()
  {
    $(".btytp").bt({
        fill: '#F4F4F4',
        strokeStyle: '#666',
        spikeLength: '20',
        spikeGirth: '10',
        width: 350,
        cornerRadius: 0,
        cornerPointY: 1,
        strokeWidth: 0,
        cssStyles: {
                fontFamily: '"Lucida Grande",Helvetica,Arial,Verdana,sans-serif',
                fontSize: '12px',
                padding: '10px 14px'
        },
        shadow: true,
        shadowColor: 'rgba(0,0,0,.5)',
        shadowBlur: 8,
        shadowOffsetX: 4,
        shadowOffsetY: 4,
        shadowBlur: 8,
    });
  }); ',
    'inline');
?>


How to create a new table in drupal without uninstall/installing the custom module In my requirement i want to create new table without uninstalling and installing the module.. is there any way to do it...?

The proper way to do this is to simply implement hook_update_N() and manually add the table that you've added to hook_schema():

/**
 * Add the foo table.
 */
function MYMODULE_update_7100() {
  $table_name = 'table_name';
  $schema = drupal_get_schema_unprocessed('MYMODULE', $table_name);
  db_create_table($table_name, $schema);

  return $table_name . ' table created.';
}

That goes in your module's .install file along with the schema hook, and you'll need to run drush updb (or run through the UI at /update.php) for the changes to take effect.


How to redirect particular page after login via social networking site? In my Drupal site I have placed a link in checkout page which takes to user/login. On successful login it redirects back to checkout page. For this I have used ?destination=checkout in the url. I have achieved using form alter

function module_form_commerce_checkout_form_checkout_alter(&$form, &$form_state, $form_id) {
  $form['checkout_message']['#markup'] = t('Click to login');
}

This redirects to login page and then redirects back to checkout page, till now it works fine. I have social site login in my login page (for eg., facebook, twitter, google).

How can I redirect the user to checkout if he/she login via social sites? FYI: Above is not working for social network login.

These are the modules used for performing a social login:

Facebook: Facebook OAuth.
Twitter, Google+: HybridAuth Social Login.

You can use user_login_destination() for your requirement which third-party authentication modules may use to determine the proper destination after a user has been properly logged in.

function user_login_destination() {
  $destination = drupal_get_destination();
  if ($destination['destination'] == 'user/login') {
    $destination['destination'] = 'user';
  }
  return $destination;
}

You just need to change line 4 to:

$destination['destination'] = '<path you want to go to after login>';


Setting OG with Services module I am trying to POST a node to my site and make it group member.

POST body looks like this:

{
   "title":"Update",
   "type":"mesurement",
   "uid":"4",
    "og_group_ref": {
        "und": [{
            "target_id": "20"
        }]
    },
    "field_records": {
        "und": [{
            "value": "22"
        }, {
            "value": "25"
        }, {
            "value": "65"
        }, {
            "value": "12"
        }]
    }
}

Yet every time I get an error saying:

{
    "form_errors": {
        "og": "You must select one or more groups for this content."
    }
}

Edit:

Field settings are:

Default widget type: Select list

Administrator widget type: Autocomplete

Number of values: 1

Mode: Organic groups

I was having the same troubles. Seems to me as far as my limited debugging skills go, that when drupal_process_form calls

$form = form_builder($form_id, $form, $form_state);

the values for $form_state[‘input’][‘og_group_ref’] don’t get passed through into $form. So I suspect I need to understand form_builder better to figure out why the values coming in aren’t getting transferred through. Ultimately when we get to og_form_group_reference_validate, $form_state['values’][‘og_group_ref’] doesn’t exist.

So, what I’m going to try for now (and seems to be working) is let og_form_group_reference_validate look in $form_state[‘input’] in addition to $form_state[‘values’], as og_group_ref still exists there.

Here’s a gist of my patch:

https://gist.github.com/housser/ba03c50f670dc5310520


How do I create a unified list of referenced users in a multi-entry entity-reference field in a multi-entry field collection field? My set up is similar to the setup in this question:
How to integrate Field collection module in Views?
I have a content type with a field collection field (hereafter itineraries) that accepts unlimited entries.  In the field collection is a (user) entity reference field (hereafter travelers) that accepts unlimited values.  It also has another (user) entity reference field (hereafter approvers) separate from the field collection.
I've created a user view, with a contextual filter to select the current logged in user.  This view has a relationship to bring in the nodes that reference the current user via the approvers field.  I have another relationship pulling in the itineraries attached to the node.
What I would like to do is make a field in my view that has a comma separated list of travelers on the node.  I can get the travelers from a single itinerary into a field, but nodes with multiple itineraries result in multiple rows.
I guess the solution must be to somehow embed a view to feed this view, but I'm not sure how to approach that, perhaps that would require an additional module?
Update:  At @no-sssweat's recommendation I tried out the Views Field View module.
I tried a content view, passing the nid and using a relationship to get the field collection items.
With that I was able to get something like this for a node with the two itineraries, the first with two travelers and the second with one:

Travelers:
Person One, Person Two
Person Three

I also tried a field collection item view, with the intention of passing in the field collection item ids as contextual filters.  Testing this in the view itself, I got one traveler per row, but in practice I couldn't figure out a good way to pass id1,id2,id3 to the view. The view with ids input manually looks like this:

Travelers:
Person One
Person Two
Person Three

So in both cases I would get all the travelers listed in one field as the result of the embedded view, but they are listed each in their own divs within the field. I'm trying to figure out how I can get them listed as a comma separated list of values. I want to get to a field that looks like this:

Travelers:
Person One, Person Two, Person Three

Can you help me get over that last hump?

I guess the solution must be to somehow embed a view to feed this
  view, but I'm not sure how to approach that, perhaps that would
  require an additional module?

You're on the right track, use the Views Field View module to achieve that.

You could also do this programmatically if you have a template file or a preprocess function

Ex:

<?php print views_embed_view('blog_posts','block_1', $contextual_filter_value); ?>

To make it as a list, use CSS:

.view-id-test.view-display-id-block .views-row {
  display: inline-block; /* If it doesn't work try display: inline; */
}

.view-id-test.view-display-id-block .views-row .field-content::after {
    content: ",";
}

.view-id-test.view-display-id-block .views-row-last .field-content::after {
    content: "";  /* or content: normal; */
}

.view-id-test.view-display-id-block being the unique parent classes wrapper as you don't to affect every single view and only a specific view & view display. (Use inspect element with your browser, to find a good parent wrapper.)

If you don't want to use CSS, then you will have to do it programmatically in your view's fields template file.

// load view
$view = views_get_view('view_name');
// set arguments for view
$view->set_arguments($contextual_filter_value);
// execute view
$view->execute();
// get all travelers from the result
foreach ($view->result as $result) {
   // capture the result of your field in an array.
   $travelers[] = $result->field_traveler;
}
//make array into comma list
$travelers_list = array(implode(", ", $travelers));
// print the list
print $travelers_list;


Pager not displaying I am having problems getting a pager to display after a table in the block_view hook of a module

The code for the query is the following one.

$query = db_select('registry', 'r');
$query = $query->extend('PagerDefault')->extend('TableSort');

$query->limit(10)
    ->fields('r', array('name', 'type', 'filename','module','weight'));
$result = $query->execute();

I build and the table with no problem adding it to the content

Then I add the pager or rather I don't with the following code

$block['content'] .= theme('pager').'
mmm
';

the mmm bit was just there as a quick check to see what was happening.

I know that the extend needs to be assigned to a new variable and I believe that I am doing this.

Is there anything wrong I am doing?

This is the complete code of the module.

/**
 * @file
 * A block module that displays registry info.
 */

/**
 * Implements hook_help.
 *
 * Displays help and module information.
 *
 * @param path
 *   Which path of the site we're using to display help
 * @param arg
 *   Array that holds the current path as returned from arg() function
 */
function current_posts_help($path, $arg) {
  switch ($path) {
    case "admin/help#current_posts":
    return '
' . t("Displays registry info for testing tables and pager") . '
';
    break;
  }
}

/**
 * Implements hook_block_info().
 */
function current_posts_block_info() {
  $blocks['current_posts'] = array(
    'info' => t('Current posts'), //The name that will appear in the block list.
    'cache' => DRUPAL_CACHE_PER_ROLE, //Default
  );
  return $blocks;
}

function current_posts_block_view($delta = '') {
  switch($delta) {
    case 'current_posts':
      $block['subject'] = t('Modules list');
      if(user_access('access content')) {
        $query = db_select('registry', 'r');
        $query = $query->extend('PagerDefault');
        //$result = $query->limit(50)
        $query->limit(10)
          ->fields('r', array('name', 'type', 'filename','module','weight'));
        $result = $query->execute();

        // Array to contain items for the block to render.

        $rows = array();

        // Iterate over the resultset.
        foreach ($result as $node) {
          $rows[] = array(
            'name' => t($node->name),
            'type' => t($node->type),
            'filename' => t($node->filename),
            'module' => t($node->filename),
          );
        }

        // Table header.
        $header = array(
          'name' => t('Name'),
          'type'     => t('Type'),
          'filename'    => t('Filename'),
          'module'    => t('Module'),
        );

        $block['content'] = theme('table', array(
          'header'  => $header,
          'rows'    => $rows,
          'id'      => 'table-articles',
          'class'   => 'articles',)
        );

        $block['content'] .= theme('pager').'
mmm
';
      }

      return $block;
  }
}

/**
 * Implements hook_menu().
 */
function current_posts_menu() {
  $items = array();

  $items['admin/config/content/current_posts'] = array(
    'title' => 'Current Registry',
    'description' => 'Configuration for Current posts module',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('current_posts_form'),
    'access arguments' => array('access administration pages'),
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}

/**
 * Page callback: Current posts settings
 *
 * @see current_posts_menu()
 */
function current_posts_form($form, &$form_state) {
  $form['current_posts_max'] = array(
    '#type' => 'textfield',
    '#title' => t('Maximum number of posts'),
    '#default_value' => variable_get('current_posts_max', 3),
    '#size' => 2,
    '#maxlength' => 2,
    '#description' => t('The maximum number of links to display in the block.'),
    '#required' => TRUE,
  );

  return system_settings_form($form);
}

I think I know what is going on. I've had this problem several times before.

The issue is that on some pages, multiple pagers may be in use. Which would explain why theme('pager'); wouldn't work.

I just had the same problem, and I got it working by doing this:

theme('pager', array('element' => 1));

On my end, I wasn't displaying multiple pagers, but I think something else on the page must have been doing this, because the above code made it work! I hope this helps anyone else who encounters the same problem.


Add metatags import to migration I have made a migration module to import the full content from a legacy Drupal 6 site to my new Drupal 7 site, using the migrate d2d module. Everything works fine, but I have just discovered that there are many custom meta tags added manually for both nodes and taxonomy in the legacy site (using the Metatags module). The taxonomy meta tags I can deal with manually, but I really would need to figure out how to add the mapping for metatags in my node migration classes. Do I add code in my general migration class in node.inc (that extends DrupalNode6Migration)?

Do I use prepareRow() to fetch info from the database and add this to a mapping with a default value in the new site? As far as I can see there are no fields in the legacy site that holds the metatags (I need title, keywords and description).

If anyone knows how to do this, please help.

Finally I came up with a solution and I post it here in case anyone else has the same problem. There are two tables in the legacy site named metatags and  metapages, in which you can find everything needed for importing the metatags.

So in my prepareRow() in each node migration class I added these rows, and now the metatags from the legacy Drual 6 site has been imported to my Drupal 7 site :-)

$metapages_path = !empty($row->nid) ? 'node/'.$row->nid : false;
if($metapages_path){
    $meta_title_pid = Database::getConnection($target='default', $key='legacy')->query('SELECT f.title, f.pid FROM {metapages} f WHERE f.path = :path',array(':path' => $metapages_path))->fetchAssoc();
}
$meta_title = !empty($meta_title_pid['title']) ? $meta_title_pid['title'] . ' | [site:name]' : '';
$this->addFieldMapping('metatag_title')->defaultValue($meta_title);
$meta_pid = !empty($meta_title_pid['pid']) ? $meta_title_pid['pid'] : false;
if($meta_pid){
    $meta_keywords = Database::getConnection($target='default', $key='legacy')->query('SELECT f.value FROM {metatags} f WHERE f.name = :key AND f.parent_pid = :pid',array(':pid' => $meta_pid, 'key' => 'keywords'))->fetchAssoc();
    $meta_description = Database::getConnection($target='default', $key='legacy')->query('SELECT f.value FROM {metatags} f WHERE f.name = :key AND f.parent_pid = :pid',array(':pid' => $meta_pid, 'key' => 'description'))->fetchAssoc();
}
$keywords = !empty($meta_keywords['value']) ? $meta_keywords['value'] : '';
$this->addFieldMapping('metatag_keywords')->defaultValue($keywords);
$description = !empty($meta_description['value']) ? $meta_description['value'] : '';
$this->addFieldMapping('metatag_description')->defaultValue($description);


How can I affect a custom block to a custom page/view in Drupal 8? I know I can choose the page were the block Will be displayed but for a big website I Will have hundred block on same région on same admin menu, it Will be hard to handle this. Is there a way to separate the custom block or create a new space for région, because if I place a custom block in a region, this custom block Will be automatically display on all page , ans I dont want that.

Thanks.

( for drupal 8 )

Of course that you can restrict on which pages you want to show block. When you edit block you can select specific pages where block will show up.
But if you want more control you should consider to use Panels module. I recommend you to check that module and see if that will help you.


Remove image banner on individual pages? I have zero experience with Drupal or any other similar systems. I have simply been given access to a Drupal website (that was created by an external company) at work and told to make changes. I have managed to somewhat figure out a few general basic things but having many problems that are making me lose my mind.

My current problem is this: there are a bunch of basic pages with the usual stuff, a side menu, content area, etc. They also have a banner image along the top (created as a field in the content type "basic page"). I need to remove the banner image from just one page. Simple. Or so I thought. I can't seem to figure this out. I tried making the banner image field not required and leaving it empty, but an image still appears.

Any sugestions?

PS. I'm not sure but I think it's Drupal 7 (that's right, I don't even know how to check that).

On the body element there are page classes for each "node", and in Drupal every node has a number, called the "nid" or "node id".

The services page nid is 65.

Look at the body element in your browsers inspector (right click, "Inspect"), you'll see something like this for the body:

<body class="html not-front not-logged-in one-sidebar sidebar-first page-node page-node- page-node-65 node-type-page i18n-en-gb blue">

For every node in the site there is always going to be the page-node-[node-id] class, e.g. page-node-65

By "banner" I assume you mean the photo of the oil rig? If so you can use the body class and the wrapper on that image:

.page-node-65 .cover {
  display: none;
}

But - consider this a stop gap solution, you need to figure out how the site is structured/built and try to remove the picture/banner from being there in the first place.


User registration and login problem When I visit the registration page, or the login page, it says that I do not have access to that page. Do you have any idea why this happens?

You're probably logged in to the site.

The user login and registration pages are not available for authenticated users, as it doesn't really make sense for a logged in user to login again or register.


How do I sort a view based on when a specific field was last updated? I have a field(field_video) for Embedded Videos. I have a view that shows a list of all Videos and I want to be able to sort that view by when the video was last accessed(Recently Viewed), when the video was added(New Videos), and total number of views(Popular). Is it possible to sort a view based on attributes of the field? I have a quicktab that would then show a block of each view by each specific sort criteria.

Such attributes are not available on fields, but they are available for nodes, and it sounds like that's all you need.

Views already provides a Sort Criteria for "Content: Updated date."

To sort by node statistics, make sure that the Statistics module is enabled (it's part of Core). That will provide additional Sort Criteria in Views. Add a Sort Criteria and filter by "Content statistics" to see three new options.

If you really need to use similar attributes on fields, you can use Rules to update extra fields based on whichever events you desire, and filter Views with those values.


Add class to Bootstrap login form button I want to add a class to a button in my login form. I have searched through all the template files and I cannot find where to do this. I found the following code that best matches the form in modules/user/user.module

function user_login_block($form) {
$form['#action'] = url(current_path(), array('query' => drupal_get_destination(), 'external' => FALSE));
$form['#id'] = 'user-login-form';
$form['#validate'] = user_login_default_validators();
$form['#submit'][] = 'user_login_submit';

The HTML for the button is below. My aim is to change btn-default to btn-primary

<button class="btn btn-default form-submit" id="edit-submit" name="op" value="Log in" type="submit">Log in</button>

Please help!

Checkout hook_form_alter. You can add and change (I would suggest only adding unless you are sure it will only affect the forms you want it to) classes with #attributes


Change region/block content based on current node I am trying to figure out how to change the content of a region/block depending on the node being viewed.

Lets say I was creating a website for a grocery store. The home page will have several links for the various departments ... Meat, Seafood, Dairy, etc. When the user clicks on one of these departments they will go to a node where there is a menu that lists all the items in that department ...

Meat => Steak, Hamburger, etc.
Dairy => Milk, Eggs, Cheese, etc.
Seafood => Shrimp, Tuna, Salmon, etc.

What I am trying to figure out is how to display the correct item menu for the selected department. How to I display the menu of all the dairy products when the user selected the "Dairy" node?

Ideally I would like to accomplish this without hard coding changes into the template as I would like the site owner to be able change things themselves.

Thanks for any suggestions!

Try the context module.

  Context allows you to manage contextual conditions and reactions for
  different portions of your site. You can think of each context as
  representing a "section" of your site. For each context, you can
  choose the conditions that trigger this context to be active and
  choose different aspects of Drupal that should react to this active
  context.

  Think of conditions as a set of rules that are checked during page
  load to see what context is active. Any reactions that are associated
  with active contexts are then fired.

Refer the module page for documentation links.


How to create a theme function for overriding Address Field theming? How do you create a theme function for overriding the formatting of an Address Field in Drupal 7? I didn't want to create a CTools plugin or work with render arrays.

Download & enable the Addressfield Tokens module (https://www.drupal.org/project/addressfield_tokens). This will provide additional tokens and theme functions for Addressfield.
Set the field in question to display using the "Address components" format.
Select all the fields you wish to display. Note that the separator does not matter, unless you choose to use it in your theme function.
Create a theme function named THEMENAME_addressfield_formatter__components, where THEMENAME is the name of your theme. Here is an example I created in my template.php to add microdata for XHTML+RDFa: https://gist.github.com/evandonovan/d47a3874e26151c4c07f6c20b7edc204. It is designed especially with the United States in mind, so may not work as well on other countries.
Clear the theme registry for your theme function to take effect. If you have Drush, you can use drush cc theme-registry. Otherwise, see https://www.drupal.org/node/173880#theme-registry for other means to clear.


Drupal nested ajax call not working correctly I got this nested ajax call issue,

/**
 * Problems
 * 1). When I click "Add one more" to add more file, I need to click the button
 *     Twice to get one 'Name'/file element available. I click once, no file
 *     field shows. Click again, one file field will show.
 * 2). When one file field shows, as long as I click 'upload' button of the 'managed_file'
 *     field, this file field will disappear immediately. I upload another file, this
 *     file will be fine. Then another uploaded file will disappear.
 * 3). When I click "submit" to submit the form, all previously disappeared file fields
 *     will show. Because, as you see, the submit function only rebuild the form.
 * 4). If container of multiple file fields are not triggered by ajax, i.e,
 *     $form['test']['names_fieldset'] is not triggered by "select" field, then
 *     tihs "Add one more" function works perfectly.
 *
 * So, why this happens with the ajax triggered container:)?
 */
function agl_jira_new_test_form($form, &$form_state) {
  $form['select'] = array(
    '#title' => 'select',
    '#type' => 'select',
    '#options' => drupal_map_assoc(array('man', 'woman')),
    '#required' => TRUE,
    '#default_value' => isset($form_state['values']['select']) ? $form_state['values']['select'] : NULL,
    '#ajax' => array(
      'callback' => 'agl_jira_select_callback',
      'wrapper' => 'names-fieldset-wrapper',
    ),
  );
  $form['test']['names_fieldset'] = array(
    '#markup' => '

',
  );
  if (isset($form_state['values']['select']) && $form_state['values']['select'] == 'man') {
    $form['test']['names_fieldset'] = array(
      '#type' => 'fieldset',
      '#prefix' => '
',
      '#suffix' => '
',
      '#tree' => TRUE,
    );
    $form['test']['names_fieldset']['text'] = array(
      '#title' => t('name'),
      '#type' => 'textfield',
    );
    $form['test']['names_fieldset']['attachment'] = array(
      '#title' => t('File'),
      '#type' => 'fieldset',
      '#prefix' => '
',
      '#suffix' => '
',
    );
    if (!isset($form_state['num_names'])) {
      $form_state['num_names'] = 1;
    }
    for ($i = 0; $i < $form_state['num_names']; $i++) {
      $form['test']['names_fieldset']['attachment']['name'][$i] = array(
        '#type' => 'managed_file',
        '#title' => t('Name'),
      );
    }
    $form['test']['names_fieldset']['add_name'] = array(
      '#type' => 'submit',
      '#value' => t('Add one more'),
      '#limit_validation_errors' => array(),
      '#submit' => array('agl_jira_example_add_more_add_one'),
      '#ajax' => array(
        'callback' => 'agl_jira_example_add_more_callback',
        'wrapper' => 'agl-jira-file-attach-wrapper',
      ),
    );
  }
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'submit',
  );
  return $form;
}

function agl_jira_select_callback($form, $form_state) {
  return $form['test']['names_fieldset'];
}

function agl_jira_new_test_form_submit($form, &$form_state) {
  //dsm('form has been submitted!');
  // do something.
  $form_state['rebuild'] = TRUE;
}

function agl_jira_example_add_more_add_one($form, &$form_state) {
 // dsm('submitted');
  $form_state['num_names']++;
  $form_state['rebuild'] = TRUE;
}

function agl_jira_example_add_more_callback($form, $form_state) {
  return $form['test']['names_fieldset']['attachment'];
}

Any help will be appreciated.

Correct one, just copy and paste it:

function agl_jira_new_test_form($form, &$form_state) {
  $form['#tree'] = TRUE;
  $form['select'] = array(
    '#title' => 'select',
    '#type' => 'select',
    '#options' => drupal_map_assoc(array('man', 'woman')),
    '#required' => TRUE,
    '#default_value' => isset($form_state['values']['select']) ? $form_state['values']['select'] : 'man',
    '#ajax' => array(
      'callback' => 'agl_jira_select_callback',
      'wrapper' => 'names-fieldset-wrapper',
    ),
  );
  $form['test']['names_fieldset'] = array(
    '#type' => 'fieldset',
    '#prefix' => '
',
    '#suffix' => '
',
    '#tree' => TRUE,
  );
  if (isset($form_state['values']['select']) && $form_state['values']['select'] == 'man') {
    $form['test']['names_fieldset']['text'] = array(
      '#title' => t('name'),
      '#type' => 'textfield',
    );
    $form['test']['names_fieldset']['attachment'] = array(
      '#title' => t('File'),
      '#type' => 'fieldset',
      '#prefix' => '
',
      '#suffix' => '
',
      '#tree' => TRUE,
    );
    if (!isset($form_state['num_names'])) {
      $form_state['num_names'] = 1;
    }
    for ($i = 0; $i < $form_state['num_names']; $i++) {
      $form['test']['names_fieldset']['attachment'][$i] = array(
        '#type' => 'managed_file',
        '#title' => t('Name'),
      );
    }
    $form['test']['names_fieldset']['add_name'] = array(
      '#type' => 'submit',
      '#value' => t('Add one more'),
      '#submit' => array('agl_jira_example_add_more_add_one'),
      '#ajax' => array(
        'callback' => 'agl_jira_example_add_more_callback',
        'wrapper' => 'agl-jira-file-attach-wrapper',
      ),
    );
  }
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'submit',
  );
  return $form;
}

function agl_jira_select_callback($form, &$form_state) {
  $form_state['rebuild'] = TRUE;
  return $form['test']['names_fieldset'];
}

function agl_jira_example_add_more_callback($form, &$form_state) {
  return $form['test']['names_fieldset']['attachment'];
}

function agl_jira_example_add_more_add_one($form, &$form_state) {
  $form_state['num_names']++;
  $form_state['rebuild'] = TRUE;
}

function agl_jira_new_test_form_submit($form, &$form_state) {
  $form_state['rebuild'] = TRUE;
}

removed $form['test']['names_fieldset'] = array(
    '#markup' => '

',
  );, added reference to the form_state in agl_jira_example_add_more_callback..


Cron is not working - leading to user/0/edit instead When I was trying to migrate my site and export the database I realised that the cache_form field is enormous. According to suggestions I have found online the proper way to solve this is to run cron. So I try to run cron by going to the admin/config/system/cron page, and in there it said that cron was last run 3 weeks ago.

When I press run cron or when I visit the link with the cron key provided in that admin/config/system/cron page, they have both led me to user/0/edit instead of running cron. I did a quick search among the files I have made changes to in the site directory in these three weeks and none of them are leading to user/uid/edit. I wonder what else can I do to solve this properly?

Thanks!

I think your not logged in, that's why going to  " user/0/edit " path because you have not permission to run cron.
Please check it.


Mailing content to a list/group of email addresses What kind of module should I use to send content to a list of emails?

I need to create a groups with list of emails.
I need to send it to one or a few of these groups.
I need for admins to be able to look at the email addresses which will receive the emails.

I am thinking about using mailchimp, but it does not fulfill all of my needs. Also simplenews_roles can be a good decision, but whre is no version on drupal-7. Is there another option available?

You can use the new Newsletter module for D7.

Features

  Multiple newsletters lists configurable on terms, not vocabularies
      Plain text or HTML out of the box
      Multiple schedules Each newsletter can have more than one schedule, e.g. Daily, Monthly, Weekly, manually or even custom, eg
  after 10 new posts for this term.
      Centralized administration and configuration on single page.
      Users can customize the terms in the list they subscribe to
      Custom template per list
      Statistics (CTR and Open-Rate)
      Drupal 7 only


Ajax progress bar using example module I am new to drupal, currently learning about example module and its sub module, I already created the form using custom modules, in that form I wish to add progress bar for submit button, i referred many sites but, i can't get any clear idea, what i did for submit button is,

function custom_form_menu() {
$items = array();
$items['think/form'] = array(
'title' => t('Entry Free'),
'page callback' => 'custom_form_form',
'page arguments' => array('ajax_example_progressbar_form'),
'access arguments' => array('access content'),
'description' => t('My form'),
'type' => MENU_CALLBACK,
'file' => 'ajax_example_progressbar.inc',
);
return $items;
}

and for submit button,

custom_form_my_form($form , &$form_state) {
$form['first'] = array(
'#type' => 'textfield',
'#title' => t('First name'),
'#description' => "Please enter your first name.",
'#maxlength' => 6,
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => 'Submit',
);
return $form;
}

So, now how can I add progress bar in this submit button, when the form is submitted.

Progress bar example:

$form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Import'),
    '#ajax' => array(
        'callback' => 'import_submit_callback',
        'wrapper' => 'import-form',
        'progress' => array(
            'type' => 'bar',
            'message' => t('Importing..'),
            'url' => 'import/progress', //url to fetch current progress percentage
            'interval' => '1000' //progress bar will refresh in 1 second
        )
    ),
);

Then create menu like this for url 'import/progress' :

$items['import/progress'] = array(
    'title' => t('Import progress'),
    'page callback' => 'import_progress',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
);

Then output json data indicating current status like this in that page callback function:

function import_progress() {
    $progress = array(
        'message' => t('Starting import...'),
        'percentage' => -1,
    );

    $completed_percentage = variable_get('import_status'); // calculate progress percentage here

    if($completed_percentage){
        $progress['message'] = t('Importing...');
        $progress['percentage'] = $completed_percentage ;
    }

    drupal_json_output($progress);
}

Further reading: https://www.drupal.org/node/1401966


Why so many "page not found" for statistics.php? In my Drupal sites, there are many "page not found" for modules/statistics/statistics.php recorded in the log ("Recent log messages" or /admin/reports/dblog).
Many of them were accessed by the admininistrator in the record.
The file exists, of course.

That seems strange to me.  Why is it so?

Note the core statistics module (Ver.7.32) is enabled, and all the three options (access log, Count content views, Use Ajax to increment the counter) in its configuration are enabled.

[Description added]
In the Report page /admin/reports/dblog when I click the links modules/statistics/statistics.php in the Message part, I see (for TYPE: page not found) the LOCATION of http://MyHost/en/modules/statistics/statistics.php or alike, that is, path with the language prefix.  My websites use the path-prefix-based i18n feature.

If file exists, but Drupal still captures calls to it, it may mean one of few things:

Obviously this happens if filename is misspelled in one place (request or filesystem) but not the other (or misspelled differently in both).
As above, sometimes this happens when paths are (slightly) different.
Path you see in your address bar and path your server use to test for file existence are not the same thing. May look the same, but may not, depends on your .htaccess, nginx.conf or whatever you use to control that.
Language prefixes may break things. If file /sites/default/files/example.jpg exists, server may fail to find en/sites/default/files/example.jpg. If that's the case, and for any reason you can't fix broken code, you can try setup like this in your htaccess:

RewriteCond %{REQUEST_FILENAME} ^(en|de|fr)/(.*)$ [NC]
RewriteCond %2 -f
RewriteRule ^(en|de|fr)/(.*)$ $2 [NC,QSA,L]

Notice, I didn't test it. OP preferred to use %{DOCUMENT_ROOT}%{REQUEST_URI} instead of %{REQUEST_FILENAME} to deal with the potential dependencies on the environment/timing etc - that are implementation details beyond the scope of this site, I believe. The logic behind it is, line by line:

Test if request filename contains one of the specified prefixes (should match your site's languages.
Test if file without prefix (second regex group) is there, and really is a file.
If so, rewrite request to remove language prefix.

Apply this logic and you should be good. Actual implementation may vary, but logic you want is just that.