limit validation button on visible state textfield? Suppose I had a selectbox with 2 options. One option enabling the visible state of one field, while the other disables that state and makes a different text field visible.

If I had a button that has limit_validation_errors, how would one go about validating only the field whose state is visible?

Currently my setup looks like the following:

$form['unit'] = array(
  '#type' => 'select',
  '#options' => array(
    0 => '€',
    1 => '%',
  ),
  '#default_value' => 0,
);

$form['price-percentage-field'] = array(
  '#type' => 'textfield',
  '#title' => t('Price'),
  '#description' => t('Set the percentage discount price for this volume set'),
  '#size' => 10,
  '#element_validate' => array('price_percentage_validate'),
  '#states' => array(
    'visible' => array(
      ':input[name="unit"]' => array('value' => 1),
    ),
  ),
);

$form['price-field'] = array(
  '#type' => 'textfield',
  '#title' => t('Price'),
  '#description' => t('Set the price for this volume set'),
  '#size' => 10,
  '#element_validate' => array('price_validate'),
  '#states' => array(
    'visible' => array(
      ':input[name="unit"]' => array('value' => 0),
    ),
  ),
);

$form['add'] = array(
  '#type' => 'submit',
  '#value' => t('Add'),
  '#name' => 'add_row',
  '#limit_validation_errors' => array(
    array('price-field'),
    array('price-percentage-field'),
  ),
  '#submit' => array('add_volume_standard'),
  '#ajax' => array(
    'callback' => 'add_volume_standard_ajax_callback',
    'wrapper' => 'error-placeholder', //<- this here is for my custom error-placeholder that will contain the form_errors nicely in a div using a few ajax_commands and form_states
    'method' => 'append',
    'effect' => 'fade',
  ),
  '#title' => t('Click this button to add a standard volume price'),
);

When using this code, both fields will always be validated. While I want to only validate the visible field. How can I do this?

Also, a validation function is not my preferable approach. I have my reasons.

I would personally prefer a form-validation-function, which seems for me the ideal solution...
But since you're using custom validators, you can check the value of your unit-field in there:

The second argument in your custom element-validation-function is the form_state-object, with that you have access all form-values. (eg. $form_state['values']['unit'])
Check the value of the unit-field in both validation-functions, depending of it's state do or skip the validation.

Example:

   function price_percentage_validate($element, &$form_state, $form) {
        if ($form_state['values']['unit']>0) {
            /* your validation code */
        }
    }
   function price_validate($element, &$form_state, $form) {
        if ($form_state['values']['unit']<1) {
            /* your validation code */
        }
    }


Change the front page basing on the domain I need to write a custom module to map some static pages used as front page to some specific domains. For example,

If domain is www.abc.com, the front page should be static_page_1
If the domain is www.bcd.com, the front page should be static_page_2

I have made a form for administrator users to enter the domain name and the static page they want as front page, but now I don't have any idea on where and how to write the code for detecting the domain name and set the front page.
Any information and suggestion will be very appreciated.

I've already find the answer by referring to Programmatically set the front page per site?. It is much simpler than the reference, because I just want to map the domain with my static page and I don't have a multisite drupal.
So, I just add an event subscriber and put all the mapping there.

  In the getSubscribedEvents method you need to set the weight to something greater than 30 which overrides the Page Cache and Dynamic Cache.

$events['kernel.request'] = ['kernel_request', '35'];

  Add this function in the same event subscriber file

public function kernel_request(Event $event) {
$config = \Drupal::configFactory()->getEditable('system.site');
$site_path = \Drupal::service('site.path');
$site_path = explode('/', $site_path);
$site_name = $site_path[1];

if ($site_name === 'site2' && $event->getRequest()->getPathInfo() == '/') {
  $config->set('page.front', '/node/239')->save();
}
else {
  $config->set('page.front', '/home-content')->save();

}
}


Copy same content date fields values to separate content types by rules What i want to do is this...

I have a content type (A) with two date fields (date_1 and date_2)
Then i have two more content types with existent date_1 field created.
(Must be this way)

Schema:
A: date_1 and date_2
B: date_1
C: date_1

An existing rule creates (every time a new node of content type A is created) a new content node of type B, copying the A:date_1 value to the B:date_1 value. That was easy... and it works just perfect.

Now, what i want to do is the (almost the) same with the content type C.
Except for the source field to be copied, that should be date_2

The rule should be something like this:
"Every time a node of content Type A is created:
Create a new node of content type C
and copy the date_2 value from node A, then paste it into the new entity field date_1...

Almost the same, except that when i want to select the source field, date_2 is not listed and i cant select him.

Is there any way to solve this?

Thanks a lot

field: date_2 is not listed because of a field configuration mismatch between both fields.
Everything MUST match between them.


read webforms fields in a mobile app and write submissions to the site database I have a courses site where students take online courses and then take exams and get their certificates.

The courses content type has an entity reference to "Lessons" content type which has a further reference to Exams content type ( Webform).

The progress of user is being stored in a custom table in database.

Now we need to build a native mobile app with login / registration, and taking courses and exams features. (user registration / login  and progress should be synced with site database)

Any ideas to start with? Custom API, web services or reading and writing to database directly.

thanks

I believe services will fulfill your needs. You can try with  Services module.

You may require to customize the module for your custom made features in the site.


anchor (#) in url alias I want to open same page from different contents. So I need to generate link like /testimonials#group-1 for these contents. I used pathauto module for this. I made pattern for this category testimonials#[node:title]. But this URL get encoded by browser /testimonials%23group-1 and it gives me no page found error.

So how can I put anchor (#) in URL alias which can give me output like /testimonials#group-1.?

I think you are trying to add anchors to a node's alias to define multiple sections in a node, which is impossible since an anchor destination is not part of a path and therefor not part of an alias. For more information, see the W3 introduction on links in HTML.

Creating a anchor: If you would like to subsection your node's body, you should use anchors in your code:

 ...

If you're using the WYSIWYG module, make sure you've got the Anchor plugin enabled, so you can create the anchors through the nicely builtin anchor plugin's GUI, which makes it that much easier.

Linking to an anchor: After creating an anchor, you can link to that section by making a hyperlink as follows:

Link text

To build the above link in the Drupal-way:

<?php print l('Link text', 'path/to/node', array('fragment' => 'anchorOne')); ?>

Or to only build the URL including the anchor destination:

<?php print url('path/to/node', NULL, 'anchorOne'); ?>


Drupal Module for Zoom Print and Save I would like to ask about finding a particular module on Drupal. I need to add "Zoom", "Print", and "Save" functionalities.

I am sure there must be a module to handle this. Is there any solution about which module I should use? For your information, I am using Drupal 7 and need to add the functionality to Views page.

I'm not sure what do you mean by zoom!! Image zoom or text resize?

Anyways you need to install 3 modules

for image zoom use deepzoom
for text resize use textsize
for print and save use Printer, email and PDF versions


Flexible addons for Solr to achieve sorting and filtering My requirement is to provide end user with an option to sort/filter the search results. This can be achieved different ways but I am unclear to choose one. I found these methods.

Using facetapi - I can filter results, not sure about sorting.
Using apachesolr_sort - I can group/sort results, not sure about filtering.
Using apachesolr_views - I can show my results more flexible this way. But this doesn't seem to support sorting https://www.drupal.org/node/443410.
Using search_api and search_api_solr - This method is more preferred and flexible to group/filter/sort results. But I am worried about heavy size of these modules.

Can someone suggest me to achieve the most flexible (and less resource consuming) method of sorting/filtering results by any combination of the above modules.

Thanks!

Search API includes Views integration out of the box. Definitely you will need Facets Api. this combination is the best for Solr integration with Drupal. Here is a great screen-cast that might help.


Hooking into the user login block to modify prefill default text in username and password I am having problems getting a custom module to recognize the user login block.

Ultimately I need my user login block to only show the username and password fields, without any labels. Instead of labels I need to prefill the form fields with the words 'username' and 'password' and have this text disappear onfocus. This drupal answers question demonstrates how to do this with the search block and a custom module. I have been able get this to work without any problems.

I have tried to do a similar thing with the user login block.

First of all i used this to get the form id:

function custom_prefill_login_form_alter(&$form, $form_state, $form_id) {

 // uncomment to get form id
 drupal_set_message("Form ID is : " . $form_id);
 }

This returns Form ID is : user_login_block for the login block page
and
it returns Form ID is : search_block_form for the search block

When on a page with the search block enabled I can use this:

if ($form['#id'] == 'search-block-form') {
    dpm('search-block-form showing');
}

but when on the user login block page this doesn't work. Neither of these show anything in the message area:

 if ($form['#id'] !== 'user-login-block') {
     dpm('user-login-block showing');
 }

 if ($form['#id'] !== 'user_login_block') {
    dpm('user_login_block showing');
}

I am very confused as to why this isn't working. I would appreciate being shown how to write an if statement that targets the user login block.

My entire function is:

function custom_prefill_login_form_alter(&$form, $form_state, $form_id) {

    // uncomment to get form id
    drupal_set_message("Form ID is : " . $form_id);

    if ($form['#id'] !== 'user-login-block') {
          dpm('user-login-block showing');
      }

    if ($form['#id'] !== 'user_login_block') {
          dpm('user_login_block showing');
      }

    if ($form['#id'] == 'search-block-form') {
          dpm('search-block-form showing');
          $search_text = 'Your search text here';
          $form['search_block_form']['#default_value'] = $search_text;
           $form['search_block_form']['#attributes'] = array(
          'onfocus' => "if (this.value == '$search_text') {this.value = '';}",
          'onblur' => "if (this.value == '') {this.value = '$search_text';}");
      }

  }

To target a specific form you can use hook_form_FORM_ID_alter(), e.g.:

function MYMODULE_form_user_login_block_alter(&$form, &$form_state, $form_id) {
  $form['foo']['#default_value'] = 'bar';
}

If you'd rather do it all in one alter hook though, use the provided $form_id parameter instead of $form['#id']...it's guaranteed to be the right one.

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_login_block') {
    $form['foo']['#default_value'] = 'bar';
  }
}

As a side note, it's probably not working at the moment because you're negating the condition:

if ($form['#id'] !== 'user-login-block') {

should be

if ($form['#id'] === 'user-login-block') {


Do we need hash in Config Sync Directory if outside root If we set the config directory to be outside root and plan on committing the configuration to git, do we need (or is it recommended) to use hash in the config folder name?

The only purpose of the hash is to make it impossible to guess the location of the exported config. This is an additional access control in case .htaccess in the sync folder fails to do this.

If the config folder is outside of the root of the webserver you don't need the hash.


file_copy() is not working I have the following code.
$main_image = glob('main*.{jpeg,gif,png,jpg,JPEG,JPG,PNG}', GLOB_BRACE);
if (count($main_image) != 1)
    die("Could not find main picture !");

$file_path = drupal_realpath($main_image[0]);
$file = (object) array(
            'uid' => $userID,
            'uri' => $file_path,
            'filemime' => file_get_mimetype($file_path),
            'display' => 1,
            'filename' => $main_image[0]
);
// copy the file in the correct folder
$destination = "public://galerii_imagini/" . $file->filename;
 if ($file = file_copy($file, $destination, FILE_EXISTS_REPLACE)) {} else {
    die("Could not copy " . $file_path . " in " . $destination);
}

Is there something wrong with my code? I always get the message from die command inside the last if statement.
Any help will be appreciated.
Edit: Thanks to Stanislav Agapov, I found the logs from drupal.
The message is:

File ..../main_ROSE2106.JPG
could not be copied, because the destination directory
public://galerii_imagini is not configured correctly.

What should I do to configure it correctly? I have set in /admin/config/media/file-system the path sites/default/files as public files.
Is there something else to set?
Edit #2:
I set 777 for the whole /sites/default/files tree.

Are you certain that the path sites/default/files/galerii_imagini  exists and is a directory? You could see this error either if it doesn't exist or if it exists but is a file instead of a directory. If you expect Drupal to create the galerii_imagini directory, you need to add this line before your call to file_copy:

file_prepare_directory("public://galerii_imagini", FILE_CREATE_DIRECTORY);

Based on a search of the Drupal 7.x source code, the message File %file could not be copied, because the destination directory %destination is not configured correctly. is only ever produced in file_unmanaged_copy, which is called by file_copy. It calls file_prepare_directory first on the destination as passed to file_copy, then on its parent directory. It produces the error message you're seeing only if both calls fail. Since it calls file_prepare_directory with default flags, it can fail with that message if:

neither the destination path nor its parent directory exists
the destination path does not exist and its parent directory exists but is not a directory
either the destination path or its parent directory exists, is a directory, is not writable, and changing its permissions to make it writable failed

In the last case, however, you would see another message in the log immediately before the one you reported in your question: The file permissions could not be set on %uri. Since you haven't reported seeing that message, I can only assume that one of the first two cases is correct.


Remove Administration Theme from user/%/edit I want the administration theme for all the default pages, except one: /user/%/edit

How do I get the default theme to display for this page instead of the administration theme?

For Drupal 7 you can use Administration theme or hook_admin_paths_alter() in your custom module.

/**
 * Implements hook_admin_paths_alter().
 */
function my_module_admin_paths_alter(&$paths) {
  $paths['user/*/edit'] = FALSE;
}

For Drupal 8, see https://www.drupal.org/node/2224207.


What do I need to create a custom form widget? I used hook_field_widget_info() and hook_field_widget_form() to create a new widget for the user reference module. The problem is when I select a value in content edit form using my widget, selected value is not shown in node display page. Also when I go back to the edit form, my selected value is not the default value(is not saved).

Does it need anything else to work properly?

function mymodule_field_widget_info() {
    return array(
       'custom_user_widget' => array(
            'label' => 'Custom user widget',
            'field types' => array('user_reference'),
            'behaviors' => array(
                'multiple values' => FIELD_BEHAVIOR_DEFAULT,
                'default value' => FIELD_BEHAVIOR_DEFAULT,
            ),
        ),
    );
}
function mymodule_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
    if ($instance['widget']['type'] == 'custom_user_widget') {
        $element['uid'] = array(
            '#type' => 'select',
            '#options' => array(1=>'a', 2=>'b', 3=>'c'),
            '#title' => t('Username')
        );
        return $element;
    }
}

You need to implement the "view hook":

/**
* Implements hook_field_formatter_view().
*/
function mymodule_field_widget_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
    $element = array();

    switch ($display['type']) {
    case 'custom_user_widget':
    $element[] = 'add here what you want to show';
    break;
    }
    return $element;
}


Drupal Commerce Payment Confirmation I'm using the Drupal Commerce module (http://www.drupal.org/project/commerce) along with the touchnet upay module (http://www.drupal.org/project/commerce_touchnet_upay).  I've been able to set it up so when a user clicks checkout, they are redirected to the touchnet site and are successfully able to pay.  However, there's nothing on the Orders page that shows that the Order is complete, they still say Checkout:Payment under Order Status.  This is the status of the orders that have gone to the payment site but did not pay as well as the ones that actually paid.

Does anyone have experience with using Touchnet and Commerce and can tell me how I can get this to change to Payment:Complete or what Touchnet sends to my site and how I can capture that so I know that the order was actually paid for?

Thanks for the help!

I believe you have to use the Rules module and create a new rule.

Use react on: after payment is received/complete (or something along those lines)

Then use add action >> set a data value >> (find your order status field token)


Clear cache doesn't clear the cache tables? I don't fully understand the Clear Cache action. I just click in clear cache Clear All caches in: admin/config/development/performance , then I go to the database to check all cache_... tables and I find that none of them are empty.

Is this normal?
Can I just truncate all cache_... tables?

In fact I just need to clear cache_form. Can I truncate this table?

Can I just truncate all cache_... tables?

You should not truncate the "cache_form" table, as it contains the data used from Drupal to validate them; if you delete that table, the form currently being submitted from the user would be invalidated, and the users would need to submit the form again.

There could be some other cache tables that cause a module to act strangely. That is the reason modules that are using extra cache tables (whose name generally starts with "cache_") are supposed to implement hook_flush_cache() to return the cache tables that can be cleared from Drupal, and which is then called with the following code, from drupal_flush_all_caches().

  $core = array('cache', 'cache_path', 'cache_filter', 'cache_bootstrap', 'cache_page');
  $cache_tables = array_merge(module_invoke_all('flush_caches'), $core);
  foreach ($cache_tables as $table) {
    cache_clear_all('*', $table, TRUE);
  }

drupal_flush_all_caches() is the function called from system_clear_cache_submit(), the submission form handler called when you click on the "Clear all caches" button, in the performance settings page.

During cron tasks, system_cron() clears the cache using the following code.

  $core = array('cache', 'cache_path', 'cache_filter', 'cache_page', 'cache_form', 'cache_menu');
  $cache_tables = array_merge(module_invoke_all('flush_caches'), $core);
  foreach ($cache_tables as $table) {
    cache_clear_all(NULL, $table);
  }

As the first argument of cache_clear_all() is NULL, the code executed in DrupalDatabaseCache::clear() (Drupal 7) is the following one.

if (variable_get('cache_lifetime', 0)) {
  // We store the time in the current user's $user->cache variable which
  // will be saved into the sessions bin by _drupal_session_write(). We then
  // simulate that the cache was flushed for this user by not returning
  // cached data that was cached before the timestamp.
  $user->cache = REQUEST_TIME;

  $cache_flush = variable_get('cache_flush_' . $this->bin, 0);
  if ($cache_flush == 0) {
    // This is the first request to clear the cache, start a timer.
    variable_set('cache_flush_' . $this->bin, REQUEST_TIME);
  }
  elseif (REQUEST_TIME > ($cache_flush + variable_get('cache_lifetime', 0))) {
    // Clear the cache for everyone, cache_lifetime seconds have
    // passed since the first request to clear the cache.
    db_delete($this->bin)
        ->condition('expire', CACHE_PERMANENT, '<>')
        ->condition('expire', REQUEST_TIME, '<')
        ->execute();
    variable_set('cache_flush_' . $this->bin, 0);
  }
}

The code removes only the rows, which are not marked as permanent, and are expired, from the tables returned from hook_flush_caches(), and from various cache tables used from Drupal, including "cache_form." There should not be too much rows in "cache_form"; if that happens, you can reduce the time passed between two consecutive executions of the cron tasks, or execute the following code from a custom module.

cache_clear_all(NULL, 'cache_form');

An alternative is to manually cause the cache to be cleared, using the Devel module, and the menu link it shows.


Getting the taxonomy parent term as Views argument I am trying to get a taxonomy parent name with this code; when I put 1 as the argument, I keep getting the ID, but when I try using 2, I get a error. It should wor,k but it keeps throwing the error back at me. I am trying to get the parent name, not the ID.

$view = views_get_current_view();
print $arg0 = $view->args[2];

  Notice: Undefined offset: 2 in __lambda_func() (line 3 of /home/loansdotorg/public_html/modules/views_php/plugins/views/views_php_handler_area.inc(39) : runtime-created function).

I believe that Views uses $view->args to store the arguments it has received from the url, or passed to it when embedded.

So in the above case, you would need a url structure where the parent term is located in the views url after the actual term. Most likely this is not the case.

If you want to get the parent term you can use the function taxonomy_get_parents


UTMs stopped being caught on webform submission Forms has hidden inputs in the components to collect UTM values from the URL.

Once the form was filled in, the submission appeares correctly in the results table, both the public fields like the name, surname, etc ... as the content of the utm.

Recently, the new forms created do not store utm values, not even the cloned forms of a functional form.

Identical forms, in some takes the UTMs (forms with some time), in others not (created / cloned recently). Even shown in the same view.

I have tried to see with the devel module  if there was a failure when interpreting the forms or the hidden fields ... without result.

Any idea or direction where the problem could go?

Thanks for your time.

The answer here provides the method you can use to pass URL query variables into hidden fields in webform.

What you need to do is assign a default value to each field which uses a token representing the query variable. So, for example, the field for "utm_unidad" should have a default value of:

[current_page:query:utm_unidad]

And so on for the other fields.


Why does Drupal jump back to the calling function after submitting a form? Dear Drupal community,

I am pretty much lost with the form listed below. When calling the form funnyform via the function funny_function (via the menu link 'Funny'), the form appears, and the word 'Fun' is displayed as I programmed. Now, when I click on the 'Resume' button, the word 'Submitted' is obviously displayed. However, the word 'Fun' appears as well. Apparently, Drupal goes back into this function once again! Now, this is very bad news because in my "real-life" this function contains additional programming code which is then run twice...

Can anybody please help me how to stop Drupal from going back there? And explain to me why it even does so??

Thanks and best wishes, Tobias

$items['funny'] = array(
  'title' => t('Funny'),
  'page callback' => 'funny_function',
  'access callback' => TRUE,
  'type' => MENU_NORMAL_ITEM,
);

function funny_function() {
  drupal_set_message('Fun');
  return drupal_get_form('funnyform');
}

function funnyform($form, &$form_state) {
  $form['information'] = array(
    '#markup' => t('Nothing'),
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Resume'),
    '#weight' => '100',
  );
  return $form;
}

function funnyform_submit($form, &$form_state) {
  drupal_set_message('Submitted');
  $form_state['redirect'] = 'another_funny_page';
}

Where else would you expect the form to lead?

You can add ?destination=somepath to the URL, or a #redirect to the submit array, or a drupal_goto in the funnyform_submit() function, but if you don't tell Drupal where to go, it's just going to reload the current page.


How to raise Notifications on new discussion posts? How do I enable notifications for a user who subscribes to a Discussion Post section so that the user gets a notification when a new discussion topic is created by another user?

The notification should show up on his profile dashboard as well as sent by email.

Presently, the user dashboard has the block View - Open Atrium Content - Recently Updated Subscribed Content, but this block only shows updates for new comments on specifically subscribed content topics, not new discussion topics.

You can use Flag module to create "subscribe button" on any content (forum category, post or comment) and then Rules to create rule:

what reacts to new content
then load parent entity (if new post, load it's category)
load all flaggings on it
send e-mails to authors of all flaggings OR create notification (so you can show them on some dashboard)

There are also modules specialized for subscribing to content and then send notifications, but they usually are not so flexible like solution based on Rules.


Omit front page in Bartik theme Hey I am using the Empty Front Page module https://drupal.org/project/empty_front_page on a sub-theme(Bartik) but the problem is that when I open my domain I see an empty screen and none of the tabs are open. Can I somehow omit this empty page and direct the user to the home tab of the website meaning www.example.com to example.com/home?

PS: I am new to php and Drupal!

I will present a solution for empty front page here with help of views module.

You can create or use a content type which you are not intended to use. Either you can create one or use article etc.

Create a views with selecting that content type & set other things such as no pager & 0 posts, so that this views doesn't produce any result.

Give it a name such as home & make a page with same name.

Go to your site configuration & set this home as front page path. You are done.


hook_node_update not working I placed the following function in my custom module.

function MYMODULE_node_update($node) {
  if ($node->type === 'page') {
    $node->title = 'test';
  }
}

When editing and saving a node of content type page nothing happens. What can be the issue?

Problem solved. It seemed to be caused by the following:

my custom module wasn't ending with ?> and above all my module name was custom_site.module and my hooks started with custom. This didn't give problems before with my other hooks so I never noticed. (This helped: https://drupal.stackexchange.com/a/111272/85560)

My module name now is custom.module and now custom_node_presave() works.

You should use hook_node_presave if you want to change a field's value as the hook is invoked from node_save() before the node is saved to the database. And as leymannx stated, make sure you clear the cache before implementing a new hook.


Hide url in subdirectory install? in my site I use version 7 of Drupal and Linux OS on the server, and need to hide the subdirectory of the installation when access by LINK ...
explaining better:
Current link: www.site.com/folder
I want to change for only:
www.site.com
I searched in various forums, websites and how is an old subject, I believe that there was a change in the code to hide / delete the symbolic url paste ...
In the folder / root .htaccess I created left like this:

Options + FollowSymlinks
RewriteEngine On
RewriteRule ^ (. *) $ Folder / $ 1 [L]

Thus, to access the site, only the index remains without the folder ... I want the whole site be without referencing the subfolder where it was installed ... How do I do this? thank you

Add this rewrite rule in your .htaccess file:

RewriteEngine On
RewriteRule ^/subfolder/(.*)$ http://www.example.com/$1 [L,R=301]

Change subfolder and www.example.com.

Also, you can try with this:

RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^ http://%1%{REQUEST_URI} [NE,R=301,L]

RewriteCond %{HTTP_HOST} ^(www\.)?example\.com$
RewriteRule !^subfolder/ /subfolder%{REQUEST_URI}  [L]

Again change you domain and subfolder name.


How to shadow a core function used in two different tests files? I have two tests files with tests that need to shadow the t() function in the Node Revision Delete project, one test file is placed in:

tests/src/Unit/Utility/TimeTest.php

And the other in:

tests/src/Unit/NodeRevisionDeleteTest.php

At this time I shadow the t() function with the same code at the end of each test file because the t() function is needed to run tests in both files.

namespace Drupal\node_revision_delete\Utility;

/**
 * Shadow t() system call.
 *
 * @param string $string
 *   A string containing the English text to translate.
 *
 * @return string
 *   The translated string.
 */
function t($string) {
  return $string;
}

When I run each test file all is working fine, but when I run all the project tests I get an error as I have declared the t() function twice:

  PHP Fatal error:  Cannot redeclare
  Drupal\node_revision_delete\Utility\t() (previously declared in
  /Users/adriancid/Sites/drupal84-test/modules/drupal.org/node_revision_delete/tests/src/Unit/NodeRevisionDeleteTest.php:357)
  in
  /Users/adriancid/Sites/drupal84-test/modules/drupal.org/node_revision_delete/tests/src/Unit/Utility/TimeTest.php
  on line 195

The only way that I found to make these works is to pass the tests that need the t() function from one test file to the other, but doing this I will have a mix of tests from diferent classes and I won't be able to use the @covers section in the test definition.

So, what is the correct way to shadow a core function used in two different tests files?

Wrap it in a !function_exists()

See core/tests/Drupal/Tests/Core/Render/Element/MachineNameTest.php for example:

<?php

namespace Drupal\Core\Render\Element;

if (!function_exists('t')) {

  function t($string, array $args = []) {
    return strtr($string, $args);
  }

}

That said, t() as a specific example is deprecated and should not be used in classes, use the StringTranslationTrait/service instead and you can actually inject it.


How to save webform submissions data in fields using rules module I used the answer in my last question Override webform module submit
to create node after webform submissions.

My webform contains many components like phone, address, responsible and others.

How can I save this data in fields tables?

Let's say that my webform contains the components: phone, address, city ..

I created a new content type that contains these fields: phone, address, city ..

Then, for each field I added

{ "variable_add" : {
      "USING" : { "type" : "text", "value" : "[data:address-value-raw]" },
      "PROVIDE" : { "variable_added" : { "var_address" : "Address label" } }
    }
  },

Where address is my MachineFieldName

and

  { "data_set" : {
      "data" : [ "article-created:field-address" ],
      "value" : [ "var_address" ]
    }
  },

To check your data as [ "article-created:field-address" ]

go to admin/config/workflow/rules/reaction/manage/rules_create_a_node_from_webform_data
go to add action and select set a data value
in the Data selector *: select article-created:...(Created article) Then you will see all your fields..

This answer to How to create a node from a Webform using rules? helped me..

I hope that can help someone..

Thank you


Why we need different menu item types? While I was studying hook_menu, I came across menu item types and I found that there are 6 types of menu item types as follows :

1] MENU_CALLBACK

2] MENU_DEFAULT_LOCAL_TASK

3] MENU_LOCAL_TASK

4] MENU_NORMAL_ITEM

5] MENU_LOCAL_ACTION

6] MENU_SUGGESTED_ITEM

I have read the documentation on Drupal.og and doc says that we have different application of each menu item type.

But I am not able to differentiate when to use which menu item type?
can I anyone help me to understand that which menu item type should be used ?

If any one explains use of each menu item type with example then it will be appreciated.

I realize this is a bit late, but just in case it helps anyone who stumbles across this...

1) MENU_CALLBACK - Menu callbacks are a special type of page that isn't meant to be viewed by a user. They are used as an endpoint for APIs (such as AJAX requests). Menu callbacks sort of act as a way for an API to "call a function".

2) MENU_DEFAULT_LOCAL_TASK - The default local task is just the local task that is selected by default. An example of this is the "view" tab on nodes. See more about local tasks below.

3) MENU_LOCAL_TASK - Local tasks are tabs. When viewing a node as an admin, several tabs are visible (view, edit, etc). Each of those tabs a local task.

4) MENU_NORMAL_ITEM - This is a page. Simple as that.

5) MENU_LOCAL_ACTION - Local actions are similar to local tasks, except they are meant to conduct an action, rather than display information. An example of this is the "Add Content" link that displays on the Content Administration page.

6) MENU_SUGGESTED_ITEM - This is almost exactly like a regular menu item, except it's disabled by default. This can be used by module makers to suggest a menu item to the user, but leave it up to the user to actually enable it.


How do you view a log of previous visited visitors showing their IP in Drupal 7? Where do you view a log of previous visitors showing their IP address in Drupal 7?

You can find visitors IP-adresses in both the sessiontable (field hostname) or, if you have the core statistics module enabled, in the accesslog table (field hostname).

You can view these logs in a tool that let you examine your database (I use phpMyAdmin), or you can write a small custom module that displays them for you.


How to create a dropdown list with node ids? I need to create a dropdown list box which contains the list of node ids of a specific content type. Then after selecting the node id in the dropdown i need the content of the node to be displayed below the dropdown.

Iam new to drupal. Is there any way to create the dropdown list box with the features...?

To get all the nodes ID's for a content-type, you can use EntityFieldQuery and node_load_multiple:

$query = new EntityFieldQuery();
$result = $query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'mycontenttype')
  ->execute();
$nodes = node_load_multiple(array_keys($result['node']));

If you are using FAPI (form API), you can populate your dropdown list with these values easily.

Unfortunately, I can't help with the last part (displaying the node under the form).


Removing Site Map Module I'm trying to remove the Site Map module from my website, however when I disable it in the modules section the page that it generates http://mywebsite.com/sitemap remains unaffected.

My first thought was; maybe the website cache needs clearing and or cron job needs to run. After doing both of those things, nothing has changed. I'm still left with the page on my site that I no longer want.

Does anyone know how I can get rid of this? I've even tried deleting the modules folder to no avail.

The module's definitely disabled.

It sounds like you might have another module also implementing that path.

To check, install the Devel module (if you haven't already), and go to /devel/php. Put in this code:

foreach (module_implements('menu') as $module) {
  $items = module_invoke($module, 'menu');
  if (isset($items['sitemap'])) {
    print $module;
  }
}

And submit the form. If another module is directly responsible for the /sitemap path (i.e. it's not a redirect or something else), its name will be printed to the screen.


Custom module embedding existing node form I have the following content types:

event
signup

I'm dealing with my_singnup module, for which I wish to:

allow user to add signup content (same as core node/add/signup)
using signup/event/%eventid path (it is simple link expose in every event)
presenting (while adding) some information from event in left side
and node/add/signup form on the right side
preventing signup/event without argument to run

The code I have already wrote is the following.

function my_singnup_menu() {
   $items = array();
   $items['signup/event'] = array(
     'title' => 'Sorry, no such event.',
     'page callback' => 'There is no event id in path.',
     'type' => MENU_CALLBACK,
     'access callback' => TRUE // for now
   );

   $items['signup/event/%eventid'] = array(
     'title' => 'Signing up for event',
     'title callback' => 'my_signup_title',
     'title arguments' => array(2),
     'page callback' => 'my_singnup',
     'page arguments' => array(2),
     'type' => MENU_CALLBACK,
     'access callback' => TRUE // for now
   );
   return $items;
}

function my_signup_title($node) {
  if ($node->type == 'event') {
  drupal_set_title(t('Signing up for event '.$node->title));
  }
  if ($node->type <> 'event') {
  drupal_set_title(t('Id in path is not event id.'));
  }
  return t('Signing up for event');
}

function my_signup($node = FALSE) {
   if($node) {
     if($node->type == 'event') {
       module_load_include('inc', 'node', 'node.pages'); //Added
       global $user; //Added
       $new_node = new stdClass; //Added
       $new_node->type = 'signup'; //Added - here was bug
       $new_node->language = LANGUAGE_NONE; //localization
       $new_node->user = $user->uid; //Added
       $new_node->name = (isset($user->name) ? $user->name : ''); //Added
       $form = drupal_get_form('signup_node_form', $new_node); //here was my big trouble
       return $form;
     }
   }
   return drupal_not_found();
}

function my_signup_theme($existing, $type, $theme, $path) {
  return array(
    'signup_node_form' => array(
      'render element' => 'form',
      'template' => 'signup-node-form',
      'path' => drupal_get_path('module', 'my_signup'),
    ),
  );
}

Right now, I see some form under event/signup/999 (thats good), but there is no custom groups and fields like in core default node/add/signup. I was so happy to see it that I forget to check it looks the same. I see only core vertical tabs such as Menu, Book, Version, Adress, Comments, and there is no custom fields and groups in it. It is strange.

node_form() is in node.pages.inc which isn't included by default. Just add a call like this to the beginning of your my_signup() function:

module_load_include('inc', 'node', 'node.pages');

When you call drupal_get_form() with a specific type (like signup_node_form) the node module internally translates that to node_form(). This happens in node_forms() which is in the node.module file, and as such is always included.

However node.pages.inc is only included when specifically requested by a module/menu callback etc. so to use node_form() you'll need to include the file manually.

You also need to pass a node object to the function with the required content type assigned like the following code:

$new_node = new stdClass;
$new_node->type = 'signup';
$new_node->language = LANGUAGE_NONE;
$form = drupal_get_form('signup_node_form', $new_node);


Views relationship question I have an Article node type where Expert node's can be referenced via autocompletion (as in: X Expert was consulted for this article)

I created a views for internal use, listing all the experts with exposed filters, easing up the journalist workflow to find suitable experts to contact for certain situations.

I'd like to list under each expert the Article nodes that they were referenced in, but as to how, I'm baffled, I attempted to create a relation with:

Content: Expert (field_expert_nid) - reverse
Relate each Content referencing the node through Expert.

But that's about how far I've gotten, any help or suggestions how to tackle this greatly appreciated :)

I had similar situation and resorted to using viewfield. Works like a charm. Recommended.


How can I display a page element based upon security? If I want to hide or show a DOM element, say a button that can show further information because the logged in user is a manager, how can I do that in Drupal 8?  Do I need to create separate pages for each type of user role?

I saw this but wasn't sure if it was the same thing I was asking,

How can I change page elements (menu, blocks, etc) based on a chosen 'audience' link?

If you want to make a button only available to users who are admins, put this property in the form element:

'#access' => \Drupal::currentUser()->hasPermission('access administration pages'),


How do I add a dynamic Facebook like button to every node of a certain content type One very comfortable solution to that problem is provided by http://drupal.org/project/fblikebutton. Unfortunately the positioning of the button isn't flexible enough for my needs.

I want every single node of one certain content type to have a FB like button at its bottom, making the base+node-url like-able. Facebook provides some snippets for that. Since I know that loading many iframes makes the site load very slow, I'ld like to add the JavaScript snippet into the appropriate template file.

My questions now are, in what template file exactly would I inject the little snippets and how do I have to customise the url in the plugin to make it fetch the url of every single node dynamically?

Inside a template_preprocess_node() I have done:

/**
 * Implements template_preprocess_node().
 */
function MYTHEME_preprocess_node(&$variables) {
  $node = $variables['node'];
  $variables['full_url'] = url('node/' . $node->nid, array('absolute' => TRUE));
}

Then in my node.tpl.php, I have

<?php // http://developers.facebook.com/docs/reference/plugins/like/ ?>

<div class="fb-like" data-href="<?php print $full_url; ?>" data-send="true"
  data-layout="button_count" data-width="450" data-show-faces="false">

In my html.tpl.php, I will hardcode the JS include so that it is right after the body (so I am not at the mercy of render trees, preprocess, etc:

This is from a pretty specific use case on a recent site.  I am not 100% sure if I tested this with multiple nodes on a single page, as the site I did this on doesn't have pages like that.


Content Field Type For Video, Images and Text I'm trying to decide what the best method would be for creating a new Content Type who's field type would allow me the flexibility to use ANY type of content inside of it. Almost like a blank HTML container. I'd like the flexibility to manipulate the content in that space to a video, rotating image, static image or text based on my needs. Would there be an appropriate field type to manage all of this?

Or would the appropriate answer be to create three separate content types that live one after the other in the area that I want them to be, then have them hide if no content is visible in them?

Apologies if this question has been answered in the community to date, but I've yet to come across a straight answer.

Thanks in advance!

I think that the best solution is to use Conditional Fields module.
You can manage dependencies between fields. So you should have one field type and all type fields separately and display them depend to type field.


access denied feed/[id]/import for a feed item I am dealing with an older d8 site that has a feed item of a custom type with custom processor. When I go to admin/content/feed and click on an existing one and I go to feed/id/import I get access denied. If I add a new one I do not get the same error but I am trying to understand what defined support for the "import" operation for a feed?

Feeds locks a feed when you start an import from it. As soon as the import finishes, the feed gets unlocked again.

When a feed is in a locked state, you cannot initiate another import. Therefore feed/id/import results into an access denied page.

There can be occasions in which an import failed to finish. This can for example be caused by bugs in Feeds or other modules. An other possible cause is that the database server restarted or stopped in the middle of an import. If you use periodic import on the feed, it may be that the import did not fail to finish, but just needs a few more cron runs.

To unlock a feed, go to the feed page and click on the "Unlock" button or go to feed/id/unlock. If you see no button or get access denied for that path as well, try to clear caches. Drupal caches access to menu paths (Feeds does clear the cache for the paths in question when a feed gets locked or unlocked).


custom display of taxonomy list in views I'm using a "Content:All Taxonomy Fields" field in a View.  Works great, but-

Can I change the display of taxonomy field lists without custom code?  The vocabulary has an image field I've added...I'd love to show the image instead of the name when listed.

Thanks!

If I understand well your question, you'd like to add the image associated to a term in your view ?
If so, in the view go to advanced (right sidebar) => Relationships. choose "Content: Taxonomy terms on node", then in "add fiels" you should be able to add any field of your terms, like name, description or image...

To Avoid duplicate output, go to "advanced => Query settings" and check "Distinct".

In case you have duplicate output anyway, you can try this other solution :

Add a content-> Nid field (Exclude from display).

Add a global php field. In output code, write something inspired from that, with your own details.

<?php
$q = "SELECT tid, filename FROM `taxonomy_term_data` INNER JOIN `field_data_field_tags` ";
$q.= "ON `taxonomy_term_data`.tid = `field_data_field_tags`.field_tags_tid ";
$q.= "INNER JOIN `field_data_field_img` ON `taxonomy_term_data`.tid = `field_data_field_img`.entity_id";
$q.= "INNER JOIN `file_managed` ON `file_managed`.fid = `field_data_field_img`.field_img_fid ";
$q.= "WHERE `entity_id` = ".$row -> nid;
$m = db_query($q);
while ($s = $m -> fetchObject()) {
  $img = "path_to_img_folder". $s -> filename;
  $tid = $s -> tid;
  echo "".$img."";
}
?>

You'll have then all your taxonomy images displayed in the same row. You may use the style settings to wrap the output with some classes. You'll have also to go to "advanced => Query settings" and check "Distinct". Hope it helps.


Don't allow "Delete this field" if a module is activated Inside "Article" type, I have a field called 'field_xenforo_thread_id' (machine name), It's possible to disable the "Delete" option only for this field and only if my module is activated please ?

If the module is activated and if the administrator remove this field, the module is broken and I want prevent this problem.

The module field lock allows you to lock fields for certain roles. You can use that module out of the box or you can copy it and adjust it so that the fields only lock if your module is activated.


how to change base url in drupal 8 I had installed a drupal website inside a folder in web root on an amazon ec2 instance. I used to access it by calling http://xx.xx.xxx.xx/folder .Now that the site is finished i created virtual hosts in my http.conf file to point the domain name to folder. I edited trusted host patterns in settings.php. So far so good! http://mydomainname.com points to front page.

PROBLEM:
when i click on links it shows 404 because path is http://mydomainname.com/folder/link instaed of http://mydomainname.com/link The front page parameter in site settings in admin side is uneditable.
How can I change that..? Please Help.

sudo nano /etc/apache2/sites-enabled/000-default.conf

Make sure it looks like this:

<VirtualHost *:80>
        # The ServerName directive sets the request scheme, hostname and port that
        # the server uses to identify itself. This is used when creating
        # redirection URLs. In the context of virtual hosts, the ServerName
        # specifies what hostname must appear in the request's Host: header to
        # match this virtual host. For the default virtual host (this file) this
        # value is not decisive as it is used as a last resort host regardless.
        # However, you must set it for any further virtual host explicitly.
        #ServerName www.example.com

ServerAdmin webmaster@localhost
        ServerName mydomainname.com
        ServerAlias www.mydomainname.com
        DocumentRoot /var/www/html/drupal

<Directory /var/www/html/drupal/>
        Options +FollowSymLinks
        AllowOverride All
        order allow,deny
        allow from all
</Directory>

        # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
        # error, crit, alert, emerg.
        # It is also possible to configure the loglevel for particular
        # modules, e.g.
        #LogLevel info ssl:warn

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined

        # For most configuration files from conf-available/, which are
        # enabled or disabled at a global level, it is possible to
        # include a line for only one particular virtual host. For example the
        # following line enables the CGI configuration for this host only
        # after it has been globally disabled with "a2disconf".
        #Include conf-available/serve-cgi-bin.conf
</VirtualHost>

# vim: syntax=apache ts=4 sw=4 sts=4 sr noet


Deliver ajax commands on successful form submit First of I apologize if this has been asked before, but I haven't found anything that actually does what I want to do.

Question: I'm trying to deliver some ajax commands on after a successful ajax submission of a form.

The Code

function my_module_form_form($form, &$form_state){
    $node = $form_state['build_info']['args'][0];
    $form = array(
        'track_id' => array(
            '#type' => 'textfield',
            '#title' => t('Track ID'),
            '#required' => true,
            '#prefix' => '
nid.'">',
        ),
        'courier' =>array(
            '#type' => 'textfield',
            '#title' => t('Courier Name'),
            '#required' => true,
        ),
        'actions' => array(
            '#type' => 'actions',
             'submit' => array(
                '#type' => 'submit',
                '#ajax' => array(
                    'callback' => 'my_module_form_ajax_submit',
                    'wrapper' => 'form-finished-wrapper-'.$node->nid,
                ),
                '#prefix' => '
',
                '#suffix' => '
',
                '#value' => t('OK'),
            ),
        ),
    );

    return $form;
}
function my_module_form_validate($form, &$form_state){
    // form_set_error('courier', 'catch all');
}

function my_module_form_ajax_submit($form, &$form_state){
    $return_form = array(
        'track_id' => $form['track_id'],
        'courier' => $form['courier'],
    );
    return $return_form;
}
function my_module_form_submit($form, &$form_state){

    $node = $form_state['build_info']['args'][0];
    $track_id = $form_state['values']['track_id'];

    $node->field_track_id[LANGUAGE_NONE][0]['value'] = $track_id;
    $node->field_courier_name[LANGUAGE_NONE][0]['value'] = $courier;
    node_save($node);

/* How can I deliver the below commands?

    $ajax_commands = array();
    $ajax_commands[] = ajax_command_invoke('myModal, 'modal', array('hide'));
    $ajax_commands[] = ajax_command_replace('form-finished-wrapper-'.$node->nid, t('Submited Successfuly'));
    ajax_deliver(array('#type' => 'ajax', '#commands' => $ajax_commands));

*/

}

Context

The form appears in a modal my_module_form_ajax_submit is responsible to display validation errors along with messages. I have tried ajax_delivery and ajax_render to return the commands. With ajax_render nothing happens, but with ajax_deliver I get an ajax popup with the commands in JSON. I think I'm close but surely I'm missing something.

Any help appreciated!

You return the ajax commands in your ajax callback function.

function my_module_form_ajax_submit(array $form, array &$form_state){
  if (count(form_get_errors())) {
    return array(
      'track_id' => $form['track_id'],
      'courier' => $form['courier'],
    );
  }
  else {
    $ajax_commands = array();
    $ajax_commands[] = ajax_command_invoke('myModal', 'modal', array('hide'));
    $ajax_commands[] = ajax_command_replace('form-finished-wrapper-'.$node->nid, t('Submited Successfuly'));
    return array('#type' => 'ajax', '#commands' => $ajax_commands);
  }
}

I'm not sure what you were trying to do with your original callback, so I couldn't incorporate it.


Load single value from multiple value image field in View I am trying to load a single value from a multiple value image field in View.
I am adding the field with a restriction to print only a single file. I am also filtering by delta(=0). Check the settings in the attachment.

However the view is loading all images attached to the field. How can I load only the 1st one?

Try to delete the delta field. You only need the content field and the restriction on the display values (like you did on the screenshot).


Which hook will use for checking taxonomy term page I need to run a hook on every taxonomy term page load.

function mymodule_WhichHook(){
   if (arg(0) == 'taxonomy' && arg(2) == 'term' && is_numeric(arg(2)) ) {
    // Store taxonomy details to DB
   }
}

Which Hook can i use for this. Please suggest.

You may implement  hook_taxonomy_term_load  in your module


Using hook_form_alter on an existing form element I'm using the Commerce module and in the checkout process I'd like to change the size of one of the input fields. I'm trying to use the following code but it doesn't seem to be working.

Am I doing this correctly? Or is there a better way to change the size of an existing form input field?

function mytheme_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'form-AyTG_90yQduNFHHSAwpVnMfNNXEt5iv_eUvptp_Ex7E') {
        $form['edit-account-login-mail'] = array(
            '#size' => 40,
        );
    }
}

Not sure which checkout form you try to alter, however, I've used mytheme_form_commerce_checkout_form_checkout_alter(&$form, &$form_state, $form_id) and mytheme_form_commerce_checkout_form_review_alter(&$form, &$form_state, $form_id) successfully.

And if I understand it correctly, the element 'edit-account-login-mail' already exists in your form. Therefore, I think you might want to add the size property instead of overwriting the form element, for instance:

$form['edit-account-login-mail']['#size'] = 40;


How do I restrict the type of characters that can be used at registrations? I want to disallow the use of spaces and all symbols except "_".

Based on what you said in your comment, you should just use Pathauto. Pathauto allows you to remove special characters from user/node/taxonomy URLs; if someone's username is 'hey$3#@", you could make their user profile URL http://yourdomain.com/user/hey3.


How can I save all taxonomy terms automatically? I'am using hook_taxonomy_term_presave to redirect file urls to another link.

In order to see the changes I need to go to : Mysite/taxonomy/term/10/edit and save the page.

I need to do this operation for all taxonmy terms of my website, is there a way to do this automatically whithout editing every page and save it ?

Thanks.

The best I know from your question is to use the Views Global Filter module.

Using this module you can save you taxonomy term into cookie and get any where in the page and can also redirect and filter the results.


Fatal error: Call to undefined function system_run_automated_cron() I migrated my database from oracle to mysql and when linking it to my drupal the following error:

Fatal error: Call to undefined function system_run_automated_cron() in /var/www/drupal/includes/common.inc on line 2732

Call Stack
#   Time    Memory  Function    Location
1   0.0000  241712  {main}( )   .../index.php:0
2   0.1117  1842704 menu_execute_active_handler( )  .../index.php:21
3   0.1120  1844088 drupal_deliver_page( )  .../menu.inc:532
4   0.1123  1845064 drupal_deliver_html_page( ) .../common.inc:2589
5   0.1213  1858496 drupal_page_footer( )   .../common.inc:2705

Someone could help me solve this problem?

For some reason it hasn't defined system_run_automated_cron() in the core system module. It's just a matter of figuring out why. A couple of things to check are:

Since you moved the DB over, did all the tables get created correctly? Check for the system table for a row entry with the name column set to "system". Is the status column set to 1?
Does modules/system/system.module exist and is executable by the webserver?


Custom page template for content pages Is there any way to make a custom page.html.twig template in Drupal 8?

By default, Drupal generates some suggestions, but I'm looking for something like page--node--content-type.html.twig.

You are looking for hook_theme_suggestions_HOOK_alter().

HOOK is the name of the template, in your case, page. You should be able to add the following to your theme in the .theme file.

In there, do something like this:

function yourtheme_theme_suggestions_page_alter(array &$suggestions, array $variables) {
  if ($node = \Drupal::routeMatch()->getParameter('node')) {
    $suggestions[] = 'page__node__' . $node->getType();
  }
}


Private Files System - Media upload works, but image is not displayed I have set default download method in D7 to private. When uploading images, they are stored in the private folder (OS level). But when having a look to content-media, only a placeholder is visible. The image cant be displayed. Any ideas ?

Thanks

Martin

For the image to be displayed, you would have to have access to the private folder, but since you're an anonymous user to the webserver, it won't display.

Images being served on your website should be in a public folder.
Downloads could come from a private folder if the webserver/Drupal moves them to a temp directory before downloading them.


How to set up Authcache module with Varnish and ESI? I am trying to set up Drupal 7 with Authcache beta 2 and Varnish 3.0 but I can't get the ESI blocks working. Varnish it self seems to work well.

I am using the example.vcl from sites/all/modules/authcache/modules/authcache_varnish/ but on the Authcache ESI status debug page I get the following messages:

ERROR: Request Header   HTTP header X-Authcache-Do-ESI is not on primary request.
Please make sure that the reverse proxy software (varnish) is configured according to the requirements of authcache_esi / authcache_varnish.

OK  ESI Tag Tag successfully substituted by reverse proxy.

ERROR: ESI Subrequest Header    HTTP header X-Authcache is not on ESI subrequest.
Please make sure that the reverse proxy software (varnish) is configured according to the requirements of authcache.

The second problem is that even if I configure some blocks on the blocks setting page to load via ESI and AJAX, this block do not show up at admin/config/system/authcache/p13n and admin/config/system/authcache/p13n/frontcontroller.

There for it does not surprise that watchdog gives the error message (for each block):

Failed to find url generator for route frag/block/block-25

EDIT: My setting.php is set up as follows:

$conf['reverse_proxy'] = TRUE;
$conf['reverse_proxy_addresses'] = array('127.0.0.1');
/**
 * Add Varnish as the page cache handler.
 */
$conf['cache_backends'][] = 'sites/all/modules/varnish/varnish.cache.inc';
$conf['cache_backends'][] = 'sites/all/modules/authcache/authcache.cache.inc';
$conf['cache_backends'][] = 'sites/all/modules/authcache/modules/authcache_builtin/authcache_builtin.cache.inc';
$conf['cache_class_cache_page'] = 'VarnishCache';
// Drupal 7 does not cache pages when we invoke hooks during bootstrap.
// This needs to be disabled.
$conf['page_cache_invoke_hooks'] = FALSE;

I didn't find any documentations so what am I supposed to do?

When using this file I had to scroll down to line 142 and change this:

  if (req.restarts == 0 && server.identity !~ "^/tmp/vtc.") {
    unset req.http.X-Authcache-Do-ESI;
    unset req.http.X-Authcache-Get-Key;
    unset req.http.X-Authcache-Key-CID;
    unset req.http.X-Authcache-Key;
  }

into this:

  if (req.restarts == 0 && server.identity !~ "^/tmp/vtc.") {
    unset req.http.X-Authcache-Do-ESI;
    unset req.http.X-Authcache-Get-Key;
    unset req.http.X-Authcache-Key-CID;
    unset req.http.X-Authcache-Key;
  }

  set req.http.X-Authcache = 1; // Added by me
  set req.http.X-Authcache-Do-ESI = 1; // Added by me

I'm not sure why those headers are not added but instead removed in the default version, since the module seems to require them to be present in the first incoming request. However, given the nature of those headers, they seem to make more sense when returned from the backend to Varnish than the opposite. znerol might have a good answer for you (and for me) why they are required in the first request.

I also wanna say thank you znerol for this amazing module and for the ongoing documentation work.


Why do I get a 403 error? I'm trying to setup a REST server to allow login from external apps.
I managed to get the sequence working using the Poster plugin in Firefox but can't seem to replicate using a small Perl script.
I manage to get the X-CSRF-Token but fail to connect, getting a 403 response.

This is the sample Perl code.

my $ua = LWP::UserAgent->new(env_proxy => 0,
keep_alive => 0,
timeout => 60);
$ua->agent('Mozilla/5.0');

my $req = new HTTP::Request('GET', 'example.com/services/session/token');
my $response = $ua->request($req);
unless ($response->is_success) {
    die $response->status_line;
}
my $token = $response->content;

my $header= HTTP::Headers->new;
$header->header('Content-Type' => 'application/x-www-form-urlencoded', 'X-CSRF-Token' => $token);

$req = new HTTP::Request('POST', 'example.com/smartphone_service/system/connect.xml', $header);
$response = $ua->request($req);

I installed the Services module and REST server locally, and that test worked. Service config is the same as the prod. What could be wrong?

Finally got it. It was mod_security indeed. I could not see errors in my (cpanel) log because I am on a shared host but went ssh and saw it:

UNSUPPORTED DELAYED Rules: POST request must have a Content-Length header

$header->header('Content-Type' => 'application/x-www-form-urlencoded', 'Content-Length' => 0, 'X-CSRF-Token' => $token);

That did the trick

Thank you Molot and David for taking the time to respond


What is the meaning of the field:delta content type offered in contextual filters in views? When creating a new contextual filter for a view the list of types includes options such as content:spec (field_spec:delta) where spec is the name of a field I have attached to the content type accepted for the view.  It appears on some, but not all of the fields offered in the list.  I cannot find a reference on this field. What is this (field_name:delta)?

It appears only for multi-value fields. It refers to the order of the values. A delta of 0 is usually the first item, 1 is the second, etc. This can be used to restrict results to ones that have values for a specific delta.


Menu elements not being links, just to create submenu? Is there a built in or module way to add menu items with hook_menu to serve as containers, not links? I have a module set. Main module provides central configuration and satellite modules do actual work. main module should create submenu satellite modules will use to add their entries to, but there is no form nor page to put in the main element. Is there a way to avoid dummy content?

I want to avoid editing template.php - I use theme downloaded from drupal.org and I don't feel creating a subtheme to get that is really worth the effort - there should be an easier way, shouldn't it?

I know there are ways to do this with Menu UI, but I need it to work out of the box for my clients, so UI is not an answer.

I'm not sure how you'd get exactly that to work with the way Drupal's menus are structured.

Core provides a barebones page callback for handling the same sort of situation itself, the system_admin_menu_block_page() function. All it does for the page display is list the menu items that are underneath it in the hierarchy (like the node/add page). Think of it as a landing page for a menu item that doesn't need any other form/page data.

I believe if there are no sub-items under the parent, the menu link won't actually be displayed so that method should get you pretty close.

$items['admin/something'] = array(
  'title' => 'Something',
  'access arguments' => array('some permission'),
  'page callback' => 'system_admin_menu_block_page',
  'file' => 'system.admin.inc',
  'file path' => drupal_get_path('module', 'system'),
);

Then your other module can define paths like 'admin/something/something-else' and they'll appear underneath the parent


How to set the front page with Mobile Switch I am using Mobile Switch to switch to my mobile theme when viewed on a mobile device. However, I don't see any way of setting redirect to a custom front page. How can I do this?

Have you tried Context Mobile Switch in comination with Context? And if you want to implement a small custom module then you can add the global $conf variable and inspect it for which property to switch on.


Available node language only English I have a custom content type with  "Set custom language as default for new content" and "Require language". Custom default language is Current language.

Entity translation is defined with "Current language" as "Default language"
and "Exclude Language neutral from the available languages" enabled.

I have 24 languages enabled but when creating a new node, only English appears as a language. But I need to be able to set any of the 24 languages

What am I  missing?

Change interface lang to the node target lang

The configuration you describe will always only allow one language when creating new nodes: the current language of the interface.

That is because you have Set custom language as default for new content. (and the current one as the default).

If you want to create content in other languages, you have to visit the node creation page in that target language (/fr/node/add/article if you're using prefixes).

Or allow other langs to be chosen

But if you want to be able to choose which language to assign to a node no matter what interface language you're currently using you have to untick the   Set custom language as default for new content. while keeping Require language (Do not allow Language Neutral).

That way your interface may be English, but you'll be able to choose any language in a drop-down to assign to that node.


Is there a way to not show some fields of a content type on the add form? I have a content type "Print" with several fields. Some fields need to be filled out by users and thus, should be hidden from the anonymous users who create content of type "Print." Is there an easy way to do this?

The Field Permissions module sounds exactly like what you're after.

  The Field Permissions module allows site administrators to set
  field-level permissions to edit, view and create fields on any entity.

  Features

  Enable field permissions on any entity, not just nodes. Role-based
  field permissions allowing different viewing patterned based on what
  access the user has. Author-level permissions allow viewing and
  editing of fields based on who the entity owner is. Permissions for
  each field are not enabled by default. Instead, administrators can
  enable these permissions explicitly for the fields where this feature
  is needed. Field permissions overview

Simply don't give anonymous users permission to add/edit these fields.


Add print button in the "Review order" page I want to know, is there any way to add print button to "Review order" page.

by clicking this button, a pop up page is loaded with good style for print mode and user can print the cart items , taxes and all information in Review order page.

Please guide me.

You can try using the PrintFriendly & PDF module, which has a version for Drupal 7 and one for Drupal 8. (The development snapshot for Drupal 8 has been created on July 27, 2017.)

The description of the module says:

  The #1 Print and PDF button for your Drupal site. Printer Friendly
  pages without coding, css, or print.css. Fast, easy, and professional.

  The Print Friendly & PDF button saves paper and ink when printing or
  creating a PDF. It's fast, easy, and looks great when printed. Add the
  button now, and your users will see the difference.

Using this module you can add a print button to review order pages.


Get all instances of a content type Is there a function in Drupal 7 to pull all instances of a specific content type to store in an array? Ex: Say I have a content type called "us_states" and I want to pull each instance of that type (with it's saved data so the title, description, and the custom content I created) and store them into an array. How should I go about doing that?

Two options: node_load_multiple() function (deprecated) or EntityFieldQuery Class (preferred).

Example node_load_multiple():

$nodes = node_load_multiple(array(), array('type' => 'us_states'));

  The second argument ($conditions) is marked as deprecated; and you can see that in the Drupal 8 documentation for the same function, it has been removed. I only included this example because I'm sure someone else would have pointed it out had I not and the fact that you specifically asked for a function.

Example EntityFieldQuery (Use this):

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'us_states');
$nodes = $query->execute();

In both examples, $nodes will be an array containing all nodes of the content type 'us_states'. (Note that the nodes within the array will be objects per usual.)

If you really need to use a function (that won't be deprecated in Drupal 8), you can pass an array of Node IDs as the first param to node_load_multiple() that contains the Node IDs of all of the 'us_states'.


How to set date display format for jQuery datepicker? I am using the standard jQuery datepicker in Drupal 7 and I would like to change how it saves and displays dates. Instead of displaying 10/11/2013, I would like it to display as November 10, 2013 for clarity. Is it possible to accomplish this?

To change how the datepicker displays in your content entry form, go to Structure > Content types > YourType > Manage fields > YourField. Expand the section labeled, "MORE SETTINGS AND VALUES", then select the desired date format from the "Date entry options" select list.


Organic Groups (OG): Make public group posts visible to everyone (outside the group) I’m using the OG module for my site where users can create groups and make them either public or private. But one feature I miss from the group environment when creating a public group is, to make all the posts in that group visible to everyone – not only group members.

I’ve looked in the OG admin settings and found the setting “Visibility of posts:” with the radio button option to “Visibility chosen by author/editor using a checkbox on the posting form. Checkbox defaults to Public.” This function is exactly what I want but when choosing this option and try to create a post inside an open, public group, I don’t get any options to select it to be visible or not. The field just isn’t there.

I’ve browsed Google and Drupal.org for an answer and have discovered that I’m not the only one with this question. But unfortunately I haven’t been able to find a solution, so I will try again to post the issue and maybe there is something I’ve overlooked.

Any help would help.
Thanks

Sincere
- Mestika

You control the visibility of a post through the Group_Access field.

Create a content type with Group and Group_Access fields (or add those fields to a built-in content type). Then when users create posts of this content type, they can make the content part of the group and set its Group Access to either "Public - accessible to all site users" or "Private - accessible only to group members."

Any "Public" content will be visible to anyone on the site, not just group members.


How to insert data to webform via HTTP/Drupal REST module? I have hooked up a simple webform and now I need to insert data via HTTP/Drupal REST module ?

Is is possible to insert this way, else should I insert directly to DB ?

I used webform_service with services module to insert data in webform using REST and its working fine form me.


How to get location (longitude and latitude) from json data show on map? I am using Openlayers module to have a map. In my json, it has longitude and latitude field. I want to get them to show on map so that user can see the location with the marker.

Is there any way to help me solve this problem?
Any help would be appreciated.

1) Add Geofield in your content type.

2) Select widget type as "Latitude / Longitude".
Here you can store values and show it on map.

For your reference listed some links :

Setting drupal 7 locations

Getting Started with OpenLayers in Drupal 7

Openlayers


Hide title if 404 error I have a custom 404 error page, and I just want a quick module that hides the 404 page title, if the user arrives at a 404 error.

I've found a D7 function that looks like it would work, checking for '404 Not Found' in the http header, and adding a class that I can target with CSS. But I'm not sure how I'd do something like this for D8.

Here's what I've got:

function MYMODULE_preprocess_html(&$variables) {
  $headers = drupal_get_http_header();

  if (isset($headers['status']) && $headers['status'] == '404 Not Found') {
    $variables['classes_array'][] = 'page-404';
  }
}

I don't think you need a custom module for something like this...
This should be as easy as:

Go to Configuration -> System -> Basic Site Settings, get the page URL you have for the 404 page.
Go to Structure -> Block Layout, edit the 'Page Title' block, and exclude it under the Visibility section, by page URL from step1.


How dio I change things on module installation? I've been looking around for several days now, maybe i'm just not fully understanding how the new Drupal 8 framework works entirely.  What i'm trying to do is create a module that is a complete product that runs on the Drupal framework. I need to be able to completely customize the Drupal settings when the module installs.  Changing things like the "Home" link to be "Dashboard" or just remove/disable it entirely or updating the front page url to point to the page i'm going to be creating programatically. There are also a myriad of administrative settings that i would like to set as well like the site email, error pages, email templates, and configuration of other required modules.

If anyone has any examples of how this can be done or can point me to the right areas of documentation that has the answers i'm looking for (googling has not yielded the answers and i like to think i have pretty decent google foo).

I think what you are thinking of is configuration and overriding configuration. You can load any config object and set its value.

See: https://drupal.stackexchange.com/a/187488/57

Menu links are entities and can be loaded and changed too. See: https://drupal.stackexchange.com/a/225605/57


Filter to display only modified content in Views I created a view that displays the number of nodes modified by each user on a specific month.
I check the "modification date". The problem is that I also obtain nodes that have never been modified but have been created on that date.

In the node table, "created" and "changed" fields have the same value when the node is created. How can I only retrieve the nodes that have been modified but not created on a specific month ?

Maybe a way of doing this is to check if node.changed <> node.created, but how can I do that in views ?

Unfortunately impossible to do it in the current UI.

There are 3 options AFAIK :

try the module views custom conditions
write an alter hook,
or implement a filter handler, which is definitely going to be slightly more complicated, but probably more fun :)

A repaired :) attempt to do the alter hook (with help from another answer on this great site) and the add_where_expression function :

function main_mm_views_query_alter(&$view, &$query) {
  if($view->name == 'admin_views_user') {
    $query->add_where_expression(0,'users.access < users.login');
  }
}

This is the view that comes with the module admin views. there are 2 columns - access and login, both are dates and this seems to work :) you will want to do a dpm($query) first, to see your actual query.


Can't load font woff I have relatively simple issue but I can't fix it myself.

My log is full warning with same message:

page not found
http://mywebsite.com/sites/all/themes/bigwig/font/entypo-icon-font.woff

I have looked around and most of suggestion is about .htaccess and I tried to add such block (but no luck).

<FilesMatch "\.(ttf|otf|eot|woff)$">
  <IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
  </IfModule>
</FilesMatch>

I have tried to access other files in folder via browser and everything worked except the one with *.woff

http://mywebsite.com/sites/all/themes/bigwig/font/*

What else can I try?

It seems somewhere you have something referencing that file. First place I’d look is on the theme folder.

If you have access to a Linux or Mac machine, you can cd into the folder and run,

grep -rn ‘entypo-icon-font.woff’ . 2>/dev/null

This will tell you if there’s a file that has a mention to that file.

To fix, you can either remove the reference to that file or see if you’re able to find the file and add it to the path on the url.


Add Line Item to "My Order" block I am using Drupal 7 Ubercart 3. Though I have added line item "Gift Wrapping" successfully using a module, I want to show it as well in the order "My Order" block so that the user immediately sees the fee in the order instead of seeing it on the review page. Please tell me is it possible to show line item in the cart along with other products?

Take a look here.
This may help you.  hook_line_item

http://www.ubercart.org/docs/api/hook_line_item


drupal_add_css does now work when in cache mode I am trying to add a jquery plugin to a page through drupal_add_css and drupal_add_js as follows:

drupal_add_css($path = 'sites/all/libraries/gips/css/gips.css', $type = 'file', $media = 'all', $preprocess = true);
drupal_add_js('sites/all/libraries/gips/js/gips.js', array('type' => 'file', 'scope' => 'header', 'weight' => 3));
drupal_add_js("jQuery(document).ready(function(){...dosomething...});"), array('type' => 'inline', 'scope' => 'footer', 'weight' => 5));

When I'm not aggregating/caching the CSS files, it works fine.
When I try to aggregate the CSS files, it doesn't. The behavior is as if some css rules get lost in the process.
The same happens even if I change the $preprocess to false.

From Chrome's code inspector, I cannot see any overriding rules getting in the way either.

I am at a loss on how to debug this. Any suggestions?

While you are using the version 7 drupal_add_js, the snippet you posted appears to be using the Drupal 6 arguments for drupal_add_css. You might also need to set the every_page option to true so that it is aggregated. Maybe try:

drupal_add_css('sites/all/libraries/gips/css/gips.css', array('type' => 'file', 'media' => 'all', 'preprocess' => true, 'every_page' => true));

You could also have a look at the group and weight settings on the api page linked above to see if they will help.


Create user in Drupal 8 but password not working I tried to create user in Drupal8 using entity_create. The user is created just fine, but I can't login with the password unless I change it from the admin page.

$authData['name'] = 'testuser';
$authData['pass'] = 'testpass';
$authData['mail'] = 'sss@test.com';
$authData['status'] = 1;
$account = entity_create('user', $authData);

I also tried, the following code (obtained from drush)

$account->pass = 'testpass';
$account->save();

and also $account->setPassword

none of above works.

I try with you code, I not see any problem and work for me (drupal 8 beta7).

$authData['name'] = 'testuser';
$authData['pass'] = 'testpass';
$authData['mail'] = 'sss@test.com';
$authData['status'] = 1;
$account = entity_create('user', $authData);
$account->save();

Note that user and pass are different when you try to log in

user: testuser

pass: testpass

That drupal 8 version are you using?


template.php function for adding field CSS classes I'm using Drupal 7 with Bootstrap. I copied the sub-theme and renamed all the files accordingly and everything works fine, however I'm having problems with my sub-theme's template.php not doing what it should.

I am trying to add specific CSS classes to my form field while editing the form or adding new content. I tried following http://atendesigngroup.com/blog/adding-css-classes-fields-drupal, but I can't change the field's classses.

This is the code I have in template.php.

/**
 * Overrides theme_field()
 * Remove the hard coded classes so we can add them in preprocess functions.
 */

function MojCrm_field($variables) {
  $output = '';

  // Render the label, if it's not hidden.
  if (!$variables['label_hidden']) {
    $output .= '
' . $variables['label'] . ':&nbsp;
';
  }

  // Render the items.
  $output .= '
';
  foreach ($variables['items'] as $delta => $item) {
    $output .= '
' . drupal_render($item) . '
';
  }
  $output .= '
';

  // Render the top-level DIV.
  $output = '
' . $output . '
';

  return $output;
}

/**
 * Implements hook_preprocess_field()
 */

function MojCrm_preprocess_field(&$vars) {
  /* Set shortcut variables. Hooray for less typing! */
  $name = $vars['element']['#field_name'];
  $bundle = $vars['element']['#bundle'];
  $mode = $vars['element']['#view_mode'];
  $classes = &$vars['classes_array'];
  $title_classes = &$vars['title_attributes_array']['class'];
  $content_classes = &$vars['content_attributes_array']['class'];
  $item_classes = array();

  /* Global field classes */
  $classes[] = 'field-wrapper';
  $title_classes[] = 'field-label';
  $content_classes[] = 'field-items';
  $item_classes[] = 'field-item';

  /* Add specific classes to targeted fields */

  switch ($name) {
    case 'field_baza_direktor':
      $title_classes[] = 'inline';
      $content_classes[] = 'col-sm-6';
      break;
  }

}

Using yourtheme_preprocess_field() won't work for forms because theme_field() isn't called. Instead, theme_form_element() is executed, which builds the form element wrapper.
If you want to use/override the input itself override the corresponding theme function, e.g. theme_textfield() and so on.

Another way could be using hook_form_alter()/hook_FORMID_form_alter() if you want to override the attributes for a specific form only.


block user by sql query I wanted to block a bulk amount of users of my site. I was thinking to do it by firing a sql query and turning off the status field of users directory.

So is it safe to fire such sql or is there any otherfunction which does that?

My site is still in drupal 6.

Tks
Vil

If not Views Bulk Operations as mentioned in the comment above by arpitr there seems to be one function from the core users module which appears to be of the purpose for the same. The User module's hook_user_operations for block operation namely user_user_operations_block would be it to answer your query and should provide you a drupal code way of doing it.

function user_user_operations_block($accounts) {
  foreach ($accounts as $uid) {
    $account = user_load(array('uid' => (int) $uid));
    // Skip blocking user if they are already blocked.
    if ($account !== FALSE && $account->status == 1) {
      user_save($account, array('status' => 0));
    }
  }
}

Essentially it loads the user account and makes call to user_save with the status as 0. If your implementation is to block users with custom code based on a specific logic, you could do the same or perhaps consider invoking the user module's hook_user_operations for block operation with the desired input though I haven't done something similar. Doing so would prevent you writing your own update query. Hope that helps.


Can I use same (machine) name for taxonomy and content type? My question: Can I (or rather, should I) create a taxonomy and a custom content type that have the same machine name?  I plan to 'link' those two together.

I tried to search around and could not find an answer, I found out that two custom fields cannot have the same name, even if they belong to two different content types for example.  So that would lead me to suggest that the answer to my question is probably not (i.e. they would try to use the same table name). But I don't know if that's correct.

Say I create a site for a school, and want to have a custom content type 'staff' that will hold teachers, administrative staff, etc.  I will also have a vocabulary that has these different staff categories (teachers, administrative staff etc), which I also thought of giving it the name 'staff'.  Is this a bad idea?

PS: I'm using Drupal 8

Technically you can have same name for taxonomy and content type as the underlying machine name is not the same and there is no confict.

Practically it might not be a good idea as it might confuse the end users but  it depends on the problem you are trying to solve.

So based on your description staff category might be a better name for your category.


Disable the Drupal 7 overlay for some administrative links Is there a way to disable the Drupal 7 overlay for some administrative links by not others?

For usability reasons the site I'm working on would benefit from some administrative links using the default overlay behavior while 1 or 2 would benefit from having it disabled.  Since the vast majority of the links make more sense for users to experience in the overlay I'd like it to be generally enabled for them, but be able to keep a couple specific links embargoed so the JavaScript does not update their behavior.

Hope this will help you.

In Drupal 7 you can achive this by using hook_admin_paths_alter

Programatically

hook_admin_paths_alter : Redefine administrative paths defined by other modules.

    function HOOK_admin_paths_alter(&$paths) {
      //return FALSE to the path where you don't want to show in OVERLAY
      $paths['node/*/edit'] = FALSE;
      $paths['node/add'] = FALSE;
      $paths['node/add/*'] = FALSE;
    }

Using Module

Overlay Paths : You can enable the overlay for selected non-admin paths and also you can disable overlay for selected admin paths.


How to restrict block for particular subpath, yet allow for all other subpath of a specific parent path? I have created the custom page and assigned for the Underwriting content type nodes like underwriting/, but I want to restrict the block for a node of that content type; for example, show it for underwriting/, but not for  underwriting/example.

Is it possible to restrict a block for particular sub-path, and allow it for all the other sub-paths of a specific path?

Assuming all of your underwriting/* nodes are of a certain content type and this content type does not have anything else than underwriting/* as path

Go to /admin/structure/block and find your block and click on Configure link.

Then under Visibility settings, Pages tab, select all pages except for underwriting/example

and then


How to show a field from the current node in quicktabs I have a quicktabs block on the node page which will have several tabs with different views/content related to the current node. How can I show a field from that node in a separate tab?

Depend from requirements in the project, but Field Group can be an option too.


Import js code in node I'm using Drupal 7 and Clean theme. And i have got a map. That's javascript codes. I created map field in my content type and want import this javascript in node.

How can i do?

Alternatively use hook_node_view_alter() and drupal_add_js()

drupal_add_js('path/to/file.js', 'file');


Editting/Modifying markup of registration form I would like to over ride the default registration form of Drupal. I want to edit its mark-up. Add few classes and wrap them with few div tags. I don't know how to get this done ? Is it possible to over ride like what we do for html.tpl.php ? I mean copy pasting a particular file some where from system into the template folder and edit it ? Please help me. I am very much new in Drupal.

You can use hook_form_alter to alter the registration form. This allows you to add markup, change labels, add divs, ...

Also to add markup, you could have a look at markup field

ANd last but not least, check out this page: https://www.drupal.org/node/350634. It contains a lot of info on how to override the user login/registration page

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id === 'user_register_form') {
    // perform other changes here
  }
}


Day and month name translation I am new to Drupal world and creating a site in Urdu language in Drupal 8. I have enabled its multilingual support and set default language to Urdu (in fact, this is the only language of the site).

I have created a content type and enabled to show Display author and date information. I have also added some contents for this content type. When I go to view some content, its author and date information is displayed as below.

Submitted by mabilalmirza on Fri, 02/09/2018 - 23:33

I know I can translate the string using translation interface but I want the day name to be shown in Urdu. I want to translate month names as well for long date format.

Can anyone guide me to accomplish this?

You can translate Interface strings through Configuration > Regional and language > User interface translation (/admin/config/regional/translate).

Enter "Submitted by" into the "String contains" search field. It's important to enter correct capitalization of letters or your string won't be found (don't enter "submitted by").

Your search will find this string to translate:

Submitted by @author_name on @date

As you can see you can translate part of the message that doesn't contain tokens for data (you need to copy @author_name and @date into your translation so the text makes sense, don't translate "author_name" or "date", leave them in English as they are!).

Dates are special formats in Drupal, with special translation options.

You can translate Date formats by going to Configuration > Regional and language > Date and time formats (/admin/config/regional/date-time).

The one being used for "Submitted by" text is "Default medium date". Choose Translate in the drop-down next to Edit button.

Here you only configure how dates are usually structured in your language (maybe something like D, d/m/Y - H:i in your case for the Default medium format, to have the day before the month).

Month and Day name translations will probably already be available from Drupal Localization project, but if you see they aren't translated you can translate them yourself through the User interface translation page.

If you don't see some of the options mentioned here, make sure you have enabled all translation modules, including "Configuration translation".


Converting a Project from D6 to D7 using Drush in localhost? I have a D6 project in my localhost

i.e   C:\wamp\www\ProjectName_6

I need to migrate the above mentioned project to D7 in the same directory using drush.

Should be like this C:\wamp\www\ProjectName_7

I am using Drush Version 5.7 which is located in the following path

C:\Documents and Settings\All Users\Application Data\Drush\

Could anyone kindly provide a step-by-step guide to complete this process or any good links which is suitable for new bie...

I googled a lot. But can't find any good article... (My search keywords may be wrong... )

Drush Site Upgrade 7.x-2.x is for upgrading FROM Drupal 6 sites TO Drupal 7 sites.  I know that the version numbering is a bit confusing, but it is based on the fact that the Current version of Drush is 7.x-5.x.  This version of Drush supports both Drupal 6 and Drupal 7, but is versioned 7.x to match the most recent stable version of Drupal supported.  Similarly, Drush Site Upgrade is versioned 7.x to match the version of Drush that it works with.  I added a sentence to the Drush Site Upgrade homepage to clarify that it is for D6 -> D7 upgrades; the README.txt already explains this.

As for a step-by-step guide to using Drush Site Upgrade, please understand that the Drush Site Upgrade command itself is a step-by-step guide to upgrading your Drupal site.  This command will print out an explanation of what it is about to do at every step, and then prompt you before taking action.  Run with the --always-prompt flag when you're first getting started to insure that absolutely everything will be prompted.  If there is a step that is not applicable, or does not work right for your environment, you can tell Drush sup to skip the step, you can do the operation(s) you need to by hand, and Drush sup can continue the upgrade process on the next step.  If something goes horribly wrong, you can always start over from the beginning and try again.

As you inferred, Drush Site Upgrade will not actually upgrade the code of your custom modules to D7.  For help with that, please see http://upgrade.boombatower.com/.


Sub-roles and role purchase I developed a site using Drupal 7 and the Ubercart module, where I sell user roles. I have sub-roles like the following.

Producer

Co-producer
Ex-producer

How can I manage this? Is there any sub-role concept existing or manageable with category name in Ubercart?

I think you are looking for something like Sub Users module to set relation between two user types.

I also sell membership with help of Drupal Commerce in D7 & I have used same thing but some modified version of the module which you can find at my given link here --

https://drupal.org/node/2049703

I sell membership to have some access & sometimes I create a usertype who has got authority to create more sub user under him to have access allowed for that particular membership type.


Get node url to other fields The above image is from Views Table. The values inside Name is title field so it is clickable by default and links to its Node. I want to make the values inside Nick Name and Age clickable link too, which will go to the same Node as its title.

I went to Nick Name field and did Rewrite Result and Output this field as a link, but in Replacement Patterns there is no Token for link, still I tried with [title], [title:url], [path], [view_node], etc.  but it cannot be linked to its Node.

You need to first add a path field to your view, and then exclude from display:

Add the field "Content:path" to your view as the first field in the list
Exclude "Content:path" from display
Under "Rewrite results", enable "Use absolute link (begins with "http://")"
For Nick name, choose "Output this field as a link"
For "Link path", use the [path] token

Repeat #4 and #5 for age if you like

It's important that the path field be listed first (or at least before Nick Name and age) or it won't be available as a token.

Also note that you must use an absolute link for Content:path under Rewrite Results. It's a little counter-intuitive, since the field is being excluded from display, but the setting is still used in the [path] token.


How to add a class to a pager? I would like to add bootstrap classes to a load more pager, with the views load more module. I am currently using javascript to add it on, but the moment I change the view the classes are no longer there. I assume I have to use theme_preprocess_item_list() but I'm not quite sure how to go about this.

Nevermind, got it working by using the template_views_load_more_pager. I was just using the wrong function name. Found it in the views load more module.