updatedhow to set default value in a form field got from another page(form)? All,

What I want to do:
On the Home page, I have an input field in which a user can insert their invite code, the invite code gets validated via ajax and if correct, popups the registration form. Its important that the user cannot get access to the registration form without the correct invite code. How can I bullet proof this concept into my Drupal7 install? I am using Regcode module for registration purpose.

The problem I have is that if the user knows the address to the registration form, they can merely enter that into the browser's address bar and register without having to gain an invite code.

One solution I thought was that the invite code is needed on the actual registration form as well, so if they do access the form via the browser's address bar, they will still need to input the invite code. However, if they already did place the invite code in the input field (on the Home page), it would automatically populate the invite code field in the registration form.

What problem I am facing:
Im not sure how to go about transferring the invite code (which the user inserted) into the registration form that pops up upon validation.
The form(single field) on the front page is written by myself inside a block.

Here i am confused how to take the form value to the registration form and how to get the value of field and after getting how to set the value as default in the regcode text field.

 <form method="GET" action="?????"></form>

the modulea's part which alter the registration form is as follows

 function regcode_form_user_register_form_alter(&$form, &$form_state) {
  $code_optional = variable_get('regcode_optional', FALSE);
  $account = $form['#user'];

  $form['regcode']['regcode_code'] = array(
    '#type' => 'textfield',
    '#title' => variable_get('regcode_field_title', t('Registration Code')),
    '#description' => variable_get('regcode_field_description', t('Please enter your registration code.')),

    '#default_value' => ???????????,

    '#required' => !($code_optional || user_access('administer users')),
    '#element_validate' => array('regcode_code_element_validate'),
  );
  // Capture the code from the url and inject it into the registration form
  if (isset($_GET['regcode'])) {
    $form['regcode']['regcode_code']['#value']       = check_plain($_GET['regcode']);
    $form['regcode']['regcode_code']['#description'] = NULL;
    $form['regcode']['regcode_code']['#disabled']    = TRUE;
  }
}

i Hope, its understandable now

Drupal doesn't store the form state between forms, so you will need to do that yourself.

In this case I would use the session variable since you want to save it per user, but not permanently.

To do this you will need to add a custom submit handler to the form if you form is not created by you, this can be done with hook_form_alter

Then you can save the value you want to save in the session variable something like

 $_SESSION['my_value'] = $value;

should do the trick, then you can set the value in the form, either directly if you control it or via form alter.

That the form value is gotten from or is to be set to a field doesn't change things. The form field structure is a little more verbose, but the way to do it is pretty much the same.


Customizing form for product attributes and features? I'm trying to create a crowdfunding site using Ubercart. However, Ubercart has recently shown a certain lack of flexibility when it comes to how it interacts with my custom content types.

I feel that the content type "research project" should not have an SKU that should be set by the project creator, and there is currently no way to set the project goals if one is merely a user and not an admin, as the project goals and deadlines are features, not attributes.

The problem, for me, is that I cannot figure out how I am to change the way in which attributes and features can be changed by privileged users, and I am not sure how to automatically set an attribute (e.g. programmatically creating IDs to put in the SKU field).

Thanks in advance. :-)

I am not an expert as I am going through a learning curve with Drupal myself, however, I do have database experience and started using Ubercart myself.

As to your question on auto-created SKU, I think as a learner you are complicating things, unless you are looking into a huge and fast growing database for which you want to create auto SKU, which serves for Stock Keeping Unit.  There is a modul Commerce AutoSKU.

As a method to setting up your "research project" implementer 'Role', you can create a form (e.g. Project Form), allowing the enduser to Name (Title) the project, but ID to that project can be in incremental order assigned by the table (project_id, auto_increment).  You can allow access to that specific form to the persons implementing the research projects.

As to making use of Ubercart's default system and its capability to advanced features such as customizing methods, I find there is quite the flexibility as to adjusting your own custom forms and assigning fields with the 'Hook System'.  It is a steep learning curve, I found.

I have been following the following videos.  The presenter is quite fast, but I found his instructions helped me to understand my capability.  It is a youtube video series consisting of 10 videos (15-20 mins long each).

Creating an E-commerce Site Using Ubercart

Sorry that I cannot help you further, but I hope I am able to get you one step closer to your project.


Should a cache tag only render array for an otherwise empty block work? I have a custom blocks that displays results based on an entity query. For some pages the correct result is blank, and I want to hide the block.

When a return an empty array from the block's build() method it appears to cache more or less forever.

If I return a render array that just contains #cache values will that get honored, or will the lack of content invalidate those tags some place another the way?

if (empty($relatedContent)) {
  return [
    '#cache' => [
      'contexts' => ['url'],
      'tags' => ['node_list'],
    ],
  ];
}

For what it's worth, I've been testing the idea and I'm running into issues, but it's not clear yet if that's related to this or some other problem.

You are right about this, you need content (in form of a render element) for the cache metadata to be recognized. But you don't need to worry about this, because BlockViewBuilder detects an empty block and adds a markup render element with an empty string:

public static function preRender($build) {
    ...
    if ($content !== NULL && !Element::isEmpty($content)) {
      ...
    }
    else {
      // Abort rendering: render as the empty string and ensure this block is
      // render cached, so we can avoid the work of having to repeatedly
      // determine whether the block is empty. For instance, modifying or adding
      // entities could cause the block to no longer be empty.
      $build = [
        '#markup' => '',
        '#cache' => $build['#cache'],
      ];
      ...


How to pass values to content creation page to set default values in form elements? Introduction (not necessarily needed to be able to answer the question)
I use Domain Access module to be able to manage different sites from one Drupal installation and a single shared database. I enabled Domain Content submodule that provides a content administration page for each subdomain.
Instead of having all contents of all domains displayed at /admin/content, this allows to display all contents of a given domain at /admin/content/domain-content/mydomain.
What I'd like to do
I'd like to prefill a form element in Create Article page according to a given domain.
So I plan to add a Add content button at /admin/content/domain-content/mydomain, and pass the parameter mydomain from here until, for example, Create Article page.
Then I'll be able to prefill (tick) the right domain checkbox in the Create Article page according the passed argument.
My question
How to pass parameters between the given admin pages to be able to prefill a form in Create Article page?

Altering the form

You should implement the hook_form_FORM_ID_alter. Then, read the parameters like this:

$name = \Drupal::request()->request->get('country'); // from param

Then alter the form elements, rewriting the #defatult_value conditionally, like this:

$form['field_country']'#default_value'] = 'my domain specific default';

In the case of a checkbox widget, the #default_value is an array (source):

$form['countries']['#default_value'] = [1, 3];

Passing parameters in general

If your parameters are simple strings, like country: denmark, you could use GET parameters. This answer has the sample code:

How do I create a link?

Passing parameters through the '/node/add' route

This is a special route, it is not so simple.

Method 1: Implementing a subtheme

If you are using the default admin theme ('seven') you would have to create a subtheme, and overwrite this hook, so that your custom parameters are passed:

   /**
     * Implements hook_preprocess_HOOK() for list of available node type templates.
     */
    function seven_preprocess_node_add_list(&$variables) {
      if (!empty($variables['content'])) {
        /** @var \Drupal\node\NodeTypeInterface $type */
        foreach ($variables['content'] as $type) {
          $variables['types'][$type->id()]['label'] = $type->label();
          $variables['types'][$type->id()]['url'] = \Drupal::url('node.add', ['node_type' => $type->id()]);
        }
      }
    }

Method 2: Overwriting the twig template

The links are ultimately rendered by the  core/themes/seven/templates/node-add-list.html.twig template. To overwrite this output, you would:
 - Implement a hook_theme_suggestions_HOOK
 - Copy the node-add-list.html.twig to node-add-list--custom.html.twig and implement your custom changes here.

/**
 * Implements hook_theme_suggestions_HOOK()
 */
function hook_theme_suggestions_node_add_list(array $variables) {
  $suggestions = array();
  $suggestions[] = 'node_add_list__custom';
  return $suggestions;
}


View published content to anonymous users front page only I have the Content access module installed, but it's not good for sorting this. I just want to make it so deny access is not denied on frontpage.

In permissions I have de-selected view publish content for anonymous users, but how can I make it so they can view the front page?

As long as they don't have permission to view content, and as long as your template file(s) say print render($page['content']) then they should be denied access.

However, you could do something like this:

Make a custom template file called page--front.tpl.php inside your theme's folder
Copy the contents of page.tpl.php to that file
Alter the new page--front.tpl.php file so that it either doesn't render any content anywhere (including the sidebars), or make it so it only renders the content to logged in users.

Example:

<?php if (user_is_anonymous()): ?>
  <?php print t('Hello. This is where you would normally see content.'); ?>
<?php else: ?>
  <?php print render($page['content']); ?>
<?php endif; ?>


Need to give a user "superadmin" status through database There doesn't appear to be a superuser on the users table.
Whenever I try to access permissions directly I get "Access denied", even though my user is listed as and Admin.

How can I promote another user to superuser status through the database?

How can I promote another user to superuser status through the
  database?

There's only one "superuser" or root user in Drupal. That user has uid 1

Perhaps you need to update that user's password.

In D6, using just SQL, you can go

UPDATE users SET pass = MD5('password') WHERE uid = 1;

and then login with that username and password.

Note, make sure that's ok with the current uid 1 user, if it's not you.


Search results are not displaying on top by relevancy I have to use "Search API" module with configured on solr server and indexed.
The search results are displaying but "relevancy" content is not on top of the page.

Example #1:
Search key word: course in the page

Actual Result:
1) Test course
2) Test content in shedule page
3) Test page
4) Course in the page

Expected Result:
1) Course in the page
2) Test course
3) Test content in shedule page
4) Test page

Here I need to display first 4) Course in the page then display others.
I am used views for that search.
 Views Interface
Please post your suggestions!

Sorry I got the answer.
Add the sort criteria relevance.

It's working fine. Cheers!!


Currency conversion for paypal I have integrated paypal payment using the Ubercart 7.x-3.6 module in my website.

My store currency is Rs(INR). Now I have 1500 Rs in a cart When I am proceeding to checkout on paypal its showing 1500 USD.

Isn't it possible that the amount converts in equivalent USD automatically?

If not, then how can I convert it from INR to USD?

Please check this out. It is a workaround for converting the currency on checkout https://www.drupal.org/node/789284


Local or session language variables I'm building a multi-language site using the internationalization set of modules.
The problem is that I've done any queries to extract for example nodes or taxonomy terms with selection of language in the code(back-end) and what language reference or defauld language value I will use to compare or execute queries? Every user that is connected on the site I think they must have each a variable that indicates the language that the user have choosen and if there isn't, uses the browser language.
I've tried with the global variable $language but this is for all the web site and it's user independent.
I hope you understand my question! Thanks..!

You may want to add a filter for Content  Translation: User's Current Language, which is the language that an authenticated user has set in the user settings (it is NOT the same as the current browser language or the site language).

If no option for the 'User's Current Language' is available in the filter criteria form, then verify your configuration at Configuration -> Languages -> detection and selection: the order should be 'URL, Default, User', and not something like 'Default, URL, User' (as mentioned also in https://www.drupal.org/node/1701854#comment-6279474).

Does this help?


7- OG 'og_users_roles' table doesn't seem to update on Group creation I recently noticed that when a user of my site create a new group, the og_users_roles table do not get updated. Witch basicly means that unless the Group creator goes to the "members management" interface to give himself "Group admin", the newly created group do not have an administrator. So og_get_users_by_roles return empty when searching for the "Group admin" rid.

Is this normal? If so how would i go to give a group creator the "Group admin" role by default on group creation ?

I fixed that by hooking on node creation and updating the table myself.
I'll let the thread open in case anyone have a better solution.


How to make full width image slideshows I am using bootstrap sub-theme as default theme.  I created a views slideshow block. In the tpl file, I added this:

<div class="test-region">
 <?php print render($page['test']); ?>
</div>

I placed the slideshow block into the above region.I can see my slideshow on my site. I added the below css to make the image slideshows 100% full width but it is not working. When I refresh my page, I can see the image slideshows in full width for 1 sec but then images go back to original sizes.

.views-slideshow-cycle-main-frame-row-item .field-content img {
    min-height: 500px;
    width: 100%;
}

Do you know why images show in full width for a sec then go back to original sizes?

I can see the image slideshows in full width for 1 sec but then images
  go back to original sizes.

sounds like there is another css that is loaded after that is causing them to shrink. (perhaps it's in the views slide show css file). To prevent anything that is loaded after from overriding your css try adding the !important tag

so try this:

.views-slideshow-cycle-main-frame-row-item .field-content img {
    min-height: 500px !important;
    width: 100% !important;
}


Add Open Graph Metatag in backend I need to set the og:iamge metatag using the Metatag Module.
Since there is no option for editing the names of the metatags or adding custom ones, I'm unsure if this is possible.

Is it possible to do this not programatically/from the backend?

Provided you installed the Metatag and Metatag Open Graph extensions, you need to:

Go to the metatag configuration page (/admin/config/search/metatag).
Edit the desired config
Under the Open Graph tab, fill the Image field with the relative path to your image

Save your config.
When expanding the config you modified, you can see the list of metatags you set (on my example I edited the Global configuration). You can see that og_image is in it.


How to add security questions in Drupal 8? I need to add security questions while user creating his account in Drupal 8. I need to use those security questions to retrieve his password, when user forgets his password.

Any suggestions ?

Well at this time you have 2 modules but only for Drupal 7:

Security Questions

  Security Questions provides administrator configurable challenge
  questions for use during the log in and password reset processes.
  Think of it like most bank website logins.

Password reset

  The password_reset module allows for passwords to be reset without
  involving e-mail addresses through the use of security questions.

There is not a 8.x branch at this time, so your best option is study the code and migrate one of them.


What is the proper way to handle drupal_get_destination and drupal_goto? I am considering the following approach in my controller (the method which corresponds to a given route).

$destination = \Drupal::destination()->getAsArray();
if (isset($destination['destination'])) {
  return new RedirectResponse(Url::fromUri($destination['destination']));
}
else {
  return $this->redirect('acquia_connector.settings');
}

Should I use different code to handle both route based and URL based redirects?

Drupal automatically uses destination, you don't have to do anything. If a destination argument is given, it will override default. So you can simplify your code to a simple, hardcoded $this->redirect(...).

The only exception is when you have links that you want to respect destination too (e.g. a cancel link on a confirm form), then you have to do it yourself. But the default confirm form already does that too AFAIK.


How do i add Meta Tags on panels page? I want to generate meta tags on panels node pages. I am adding Meta tags using nodewords module, it works fine on other node pages except panels generated layout.

Any workaround for this?

There are set of other modules which helps you create meta tags

Page Title
Meta Tag
Meta Tags Quick

Note: Meta Tag Module supports panels too!!!


Add text above the registration form on user/register page Is there a way to add a message above the Registration Form?

I know you can edit the field by going to "Configuration/People/Account Setting/Manage Field", but how about a message above the form?

Thanks

The simplest way would probably be to create a block that is only displayed for that page, and position it above the content.


Ckeditor - Not displaying text on edit node option I've been using Ckeditor for a while to add text to created nodes.

But when editing the same nodes as an authenticated user, Ckeditor doesn't show the text in the body.

It still works for the administration role.

You have to give the Authenticated user role the rights to use the input format CKEditor used to save the page. Look on the access rights page, URL depending on  Drupal version.


How to tell if a Webform field has been hidden by conditional rule I maintain a contrib module that implements hook_webform_submission_presave. It does some complex stuff which boils down to taking the submitted values and storing them in another database.

Here's the problem: if the field was hidden we want to treat it differently. As of Webform 4, conditional fields are built-in to the core webform module. But looking at the submission object, I can't tell the difference between a field that is blank because it was intentionally left blank by the user vs a field that is blank because it was hidden by a conditional rule. In the latter case, we don't want to overwrite an existing value in the other database, because the user wasn't telling us "I want this field to be blank" they were in fact telling us nothing about the field because they didn't even see it.

For more information about the scenario see the original issue.

Assuming you know the numeric id of your field (for example let's say it is 5)

If $submission->data[5] is an array,
then the field was submitted. The array may contain an empty string, which means the field was left blank.

If $submission->data[5] === NULL
then the field was not submitted because it was hidden by a conditional rule, or was excluded from the form for another reason (e.g. the user did not have permission to see it).


How to add content inbetween node fields on node creation? I have a node called survey. Inbetween fields I want arbitrary text. The text is not associated with a field. I tried adding a "group", but could not find a way to add html. Then I looked at adding some kind of plain text field, but also no luck.

I'm sure I've done this using groups in the past, but I just can't seem to find out where to do it. Any ideas?

And just to be clear:
 - I have a node called survey
 - It has fields on it like "name" and "email" address
 - Inbetween name and email, I want, for example, to show an image and some text. I want to be able to enter the html to do this, but not sure how to add it?

In code, I would just add a type "#markup", but how do you do this via the interface?

I guess this inbetween content is static or else you would have it as a field as well. So, I think you should just edit the template file of this node and add the fields and whatever other info you want between them directly on the file.

It would look sth like:

<?php print render($content['field_firstfield']);?> // first custom field
<div>
whatever you want inbetween
</div>
<?php print render($content['field_firstfield']); ?> // second custom field
<?php print render($content['body']);?> // all the rest content


Wanting to add a drop down menu to reg form I want to add a drop down list to the user registration form for users to pick a category for their page to be under when signing up.

I also want it so people can click on a menu and it will take them to a page view that their catagory is under.... for example, clicking on "food" brings up a view with all pages related to food..

Is this done with the taxonomy? Or can I just set up a view to fetch the related shops from the database?

Any ideas?

Create a  BLOCK-VIEW of type TAXONOMY.
Select the vocabulary which u have created and want to be displayed in DROP DOWN LIST.
In the format type,select JUMP MENU.
SAVE the view.
Assign view to a region where you want drop down menu to be displayed..


How can I add an AJAX callback to a checkbox? I am using taxonomy manager module I want to add ajax callback to checkbox tree view for checkbox is checked condition but it is not working can some one please suggest me. I have modified the code like this
$form[$term->tid]['checkbox'] = array(
      '#type' => ($multiple) ? 'checkbox' : 'radio',
      '#title' => $term->name, // Escaping is done in theme wrappers.
      '#value' => $value,
      '#return_value' => $term->tid,
      '#ajax' => array(
        'callback' => 'ajax_example_autocheckboxes_callback',
        'wrapper' => 'checkboxes-div',
        'method' => 'replace',
        'effect' => 'fade',
      ),
      '#required' => FALSE,
      '#theme_wrappers' => ($multiple) ? array('taxonomy_manager_tree_checkbox') : array('taxonomy_manager_tree_radio'),
      '#highlight' => in_array($term->tid, $terms_to_highlight) ? TRUE : FALSE,
    );

This is the taxonomy manager module theme function.
function theme_taxonomy_manager_tree_checkbox($variables) {
  global $user;
  $element = $variables['element'];
  $element['#attributes']['type'] = 'checkbox';
  $element['#attributes']['ajax']['event'] = 'change';
  element_set_attributes($element, array('id', 'name', '#return_value' => 'value'));

  // Unchecked checkbox has #value of integer 0.
  if (!empty($element['#checked'])) {
    $element['#attributes']['checked'] = 'checked';
  }
  _form_set_class($element, array('form-checkbox'));
  $output = '<input' . drupal_attributes($element['#attributes']) . ' />';
  /* custom alter function */
  if(user_is_logged_in()){
    if(!user_access('administer taxonomy')){
      $cdms_taxonomy_id = taxonomy_term_load($element['#return_value']);
      // echo "IF"; exit;
    }else{
      $cdms_taxonomy_id = taxonomy_term_load($element['#return_value']);
      // echo "Else"; exit;
    }
  }
  // echo '<pre>';print_r($variables);  echo"Term load"; print_r($cdms_taxonomy_id);  exit;
  $data = [
    'title' =>  $element['#title'],
    'tid' => @$cdms_taxonomy_id->field_cdms_txy_id[LANGUAGE_NONE][0][value],
    'count' => '',
  ];
  // Calling all modules implementing hook_my_data_alter():
  drupal_alter('my_data', $data);

  if (!in_array("Client User", array_values($user->roles))) {
  $title = $element['#title'] ."(".$data['count'].")";
}else{
   $title = $element['#title'];
}
  if (in_array("Client User", array_values($user->roles))) {
    $title = check_plain($title);
  }else{
    if (isset($element['#link'])) {
        $attr = array();
        $attr["class"][] = "term-data-link";
        $attr["class"][] = "term-data-link-id-" . $element['#return_value'];
        if (isset($element['#extra_info'])) {
          $attr["title"] = $element['#extra_info'];
        }
        $title = l($title, $element['#link'], array('attributes' => $attr));
      }
      else {
        $title = check_plain($title);
      }
  }

  $element['#children'] = '<label class="option">' . $output . ' ' . $title . '</label>';
  $element['#title_display'] = 'none';
  return theme('form_element', array('element' => $element));
}

ajax_example_autocheckboxes_callback function is not defined in the above code.

Also please update more info about what you are trying to do.

$form[$term->tid] = array(... 'ajax_example_autocheckboxes_callback' ...); //ajax callback
$form['tree']; //new field.

after the above function call you can get new built_info of $form_state as its rebuilt. So you can alter output of the field.

function ajax_example_autocheckboxes_callback($form, $form_state) {
  dsm($form_state);
  return $form['tree']; // this is a new field.
}

I will update my answer if more information is provided.


Drupal 7 Webform settings: how to change the default text in button "next page"? I have created a webform with drupal 7 with two pages with "pagebreak" field, but when i go in mysite webform and i view the webform at the bottom of the page there is the button "next page": i have to change the text in this button... and also probably set an image at the place of simple text "next page"..
Thank you !

You can use hook_form_alter to alter things in forms like button texts. This can in drupal 7 be done in both the theme and a module, but in Drupal 6 it can only be done in a module.


Create Alias URL to taxonomy term page with TID I am trying to figure out how to create a url-alias friendly url to a taxonomy term page with only the tid of the term. I know drupal does this automatically in the node, but I am trying to do this in a block.

e.g. Where the term is "Texas" with tid 34, and the alias is to the taxonomy page is "/location/texas"

So, instead of creating a url to this "/taxonomy/term/34", I would like to create a url to the aliased version of that link, to /location/texas, just with the TID.

Using Drupal 7.15

Thanks!

If what you are asking is, "How can I create a link to a taxonomy term path alias if all I have is the TID," you can use drupal's built in l() function in any php function or template.  For example, if taxonomy/term/34 exists and location/texas exists as its alias and $tid equals 34...

<?php print l('Texas Taxes', 'taxonomy/term/' . $tid); ?>

...will create Texas Taxes because l() will by default look up and use the alias for any system path.


Drupal Console Installation: The "phar.readonly" setting needs to be off to create Phars I am trying to install the Drupal Console for Drupal 8 on Linux Mint 17.1. During the installation I am getting the following warning notice:

[ ] Notice: The "phar.readonly" setting needs to be off to create Phars.

Any idea how to solve this? Will this effect the console operation?

Add this to your php.ini:

phar.readonly = Off

It won't affect the console's operation (unless it needs to create phars at some point, in which case it now can, whereas it couldn't before).


Require specific access for certain pages with only one input field For certain pages i have to require a login first (custom form with 1 input field).

When you try to reach the URL of one of those pages you are
redirected to a login-page
They have to fill-in a number of 11 digits. If the filled in field
contains 11 digits they are redirected to the protected page(s).

It's not an age gate. It's for doctors the have to fill in a 11-digit code. If the code contains 11 digital characters they can see the protected page(s).

How (which modules) are best practices to built this functionality?

so the characters can be random or need to be verified against some database table entries?

best thing would be to have a custom code/solution for this, use ctools popup and custom javascript to check for the right cookies on the selected pages, we can add a field defining the setting whether the page requires verification or not, and overridden node tpl (template) for that particular content type which can contain drupal_add_js or inline javascript based on the field condition. Adding a module and customising will add more pain in my opinion.


How to create navigation menu on sidebar with different navigation links displayed on different pages? I am using Drupal-7.

I have created Dropdown menu with Megamenu.
Now, I wanted to create navigation menu on left side that menu items will be different on each page.
I have created navigation block region for left side bar and wanted to create dynamic left side menu for each pages.
For example:

If our page structure is:

1.0
1.1

    1.1.1

1.2
    1.2.1
1.3
    1.3.1
    1.3.2
    1.3.3
        1.3.3.1
    1.3.4
    1.3.5
    1.3.6

So, on 1.0 page on left side menu should appears like this:

1.0
    1.1
        1.1.1
1.2
    1.2.1
1.3
    1.3.1
    1.3.2
    1.3.3
        1.3.3.1
    1.3.4
    1.3.5
    1.3.6

On page 1.1 left side menu - It should be only - 1.1.1
On page 1.2 left side menu - It should be only - 1.2.1

On page 1.3, it should be like this:

1.3
    1.3.1
    1.3.2
    1.3.3
        1.3.3.1
    1.3.4
    1.3.5
    1.3.6

On page 1.3.1, 1.3.2, 1.3.4, 1.3.5 and 1.3.6 - no item on left sidebar.

On page 1.3.3 - only 1.3.3.1 should be there.

Can anyone please let me know that how should I create left side bar menu like this? Do I have to use Menu Block module for that? If I have to use Menu Block module then how do I create menu items that will be displayed different on each pages?

Thanks!

This totally looks like a Menu Block scenario, where you would want to enable the 'Make the starting level follow the active menu item.' setting. Also enable 'Block title as link', but don't enter a custom title as this would override the link.


How do I add conditional fields to a paragraph? I was able to add conditional fields in a paragraph, following Conditional Fields in Paragraphs Using the Javascript States API for Drupal 8, but it controls and hides only 1 field.
I need to control multiple fields from one select list. I added multiple fields to a variable and created a for loop. The select list has 3 options.

3row|3row
2row|2row
1row|1row

The following is the code for the custom module. When it runs, the last for loop is the only one that works. The first 2 select list options don't work. Do I need to add a field value check before each for loop? My module name is conditional_fields.
use Drupal\node\NodeInterface;
use Drupal\node\NodeForm;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\paragraphs\ParagraphInterface;
use Drupal\paragraphs\Plugin\Field\FieldWidget\ParagraphsWidget;
use Drupal\paragraphs\Entity\Paragraph;

/*
 * Implements hook_field_widget_form_alter().
 */
function conditional_fields_field_widget_paragraphs_form_alter(&$element, \Drupal\Core\Form\FormStateInterface $form_state, $context) {
  $field_definition = $context['items']->getFieldDefinition();
  $paragraph_entity_reference_field_name = $field_definition->getName();

  if ($paragraph_entity_reference_field_name == 'field_topic_paragraphs') {
    $widget_state = \Drupal\Core\Field\WidgetBase::getWidgetState($element['#field_parents'], $paragraph_entity_reference_field_name, $form_state);

    $paragraph_instance = $widget_state['paragraphs'][$element['#delta']]['entity'];
    $paragraph_type = $paragraph_instance->bundle();

    if ($paragraph_type == 'teaser_content') {
      $dependee_field_name = 'field_paragraph_number_of_rows';
      $selector = sprintf('select[name="%s[%d][subform][%s]"]', $paragraph_entity_reference_field_name, $element['#delta'], $dependee_field_name);

      $fields_to_control1 = ['field_description_col_5','field_link_col_5','field_description_col_6','field_link_col_6','field_description_col_7','field_link_col_7','field_description_col_8','field_link_col_8','field_description_col_9','field_link_col_9','field_description_col_10','field_link_col_10','field_description_col_11','field_link_col_11','field_description_col_12','field_link_col_12','field_description_col_13','field_link_col_13','field_description_col_14','field_link_col_14','field_description_col_15','field_link_col_15','field_description_col_16','field_link_col_16'];

      $fields_to_control2 = ['field_description_col_9','field_link_col_9','field_description_col_10','field_link_col_10','field_description_col_11','field_link_col_11','field_description_col_12','field_link_col_12','field_description_col_13','field_link_col_13','field_description_col_14','field_link_col_14','field_description_col_15','field_link_col_15','field_description_col_16','field_link_col_16'];

      $fields_to_control3 = ['field_description_col_13','field_link_col_13','field_description_col_14','field_link_col_14','field_description_col_15','field_link_col_15','field_description_col_16','field_link_col_16'];

      foreach ($fields_to_control3 as $field) {
        $element['subform'][$field]['#states'] = [
          'invisible' => [
            $selector => ['value' => '3row'],
          ],
        ];
      }

      foreach ($fields_to_control2 as $field){
        $element['subform'][$field]['#states'] = [
          'invisible' => [
            $selector => ['value' => '2row'],
          ],
        ];
      }

      foreach ($fields_to_control1 as $field) {
        $element['subform'][$field]['#states'] = [
          'invisible' => [
            $selector => ['value' => '1row'],
          ],
        ];
      }

      unset($element['subform']['field_paragraph_number_of_rows']['widget']['#options']['_none']);
      $element['subform']['field_paragraph_number_of_rows']['widget']['#empty_option']  = t('- 4 Rows -');
    }
  }
}

I've used form states with these pre-requisites:

Form states with paragraphs
The content widget used is: Inline Entity Form - Complex
The widget should be changed, not the field

There is this content type with the paragraph reference with a two-fields paragraph: content reference and content number. The content reference field cardinality is 5, and the number of content is a select list (1, 2, 3, or 5). So, the logic is used to enable the content input according to the number of content selected.
This was the solution I've used, hopefully, it can help someone else:
/**
 * Implements hook_field_widget_WIDGET_TYPE_form_alter().
 */
function HOOK_inline_entity_form_entity_form_alter(&$entity_form, &$form_state) {
  if ($entity_form['#entity_type'] === 'paragraph' && $entity_form['#bundle'] === 'PARAGRAPH_BUNDLE') {
    $parents = $entity_form['#parents'];
    // It needs to get the parent form (content type form field) in order to work fine.
    $identifier = $parents[0] . '[' . implode('][', array_slice($parents, 1)) . ']';
    // I need to use the target_id to aim the wdiget.
    // The first input should be shown if I select 1, 2, 3, or 5 content to be added.
    $entity_form["field_content_reference"]["widget"][0]["target_id"]['#states'] = [
      'enabled' => [
        'select[name="' . $identifier . '[field_content_number]"]' => [
          ['value' => 1],
          'or',
          ['value' => 2],
          'or',
          ['value' => 3],
          'or',
          ['value' => 5],
        ],
      ],
    ];
    // The second input should be shown if I select 2, 3, or 5 content to be added.
    $entity_form["field_content_reference"]["widget"][1]["target_id"]['#states'] = [
      'enabled' => [
        'select[name="' . $identifier . '[field_content_number]"]' => [
          ['value' => 2],
          'or',
          ['value' => 3],
          'or',
          ['value' => 5],
        ],
      ],
    ];
    // The third input should be shown if I select 3, or 5 content to be added.
    $entity_form["field_content_reference"]["widget"][2]["target_id"]['#states'] = [
      'enabled' => [
        'select[name="' . $identifier . '[field_content_number]"]' => [
          ['value' => 3],
          'or',
          ['value' => 5],
        ],
      ],
    ];
    // The rest of the input should be shown if I select 5 content to be added.
    $entity_form["field_content_reference"]["widget"][3]["target_id"]['#states'] = [
      'enabled' => [
        'select[name="' . $identifier . '[field_content_number]"]' => ['value' => 5],
      ],
    ];
    $entity_form["field_content_reference"]["widget"][4]["target_id"]['#states'] = [
      'enabled' => [
        'select[name="' . $identifier . '[field_content_number]"]' => ['value' => 5],
      ],
    ];
  }
}


Default value for form_system_theme_settings_alter I'm trying to set some theme settings, and I can't figure out how to have my settings get their default value, which should be obviously the currently set value.

Here's an example:

$form['navbar_layout'] = array(
    '#type'          => 'radios',
    '#options'       => array(
        0 => 'Logo left, Menu right',
        1 => 'Logo right, Menu left',
    ),
    '#default_value' => theme_get_setting('navbar_layout'),
    '#title'         => t('Navbar\'s Layout'),
    '#description'   => t("Choose the layout of the navbar."),
);

Each time I'll access the theme settings page, no box will be checked, despite the fact theme_get_setting() correctly returns the right value.

I think it will only execute if you save the theme settings page. If you want to have the default work upon theme activation you have to have your setting in your theme's .info file. I could be wrong.


entity_metadata_wrapper - how to remove one item from entity reference field I have a entity reference field that holds relations to multiple nodes. I have to remove one item programmatically based on nid. Normally to remove item I've just set it to null like this:

$wrapper->field_foobar = NULL;

But entity reference is a list, so I have to know delta for element to do something like this:

$wrapper->field_foobar[$delta] = NULL;

So I have content_id and target_id what should I do to find delta? I know it's possible to do it with simple SQL query, but I gues there should be some way to do that with entity metadata .

Any sugestions?

I'm on Drupal 7 of course.

Use unset instead, followed by a save:

unset($wrapper->field_foobar[$delta]);
$wrapper->save();

To find the delta, you can iterate over the collection and look for the node id:

foreach($wrapper->field_foobar as $delta => $item)  {
  if ($item->nid->value() == $my_id) {
    unset($wrapper->field_foobar[$delta]);
    $wrapper->save();
    break;
  }
}


Comments form action points to different node I'm having a very weird problem with comments on a node. I recently upgraded to Drupal 7.12.

Now the comments aren't working right. When a user (registered or anonymous) enters in a node page, the action call of the comment form points to the page URL. But, when the user browses to another page, the action call of the comment form of the new page remains pointing to the previous page! This happened until the browser is closed, or the user logs out.

Could anyone shed some light as to why this is happening?

[Edited]
I just discovered that when I disable de Panel module the issue is not happening. The problem is that all the presentation layer goes to the trash :-( Anyone had a similar problem?

I think I've patched the problem clearing the cache just before the comment form render:

    <?php print render($page['content']); ?>
    <?php cache_clear_all('*', 'cache', TRUE); ?>
    <?php print render($content['comments']); ?>

As I said, seems there is a variable cache problem, and it seems to be on the Ctools module. This is only a patch until the fix comes.

Hope it will be useful.


Better Exposed Filters and a Node Relationship I'm using Better Exposed Filters to enable datepickers for exposed date fields on my View. It's great, except that my view displays nodes via a taxonomy relationship. If I try to filter by node creation date, I don't get any Better Exposed Filters options. However, if I choose a date field that doesn't use a relationship (even if it doesn't exist on the term and therefore doesn't work), I get all the Better Exposed Filters options.

How can I best go about putting a popup datepicker on my exposed filter that uses a relationship?

I don't think this is related to the relationships. It looks like Drupal core date fields (post, changed, etc.) are not getting the proper BEF options, namely the datepicker. That's a bug in BEF -- it was mentioned at the end of this issue, but I never saw that because that issue is closed. Feel free to post a bug in the BEF issue queue for this.

Thanks.


How do I receive and record Paypal transaction variables from POST? I have a service I want my customers to subscribe to, and I want to be able to update a field within my DB based on their subscription. Was it cancelled? Did it successfully begin/recur?  I'd like to get this information, so I can perform the update within my database accordingly.

I would like to capture the transaction variables that Paypal POSTS to a specified successful payment URL, but I have no idea how. I obviously need to create a page that does this, but I'd like to know what I need to do.

Look at the uc_paypal module included with Ubercart for a fantastic example of this. Look at uc_paypal_menu() (in uc_paypal.module) and uc_paypal_ipn() (in uc_paypal.pages.inc).


Menus, drush uli link, and some images not working after moving site to localhost I've just gotten a site I'm supposed to do some work on but I'm having trouble with migrating to a local development environment. I don't have admin access to the site itself, but I do have access to the server. I pulled the database down along with the code base, but I seem to have messed up the file permissions when moving the site because the site loads, but not all the functionality is present.

The site isn't accessible beyond the splash page, and none of the image assets load except the site logo. Accessing any menu links generates a 404. The image that loads has the same ownership and permissions as the image which loads which are myuser:www-data and 640. Initially, no images loaded, but following this post about securing file permissions got the logo loaded.

I am also having issues with accessing the site. Since, I can't access any menus beyond the root, it seems that I can't access the login page either. I've added a user for myself with Drush, and even run drush uli with the the URI provided as a parameter, but the link is inaccessible and returns a 404. I also used the File Permissions module, but it doesn't seem to have helped.

At this point, my next step is going to be setting up a clean install and importing the db through backup and migrate and moving the theme and modules manually, but I'd like to figure out what I did wrong and how to avoid this.

I did recently a manual migration and had some problems, similarly to you. After this, I made a script to manually migrate the site and the database. You need to have a zip with the Drupal installation, not the folder of the installation, just the files inside it, the database and know if the database has some prefix. Change all the prefix in the database, you could use notepad++ or similar to change all in one command. Change the url i.e: mydomain.com/drupal to localhost/drupal. Then import the database, and unzip the files in your localhost server. Then go to sites/default/settings.php and at the bottom of the file edit the data of your database, prefix if you have one, pass, user, port if you changed it and, in same file, look for $settings['update_free_access'] = FALSE; and change it to true.
Now, in your browser visit localhost/yourinstallationfoldername/update.php and follow the instructions.
If you don't know the users you can see in the database for the table users and you can see there their ID (uid) and password (uuid) on md5. Just search on google for any md5 generator and copy paste it on uid 1 (admin user generated on installation) for know the name of the user you can go to the table users_field_data and look on name column.

If you have a virtual server working on your server, you must remember to point it to the new folder where is your Drupal installation. This is a good tutorial about how to do it: Installing virtual hosts for Drupal sites and subsites.


How to find the view/page/module that's generating a SQL statement I have newrelic performance monitoring with my Pantheon hosting account. It shows "slow SQL" reports but I can't tell which page, view or module is generating a SQL statement.

For example:

  SELECT node.nid AS nid, node.title AS node_title, users_node.name AS
  users_node_name, users_node.uid AS users_node_uid, node.created AS
  node_created, '?' AS field_data_field_photo_node_entity_type FROM node
  node INNER JOIN users users_node ON node.uid = users_node.uid LEFT
  JOIN field_data_field_photo_topic field_data_field_photo_topic ON
  node.nid = field_data_field_photo_topic.entity_id AND
  field_data_field_photo_topic.field_photo_topic_tid =
  :views_join_condition_? WHERE (( (node.status =
  :db_condition_placeholder_?) AND (users_node.uid = :users_uid? )
  )AND(( (node.type IN (:db_condition_placeholder_?)) AND
  (field_data_field_photo_topic.field_photo_topic_tid IS NULL ) )))
  ORDER BY node_created DESC LIMIT ? OFFSET ?

How could I get that info?

I suspect your logs are are the output from the MySQL Slow Query Log.  What ends up here varies based on server configuration, but they general culprits are

Queries that take a long time
Queries that don't use indexes

My suggestion is to try to match up the timestamps (start time) to the Apache access_log to get a page.  Then, use the Devel module and enable "Display query log" from admin/config/development/devel.  This will record queries and log them along with execution times.

It looks like that bad query is tied to a view.  For these, enable "Add Views signature to all SQL queries" on the Advanced settings page.  When you do this you can identify which view is slow.

To resolve the "slowness", copy the query and hand edit to add in the parameters.  Then open a MySQL tool, and use the EXPLAIN statement.  Look at what it tells you and go from there.


Change URL of site, server and folder remains the same I want access an old site on a new domain. The server and folder remains the same. I have pointed the new domain to the old Drupal site and updated settings.php to include

$base_url = 'http://www.newurl.com';

I can access the site, but all links in the theme and in the control panel point to http://oldurl.com. I can navigate around the site by manually altering each URL to reflect the new domain.

I'm under the impression that updating base_url should work, and take effect immediately. Have I missed something?

Seems the website was coded using absolute paths, which is not really good practice from Drupal coding standard's perspective. Please read the discussion on Absolute or relative URLs?. Your case is covered by the accepted answer:

  When moving a site from dev > staging > production a Wordpress site's
  URLs and image references have to be replaced in the DB, this can
  create an absolute mess.

Though Wordpress is mentioned, that concerns any type of websites, including Drupal.

Anyway, to address the issue you need to do two things:

Look for and replace all the instances of your old domain in the active theme's template folder. This is easier part as any decent text editor has Find&Replace feature.

Check the website again and if everything is working then you are lucky. If not proceed to the second step.

Search and replace all the instances of your old domain in the database tables. You can do it either using drush or UI like phpMyAdmin. The query is pretty simple:

UPDATE table_name SET field_name = replace(field_name, 'old-domain', 'new-domain');

To do so you first need to figure out the tables where your old domains could be stored. Most probably those are 'node' and 'comment' tables and their last revisions, however if content types have additional custom fields then more tables are involved. You could perform quick search for the old domain in the database to find all the tables where it is stored.

If step 2 is involved, then I would also suggest, using the opportunity, to turn all your paths from absolute to relative. In that case, you would run:

`UPDATE table_name SET field_name = replace(field_name, 'old-domain/', '/');`

instead.

I hope this helps.


Using CDN for jQuery and jQuery-ui with Drupal 6 For my Drupal 6 site, I'd like to get the latest jQuery and jQuery-ui scripts from the Google CDN.  Although this seems like something that many people would want to do, it seems that it is not so easy.

The project Advanced CSS/JS Aggregation (advagg) seems promising, but after installing it and trying to use the Google CDN in the standard way, e.g., adding

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/jquery-ui.min.js"></script>

to the head of a Drupal page, those files are not available.

Any ideas for how to do this?

EDIT:

I used drupal_set_html_head() to add the above lines to the HEAD of the Drupal page where I want to use jQuery and jQueryUI.  I verified that this was working by viewing the page source.

Those files look to be available https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/jquery-ui.min.js

update

As to why it didn't work:

Jquery that ships with drupal 6 is 1.2.3
The Jquery update module can push this to 1.3.2

You are trying to use a much more recent version of jquery than Drupal 6 can handle. Drupal uses a lot of jQuery in it's workings, so it is not straightforward to put a new version on top. Sorry I didn't spot that earlier.


Premium Responsive Drupal 6 themes? Where can I find Premium Responsive Drupal 6 themes?

(CSS defined in such a way that the same stylesheet is used on mobile and desktop)

It must be Drupal 6 because I am using it with drupal-cod.

Update 1: As pointed out by the OP, Jeff Burnz doesn't only sell his time as a consultant, but actually has a site, AdaptiveThemes.com, where he sells his "adaptive"-themes, but those are D7 only.

Unfortunately I'm not aware of any company advertising such themes yet.
One of the first I would except to see this from is http://fusiondrupalthemes.com/, but nothing there yet.

If you are looking for something more unique, I believe the Drupal 8 Design Initiative owner, Jeff Burnz, sells his time to make themes, and is the author of a number of responsive themes already. Sky, Corolla and the base theme Adaptive theme, which you may want to look into, given the lack of an actual answer to your question.


Display twitter tweets for own account in drupal 6 Suppose My twitter account is drupaltest so I want to display all the mentions of #drupaltest or @drupaltest on the Drupal 6 website. Looking at the twitter module http://drupal.org/project/twitter but that one is a little confusing. So let me know whats the best way to post tweets for your accounts on the Drupal 6 website? I am not looking for any reverse functionality of posting on twitter through my website, just want to display those tweets.

Thanks.

The easiest way is definitely to install the Twitter module that you have already discovered. I used to do this on my website as a way of pulling in tweets to my blog. You will only need the read-only configuration for the module, and you may find it easiest to use the Views integration.

If you'd rather code your own, the QueryPath module allows you to write jQuery-like requests directly against Twitter's API, but you'll have to write your own module. (You can start with the sample modules that come with QueryPath).


Views Galleriffic- pagination does not show When I updated the Views module to 6.x-3.x-dev, pagination stopped being shown in Views Galleriffic 6.x-1.x-dev.

http://demo.dolphin-sch.ir/Doctor/content/asas

My settings are:

Use pager: Paged, 9 items
Style: Galleriffic Gallery
Enable Bottom Pager: yes

And I have 17 images.

Please guide me.

I want to show pagination like this link:
http://demo.dolphin-sch.ir/nagara/fa/galleriffic/95

1) Turn off the Views pager (ie set it to "All items).

2) In the "Style" set the number of thumbnails you want to display before the pager. If you have 17 images you can set it to "9" there.

3) Make sure you have the top or bottom pager turned to "yes" in "Style".

Any luck? I just tested it with views-6.x-3.x so it should work if you have the right settings.


cant install themes after upgrade I've upgraded from  D6.31 to D7 . few problems with block.tpl.php in te deafult theme, but sorted easily.
Now when I install a theme i get a WSOD

select * FROM watchdog ORDER by wid DESC lIMIT 2;

gives an error of

The file %path was not deleted, because it does not exist. | a:1:{s:5:"%path";s:43:"temporary://marinelli-7.x-3.0-beta11.tar.gz";}

google hasnt thrown up any possible solutions. Anyone know ?

hmmmm . When i try it today i get an error message in the browser. I thought I had turned on error reporting in php.ini yesterday.

OS ubuntu 14. all the webdirectory is chown www-data: www-data .
ive tried chmodding the themes directory to 777 but I still get the error.

ive just got one user, I assume admin privileges havent changed with the upgrade

Warning: move_uploaded_file(/tmp/marinelli-7.x-3.0-beta11.tar.gz): failed to open stream: Permission denied in drupal_move_uploaded_file() (line 1639 of /var/www/devsite.org/includes/file.inc).
Warning: move_uploaded_file(): Unable to move '/tmp/phpgdOHHS' to '/tmp/marinelli-7.x-3.0-beta11.tar.gz' in drupal_move_uploaded_file() (line 1639 of /var/www/devsite.org/includes/file.inc).
File upload error. Could not move uploaded file.


How to save database connection easy and safe? I'm trying to let Drupal7 connect to several databases(pgsql) and update data automatically. So I use Database::addConnectionInfo($name,'default',$connString) And db_set_active($name).

It works perfectly until I realize it's dangerous to save database password in fields while the connection string actually needs it.

Is there any way to do so easy and safe?

Thank you! :)

Well, there is the encrypt module which can encrypt your data. Be sure to use the 7.x-2.x branch.

And yes, store the key somewhere on the filesystem that is not easily accessed and it should be hard for an attacker who has db access to be able to decrypt the info.

Just be sure that there's no way to execute php via the Drupal interface. A module like paranoia can help in that.


How to customize the "Read more" link in D7? By default, the "Read More" link wrapped in the tag <li>. How i can change this tag to <p>?

I tried to use hook theme_node_view_alter(&$build), but i couldn't find in $build required variables.

node_build_content is where it's originally set. You should be able to override this by implementing hook_node_view or hook_entity_view. The links should be in $node->content['links']


Auto sign-in to Organic groups homepage I have setup a site where users can register as a certain type of user. Once registered, an organic group node is created for them and they can then invite other users into their group.

Can anyone advice me how the group owner and the invited members to automatically login to the group page and how to restrict users to a single group?

The way I accomplished this was to use Rules to detect when a user logs into the site and also when content is about to be viewed.

Rules provides a programmatic  area in the "DO" feature of the Rule. I execute some php code to detect the group the user belongs to and redirect using drupal_goto.


Why doesn't hook_preprocess_block() alter the block content? I'm finding I can't alter block content with hook_preprocess_block() in Drupal 8.  Should I expect to be able to alter content, such as a block body, using hook_preprocess_block()?

For example, this has no effect on my block output:

function mysite_preprocess_block(&$variables) {
  $variables['elements']['content']['body'][0]['#text'] = 'alter all block bodies everywhere';
}

There were two issues, in my case.  For one thing, I was using the wrong key.  I needed to use...

$variables['content']['body'][0]['#text']

...instead of...

$variables['elements']['content']['body'][0]['#text']

The other issue was that I had nothing saved in the body field, and in some cases setting a value for the body field in hook_preprocess_block() has no effect on output unless there is a value saved in the body field.  You must at least save some garbage characters to the field or else setting a value in hook_preprocess_block() will have no effect on the output.


How to add my html code so as to design the page generated by a view using drupal 7? I have created a view with a page and a block. Also i have created a new content type by creating a new node--news_page.tpl.php file and a page--news.tpl.php file so as to display my block there. What am i trying to do is to edit the way news are displayed. To accomplish that i need to add my html code to the page the view created. How do i do that using drupal 7 and views3 module?

In your view on the right-hand side there is an 'advanced' link.

When you click this it will display a number of advanced options.

The option you want is 'Theme : information".

Click on information and you will presented with a number of template suggestions to help you theme your view.

To determine what template to use you basically need to think what level you want to theme at.

Example:
If you click the link 'Display output' and copy/paste the code into one of the suggested file names i.e. views-view--[YOUR_VIEW].tpl.php, this is the top level you can theme at.

If you wanted to theme a particular field you will find that further down in the suggestions.


How to resolve error 'migration_group' entity with ID 'migrate_drupal_7' already exists? I have been trying to migrate to Drupal 8 using the drush. I have followed all the instruction as mentioned in [https://drupalize.me/blog/201604/custom-drupal-drupal-migrations-migrate-tools][1]

After installation, enabled all the required modules like migrate upgrade, migrate tools and migrate plus, and then added the code in settings.php file mentioned below.

 // Database entry for `drush migrate-upgrade --configure-only`
$databases['upgrade']['default'] = array (
  'database' => 'dbname',
  'username' => 'dbuser',
  'password' => 'dbpass',
  'prefix' => '',
  'host' => 'localhost',
  'port' => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
);
// Database entry for `drush migrate-import --all`
$databases['migrate']['default'] = array (
  'database' => 'dbname',
  'username' => 'dbuser',
  'password' => 'dbpass',
  'prefix' => '',
  'host' => 'localhost',
  'port' => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
);

Now used the command - **drush migrate-upgrade --configure-only --legacy-db-url=mysql://dbuser:dbpass@localhost/dbname --legacy-root=/path/to/sites/default/files** and than drush returns the following errors - ***'migration_group' entity with ID 'migrate_drupal_7' already exists***

How can I resolve the error?

you can delete existing migration groups from: /admin/structure/migrate


How to create Page variant Selection rule "if URL contains"? I want my variant to apply to all pages if the URL contains a certain string, eg: "cars".

So the cars variant should apply to cars, cars/toyota, cars/toyota/camry, etc.

Is there a way to use a wild card (cars/*?)?

I can't find any documentation on this.

Thanks

Try under Variant -> Selection rules, in the pulldown Select:URL Path then Add. In the new dialog box, select "Allow access to the following pages" then enter "cars/*" in the textarea, then save. According the description below the textarea which says

The '*' character is a wildcard. Example paths are blog for the blog page and blog/* for every personal blog.


Search API Panels Display and Contexts I am trying to build a page with Search API and Panels. I have created my search views with contexts, but I am unable to view any facets in my panel page.

My facets show up in regular blocks, but they don't show up in panels regions.

I have been able to find information regarding this issue from this Search API Issue. Apparently the order of the way the view is placed in panels is the problem, and if I re-order my facets and views in Panels, the facets show up properly.

In comment #28 of this issue, there is a way to set up a context to be able to display the facets anywhere on a panel page, but the wording is very confusing.

  EclipseGc actually gave me a quick walkthrough on how to do this the
  "proper" way. It takes a bit more time and effort but its a lot more
  flexible and effective (plus it works without having to try and figure
  out the order of blocks like above). The basics of it are:

  Create a context view for your display.
  Go to contexts in your panel and add a view context with your view.
  You will now have a new "view context" option when adding content
  to a region.
  Choose view row (this is where it gets a bit more complexed as you
  have to manually build grids etc using regions and rows and so forth).
  You can now add your facets using the miscellaneous content option
  in panels wherever you want in your panel!
  I had to use to the default view exposed forms as the context view
  exposed forms didnt want to inherit the path. These can also go
  wherever and work!

What is a "context view" and how do I add it? It is a ctools context? Or is it a new context in views, or is is a context having to do with the contexts module?

Thanks for your help!

It's about time this got a proper answer. Here's that explained as a step-by-step:

Creating a Search API view. None of this will work unless, when you initially create the view, you choose one of the Search API options like "Show [Search Index]" and the appropriate index instead of "Show [Content]" in the drop down at the very start of the views creation process.
Giving it a Context view display. A "Context view" is a type of View Display like a "View block" or a "View page" or an "Attachment view" etc. Create one with the "Add" button at the top of the View edit page.
Load it as a Context in Panels or Page Manager. The thing that is special about Context views, is that systems built on cTools contexts (like Panels and Page Manager) can load the view early on in the process, and also, analyse it so they know what types of data to expect. In the Contexts page for your Page Manager page or Panel, add a context, choose Views, then find the right view.
Place each part of the view as Content. Because cTools is loading the View as a context, and because cTools knows what Views are and how to make sense of them, it knows exactly what elements of the view it's going to get. If it was a views block, all it can do is just dump the whole output of the block somewhere, but since it's taking the time in the Context stage to analyse and make sense of the View, it can figure out that it's going to get seperate rows, headers, footers, exposed fitlers, etc. When you go to Content in the Panels / Page Manager interface, you'll find a 'Views Context' vertical tab with various bits of your view in it. This is the "bit more complexed" bit the guy refers to. If you want, you can go nuts and build a complex, sophisticated grid display placing the Views Row content type lots of times with different limits and offsets, with the first row highlighted, then a column showing rows 2-5, then a column showing rows 6-10... Or you can just stick the 'Views row' content in without limits or offsets (plus Views Header and Views Footer if you're using them) and it'll work as normal.
Place the Facets, Current View block, etc. This is the important bit for the question. Because the View is loaded at the start of rendering the page, the search is loaded at the start of rendering the page, so order doesn't matter. If it was a Views block, it wouldn't be done until that block was rendered. So your facets and current search blocks can go anywhere.

All of this is a bit rough around the edges and might not work first time. If you're using Search API Spellcheck, don't forget to put it in the View Header then place the View Header in Panels / Page Manager. If your view gets its search terms using Contextual Filters instead of Exposed Filters, sometimes it just works, but you might sometimes need to set the argument manually and occassionally check and patch supplementary modules like Current Search Links and Search API Spellcheck depending on how the search is set up.


How to get Webform Radio Option Value as a token value for email template? I am trying to use my webform's radio field to choose between two departments, let's call them ABCDE and XYZ.  On the webform display that the user sees, I want them to show up as ABCDE and XYZ.  When I send the form as an email, I need these to show up as a similar 4 digit word such as ABCD and WXYZ.

I attempted to do this by setting the "Option Value" as the hidden 4 digit word and then have the actual text show up as "Option Text".

In the email template, I have this printed out as: [webform_submission:values:radioButtonName]

This prints it out as the "Option Text" (ABCDE and XYZ) rather than the "Option Value" (4 digit ABCD or WXYZ) that I am looking for.  Is there a way to print the "Option Value" of this radio button instead?  I assume its done by changing the word "values" to something else, but I haven't been able to find this.

You need to append the :raw suffix to the token and change [webform_submission:values:radioButtonName] to [webform_submission:values:radioButtonName:raw].


What do I do with the "files"? I have a pantheon account and a Drupal site installed on it. I wanted to work on my project via localhost, so I have the WAMP server setup, with the Drupal code and downloaded & imported the Drupal Database. However, I also have pantheon "files". What do I do with these files if I already have the code & database? I downloaded them to my computer in a zip file, but not sure what to do with them or where to put them?

That should be the contents of your public file system, which will usually be placed at PATH_TO_DRUPAL_ROOT/sites/default/files


How do I use composer with modules? I'm working on a custom module and want to use phpoffice/phpexcel

I can install the library just fine with composer require phpoffice/phpexcel, but what if I update Drupal-Core to a new version and by doing so override the composer.json? I would have to remember to do another composer require ... to add the dependency again.

What is the right way of doing this?
I have a similar problem with the address-Module, which also requires to be installed with composer.

To avoid overriding composer.json file you should update drupal/core using composer too.

https://www.drupal.org/docs/8/update/update-procedure-in-drupal-8

To update only drupal/core you will have something like

composer update drupal/core --with-dependencies

Which will only update the composer.json file, not overriding it.

[EDIT] Before you begin ( from documentation )

Always take a backup of your files and db before updating.
If you're using composer and version control, also commit and push composer.json and composer.lock. Use mysqldump to backup your database. Modules such as Backup and Migrate are also available.
Alternatively, you can create a .tar.gz of files and the database with drush archive-dump (however this is a legacy command, slated for removal in Drush 9, which only covers files under /web).
Read the core release notes and, as a precaution, check the project page for each contributed module, theme or plugin: some may need updating to work with a new "minor" version (e.g. 8.3) of core.  Patch releases (e.g. 8.3.1) shouldn't require this, but it's advisable to test in a development environment first.
Activate maintenance mode when updating production servers.


Load external libraries in a custom block I need to implement a custom block using JavaScript. These are the steps I took.

I created a custom module
I created a custom block by creating a class which extends blockbase
I created a JavaScript file
I defined a library in libraries.yml file and included the JavaScript file
I attached the library to the block using #attached

So far so good. In the JavaScript file, I am trying to use the open source Datatables library, but I am unable to add it.

This is the code that implements the block.

/**
 * @file
 * Contains \Drupal\custom_cms_blocks\Plugin\Block\TopNewsBlock.
 */

namespace Drupal\custom_cms_blocks\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
 * Provides an 'Active forum topics' block.
 *
 * @Block(
 *   id = "top_news_min_block",
 *   admin_label = @Translation("Top News Min Block"),
 *   category = @Translation("Custom CMS blocks"),
 * )
 */
class TopNewsBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
     //Fetch data
     return array(
      'type' => 'markup',
      '#markup' => '

Artist / Band	Album	Song

Muse	Absolution	Sing for Absolution

',
      '#attached' => array(
        'library' =>  array(
          'https://cdn.datatables.net/1.10.11/js/jquery.dataTables.min.js',
          'custom_cms_blocks/top-news-library'
        ),
      ),
     );
  }

}

Can you explain me how I can include an external JavaScript file in a block?

Libraries don't work like that. You need a yourmodule.libraries.yml and define it there.

There's detailed documentation on https://www.drupal.org/developing/api/8/assets#external. The following is an example of how a library is defined.

angular.angularjs:
  remote: https://github.com/angular/angular.js
  version: 1.4.4
  license:
    name: MIT
    url: https://github.com/angular/angular.js/blob/master/LICENSE
    gpl-compatible: true
  js:
    https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.min.js: { type: external, minified: true }

Then, the library that you specify is yourmodule/nameofthelibrary, see https://www.drupal.org/developing/api/8/assets#render-array or any of the other examples on that page.


How do you remove or hide the 'Permalink' in comments? Does anyone know how to remove or hide the 'permalink' in the comments section (i.e on posted comments).Here is a copy of one of my comments -

" Permalink Submitted by Jade K on Fri, 11/11/2011 - 14:28"

Additionally, does anyone know how to rename or remove 'submitted by' from comments?

Copy the default comment comment.tpl.php into your theme directory:

cp /your_drupal_path/modules/comment/comment.tpl.php /your_drupal_path/sites/all/themes/mytheme/comment.tpl.php

Search and change the following lines into your theme's path comment.tpl.php:

From:

<?php print $permalink; ?>
<?php print $submitted; ?>

To:

<?php print $submitted; ?>

This will do the magic!


Override theme_node_preview I'm using a custom theme but Seven as administration theme.

How can I override the theme function 'theme_node_preview'?

Notice that theme_node_preview is called in the node form, and it's shown in an overlay. So it's part of the admnistration theme.

I tried to used the generic phptemplate_ prefix but this way of overriding theme functions was removed for Drupal 7.
I tried seven_node_preview from a module and also from the template.tpl.php of my custom theme, but didn't work.
I don't want to create a subtheme of Seven only for this.

I know you explicitly stated that you don't want to create a subtheme of Seven, however short of hacking the core Seven theme or messing with the theme registry (which I explain below against my better judgement) this is the simplest way to accomplish what you are trying to do.  The amount of overhead to do this is incredibly small and requires only three files.  Simply create a folder named something like "mytheme" and add an empty "mytheme.css" file in addition to a "mytheme.info" file with the following code:

name = My Theme
description = Custom subtheme of Seven.
core = 7.x
base theme = seven
stylesheets[all][] = mytheme.css

Then add a template.php file and override the theme hook similar to below:

function mytheme_node_preview($variables) {
  // Do custom stuff here.
}

All done. This is the "Drupal way" of doing theme hook overrides.

Again, it is against my better judgement to post the code below. If you absolutely have your mind set on not creating a subtheme, you can implement hook_theme_registry_alter().  Did I mention that this solution is hacky and the hook is pure evil? :-) In a custom module named "mymodule", do the following:

function mymodule_theme_registry_alter(&$registry) {
  $path = drupal_get_path('module', 'mymodule');
  $registry['node_preview']['file'] = 'mymodule.module';
  $registry['node_preview']['theme path'] = $path;
  $registry['node_preview']['function'] = 'mymodule_node_preview';
  $registry['node_preview']['includes'] = array(
    $path . '/mymodule.module'
  );
}

function mymodule_node_preview($variables) {
  // Do whatever you need to do here.
}

Use the snippet above at your own risk.


drush up fails with Unknown archive format Today, I am getting an error message when I run the Drush download or update command.

drush up -y captcha

fails with

  Unable to extract /.tmp/drush_tmp_1582749966_5e56d90e14736/captcha-7.x-1.7.tar.gz. Unknown archive format. [error]

When I changed the Drush temp directory I still get the same error message. Also, same error message using php7.2, php7.3, php7.4

Why does this happen?

I had the same issue.
I'm on PHP 7.4.5
The issue is fixed by upgrading drush from 8.1.15 to 8.3.3:

Change (update to 8.3.3) Drush-Version in

~/.composer/composer.json

and

composer update


How can I run Drush as user 1 in version 5? Drush v3 had a --user flag (--user=1), however, this seems to be removed since v4, according to the website.  How can I run Drush 5 as logged in as user 1?

See drush topic core-global-options; you will see that the --user flag is still supported.

Of course, you do not really 'log in' to your Drupal site with Drush.  The usual convention is that Drush commands should call API-level functions, which are expected to operate independently of the current user.  (Drupal does access checks before calling the API functions.)  There are only a few instances, mostly in contrib, where setting the user is necessary.


Drupal 7 CKEditor-CKFinder remove "Browse Server" I have a multi-domain site setup with domain access module. In each domain users are allowed to post their own contents with media upload settings. I am using CKEditor and CKFinder together.

Now, I want to disable the "Browse Server" Button but the local Browse button will be there.

I am unable to find the settings(which I think not in Drupal admin) or the code to edit to fixup this.
https://stackoverflow.com/questions/3610041/ckeditor-with-ckfinder-disable-filebrowser-keep-upload-functionality
This one didn't helped my either.
Any help on this?

Well I have found that patch solution. So just answering my own question.
In sites/all/modules/ckeditor/includes/ckeditor.lib.inc file,

There is a section as

if (user_access('allow CKFinder file uploads')) {
                $ckfinder_full_path = $host . ckfinder_path();
                //$settings['filebrowserBrowseUrl'] = $ckfinder_full_path . '/ckfinder.html?id=' . $profile_name;
                //$settings['filebrowserImageBrowseUrl'] = $ckfinder_full_path . '/ckfinder.html?Type=Images&id=' . $profile_name;
                //$settings['filebrowserFlashBrowseUrl'] = $ckfinder_full_path . '/ckfinder.html?Type=Flash&id=' . $profile_name;
                $settings['filebrowserBrowseUrl'] = '';
                $settings['filebrowserImageBrowseUrl'] = '';
                $settings['filebrowserFlashBrowseUrl'] = '';
                $settings['filebrowserUploadUrl'] = $ckfinder_full_path . '/core/connector/php/connector.php?command=QuickUpload&type=Files&id=' . $profile_name;
                $settings['filebrowserImageUploadUrl'] = $ckfinder_full_path . '/core/connector/php/connector.php?command=QuickUpload&type=Images&id=' . $profile_name;
                $settings['filebrowserFlashUploadUrl'] = $ckfinder_full_path . '/core/connector/php/connector.php?command=QuickUpload&type=Flash&id=' . $profile_name;
            }

So I commented the actual filebrowserBrowseUrl, filebrowserImageBrowseUrl & filebrowserFlashBrowseUrl settings and made those as blank. That did the trick.


Custom display suite template I'm trying to understand Drupal 8 theming, since I want some custom layouts for some of my pages. I've tried Display Suite module, and it gets me some of the way, but non of the display suite layouts offers the exact layout I need.

How do I make my own Display Suite layouts? I have made a copy of the layout template files from ds/templates to mythemename/templates/generated, and renamed the file as Display Suite tells me to. When I open that file, I see Header, Left, Right and Footer "regions". But how would I go about adding new regions to that template? I understand how to add block-regions to a website, but that seems to be something different than the "regions" in a display suite template.

And if I edit a display suite template, would I somehow be able to rename it to, lets say, "mytemplate", and make it appear in the drop-down box from where you select what display-suite template to use?

You can create your own layouts in a module or theme by defining a my_module.layouts.yml or my_theme.layouts.yml file. Then you'll have to create the templates for your layouts where you output the regions.

This is the layout definition for the DS 2 Col Fluid layout (ds.layouts.yml):

ds_2col_fluid:
  label: Fluid two column layout
  category: Display Suite
  class: '\Drupal\ds\Plugin\DsLayout'
  type: partial
  template: templates/ds-2col-fluid
  library: ds/ds_2col_fluid
  icon: images/ds-2col-fluid.png
  regions:
    left:
      label: Left
    right:
      label: Right

label defines the label that's displayed when you're selecting your layout on the Manage Display screens.

category defines the option group that your layout appears in on the Manage Display screen. It can be helpful to use My Module or My Theme here to group all layouts defined by your module or theme.

class I've never had to change this to anything else to anything other than \Drupal\ds\Plugin\DsLayout

type I've never set this to anything other than partial. I'm not sure what the other options are.

template defines the template file to use. This should be the relative path, from your module or theme, to the template.

library allows you to load a drupal library as a dependency when you're layout is being rendered. Add js or css that you may need.

icon defines the path to the icon that appears on Manage Display screens to represent your layout.

regions define the regions of your layout.

As far as I know you don't need to include the icon or library parameters and it won't cause any errors.

Your template file will have variables for content, attributes, html element for each region, layout and outer wrapper. See ds/templates/ds-2col-fluid

Here's an example for how you can render a region you defined in your layouts.yml file (taken from ds/templates/ds-2col-fluid):

{% set left = left|render %}
{% if left %}
  <{{ left_wrapper }}{{ left_attributes.addClass('group-left') }}>
    {{ left }}
  </{{ left_wrapper }}>
{% endif %}

If you define your layouts and templates in a module file, you can later override the templates in a theme if needed, as you can with any standard template in drupal.


How to use Form API and and node_submit to insert taxonomy data I have a content type with a number of text fields and a field linked to a taxonomy vocabulary with about a dozen terms.

I have successfully developed code using the Form API to insert data from my custom form into my node using node_submit for the text fields.  A sniped of the code I use is for the text fields is:

$node->field_s_phone[$node->language][0]['value'] = $form_state['values']['phone'];
$node->field_s_email[$node->language][0]['value'] = $form_state['values']['email'];

node_submit($node);
node_save($node);

I would like to implement a single set of checkboxes of my vocabulary terms on the custom form, then pass the values using node_submit in a similar fashion to the text fields (sort of like):

$node->field_catagories[$node->language][0]['value'] = $form_state['values']['catagories'];

I would be grateful for any thoughts or insight.

Thanks,
Bill

Try this, if I completely understood you, this should help.

    $i = 0;
    foreach($form_state['values']['catagories'] as $tid) {
      $node->field_catagories[$node->language][$i]['tid'] = $tid;
      $i++;
    }


Adding images to a node Is there a way to programmatically add an array of images from a particular file path? I want to add all the images from one folder in my drupal site and add fancybox styling to them. Can this be done? I've tried looking on drupal.org with no success.

If by 'programmatically' you mean using PHP, then there seem to be two good options.

Create a template file, include the fancybox library if not already loaded, load the file path/names from your image directory into an array, tweak the array as needed, and call fancybox with the paths in your array.
Create a custom module that does essentially the same thing, but here you can also add an admin view to manage the images, set custom permissions, etc.


Caching problem. Site only works with cache off I have this drupal 7 site.
I wanted to clone it in order to try some new stuff in it, without working on my localhost. So I did it, following these steps:

Cloned the database:

mysqldump -h localhost -u XX -p XXX > backup.sql
mysql -h localhost -u newXX -p newXX < backup.sql

And then cloned the files and changed their perms:

rsync -avHl /home/XX/public_html/* /home/newXX/public_html
chown -R newXX. /home/newXX/public_html/*

After that I've updated and changed the settings file (to use in the cloned files the new database credentials), and created a new .htmlaccess file.

All went well and good. The new site was just like the older site, and both sites were running ok.

A few days have passed since then.

But after that the old site have all WSOD inside every page, except the frontpage.

It was a cache problem, that didn't solved clearing all cache tables, but adding this into my settings file:

$conf = array(
'cache' => '0',
'preprocess_css' => '0',
'preprocess_js' => '0',
'block_cache' => '0',
'page_compression' => '0',
);

The thing is that I can't have my site without caching, and even after successfully logging in and manually unchecked all cache items under admin/config/development/performance, I get the WSOD if I try and remove the $conf array I've manually set at the settings.php file.

Note: I have memcached installed on my server, and this is what I've added in my settings.php file:

$conf['cache_backends'][] = 'sites/all/modules/memcache/memcache.inc';
$conf['cache_default_class'] = 'MemCacheDrupal';
$conf['memcache_key_prefix'] = 'memcache_liga';
$conf['cache_class_cache_form'] = 'DrupalDatabaseCache';

Please note that I've uninstalled memcache module on the cloned site, and deleted that configuration inside the settings file of the cloned site.

Why is all this happening? And what I may do about this?

Update: I forgot to mention that I've added to my index.php right after the opening php tag, this:

error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

And when the error appears (WSOD), the page is still completely blank!

Here is how I do in my local projects, may be it can help you.

I have one main project(local) and four its instances(cloned). Same files, same db structure (I'm using Memcache Storage module).. First time when I've tried to clone and work on them I faced some strange problems, then I found that they were sharing cached data (I was using default memcached instance with 11211 port).. Then I just copied the default memcached.conf file as memcached_1.conf(memcached_2.conf,...) and changed their port as 11212,... in them, restarted all memcached instanes(sudo service memcached restart), and specified those ports to to my cloned projects in their settings.php, that solved my problem..


How to pass variables into link path within l() function? I am wondering how to pass variables into a the path argument for a link created with l(). The path looks like registration-history/listing/$node->nid/$sku/$node->created/$start_date And the link text is in $registration_count.

Some Examples

Example 1: Link to front page

<?php
// example 1:  front page
print l(t('Home'), '<front>');
?>

Example 2: Link to front page and open in new window

<?php
print l(t('Home'), '<front>',array('attributes'=>array('target'=>'blank')));
?>

Example 3: How to use html

<?php
print l('Home', '<front>',array('html' => TRUE));
?>

Example 4: How to use image instead of text link

Lets create my picture path

<?php
global $base_url;
$path = "$base_url/sites/default/files/ceo5.png";
print l('', 'sites/default/files/ceo5.png', array('html' => TRUE));
?>

Example 5: Add class, ids, etc

<?php
// add a new class to my php ini configuration path
print l(  t('PHP ini configuration'),  'node/3',  array('attributes' =>array('class'=>'php-ini-conf', 'id'=>'phpini-conf') ));
?>

Example 6: Adding query string to links

Adding a query string to example 5

<?php
// adding query string on example:5
print l(  t('PHP ini configuration'),  'node/33',  array('attributes' =>array('class'=>'php-ini-conf', 'id'=>'phpini-conf'), 'query'=>array('id'=>'5','status'=>'ok') ));
?>

The output will be:

http://webemania.com/blog/php-ini-configuration?id=5&status=ok

Example 7: Adding destination to query link

<?php
print l(  t('edit'),  'node/'.$nid.'/edit',  array('query' => drupal_get_destination() ));
?>

Example 8: Create a hash-only link (to #)

<?php
print l('linktext', '', array('fragment' => ' ', 'external' => TRUE));
?>

Example 9: Specific portions of a page

Use fragment attributes Go to php ini configurations short open tag portion: PHP Short open tag

<?php
l(  t('PHP ini configuration'),  'node/33',  array('attributes' =>array('class'=>'php-ini-conf', 'fragment' => "php-tag")));
?>

References:

How and why to use l() function to create links in Drupal


Using slashes in drupal path parameters I'm working on my first module. I'm setting up hook_menu() to register several URLs. Some of the parameters may be raw strings with slashes in them. For example, "Round 1 / Heat 1" as one parameter. Now, I know that I can make my javascript encode the slashes when constructing the URL, but it makes me wonder if I'm Doing It Wrong™.

It feel natural to me to be able to use GET params, but I don't see any way to access those in menu callbacks.

Am I doing It wrong with these URL-based parameters?
Is it possible to just POST these parameters, and access them in menu callbacks?

There's one additional trick additionally to the options that you already listed. If you look at search_menu(), you can see that it uses a named placeholder called %menu_tail and this: 'load arguments' => array('%map', '%index'),.

This does exactly what the name suggests. It calls menu_tail_load() (and passed it's own index/position to it as a load argument), which doesn't actually load anything but takes all additional path elements including it's own position,  and returns them as a single argument.

Obviously, this only works for the last argument. If you have multiple arguments like this, use GET/POST variables or escape them.


Create a field (defined within same module) during module installation? Having this code:

function mymybase_update_7200(){
    if(!field_info_field('field_timer_exam')){
        $field = [
            'field_name'  => 'field_timer_exam',
            'label'       => 'Countdown timer',
            'type'        => 'mymy_field_countdown',
        ];
        field_create_field($field);

        $instance = [
            'field_name'  => 'field_timer_exam',
            'entity_type' => 'user',
            'bundle'      => 'user',
            'label'       => 'Countdown timer',
            'settings'    => [
                'user_register_form' => 0,
            ],
            'widget'      => [
                'type'      => 'mymy_field_countdown_widget',
                'settings'  => [
                    'display_label' => TRUE,
                ],
            ],
        ];
        field_create_instance($instance);
    }

    if(!field_info_field('field_timer_final_exam')){
        $field = [
            'field_name'  => 'field_timer_final_exam',
            'label'       => 'Countdown timer',
            'type'        => 'mymy_field_countdown',
        ];
        field_create_field($field);

        $instance = [
            'field_name'  => 'field_timer_final_exam',
            'entity_type' => 'user',
            'bundle'      => 'user',
            'label'       => 'Countdown timer',
            'settings'    => [
                'user_register_form' => 0,
            ],
            'widget'      => [
                'type'      => 'mymy_field_countdown_widget',
                'settings'  => [
                    'display_label' => TRUE,
                ],
            ],
        ];
        field_create_instance($instance);
    }
}

Which i think it is ok, field get created when running in the hook_menu page callback for example, but during installation the fields does not get created.

There is no error in the watchdog nor in apache logs, the field does not exist in the user entity nor tables like field_data_field_timer_exam

The update get fired, at system table i can see the schema_version columna get updated for my module

What could be happening?

The function hook_update_N() only gets called by running update.php. You also need to implement a hook_install(), for example like this:

function mymybase_install() {
  mymybase_update_7200();
}

Do note that this only runs when you enable the module for the first time. So if you already enabled the module, you can test this by first disabling it and then uninstalling it. If you want to run the function each time the module is enabled, you should use hook_enable().


Add search to the Drupal 7 find content By default drupal 7 find content page comes with filter by type and status. I wanted to give one more filter, where user can type the few letters from the title they are looking for so that they can find the article/page with ease even when theres 100's of content in the site.

I did something similar using views and exposing title as a filter. But it would be great to add this field and search to the default filters we find in the drupal 7 find content page.

Try the Administration Views module:

  Replaces administrative overview/listing pages with actual views for superior usability.

It will let you replace the standard content admin page with a view, to which you can add as many filters as you need.


Different Feeds Tamper per destination in mapping I have a csv feeds importer I'm trying to build where I would like the last 2 digits of a code to be mapped to the task code field, but the full 4 or 5 digit number be mapped to the GUID.

From the interface I can only see a way to run the tamper on the source field for all destinations.  Is there some way I can tamp in different ways for different destination fields?  (or tamp for one destination, and use the raw value for another)

First thing this morning, I realized what Map to multiple fields using 'Blank source' in the documentation means.  I was able to have Task Code as my source for GUID, then Blank Source 1 as my source for Task Code.

In the tamper for Blank Source 1 I use Copy Source Value before doing my other transform:


Is there any way to know if it is the first visit of a Anonymous User? I'd like to know if is there any way to know if it is the first visit of a Anonymous User?

If so, can I fire up a rule to redirect the visitor to other page.

Why not set a cookie when folks visit, then you can check for whether they have the cookie. No cookie = first time visitor.