Create new table in existing module without affecting existing table data I have my custom module myCustomModule in drupal 7 website along with installation file to create table.

I Have already saved lot of content in table but I need to create a new table in same module without affecting the previous table data.

if I add something new in .INSTALL file, I have to uninstall and install module which will remove the existing data content from my table.

Is there a way to create new table for existing module without affecting existing table data.

How do I update my module structure without affecting previous things.

[or last option for me is to create a new module and have separate table but I dont want to create so many modules ]

Please help , I need to do it for Drupal 7

EDIT

I followed this link and tried below and cleared cache after updating my code

/**
 * Create new database table {new_table}.
 */
function my_module_update_7101() {
 $schema['new_table'] = array(
     'description' => 'Table for storing information about static media asset .',
        'fields' => array(
            'aid' => array(
                'type' => 'serial',
                'not null' => TRUE,
                'description' => 'Primary Key: Unique aggregator static media asset ID.',
            ),
            'asset_title' => array(
                'type' => 'varchar',
                'length' => 255,
                'not null' => TRUE,
                'default' => '',
                'description' => 'Title of the static media asset title',
            ),
            'asset_file_path' => array(
                'type' => 'varchar',
                'length' => 255,
                'not null' => TRUE,
                'default' => '',
                'description' => 'CDN url path for asset.',
            ),
            'status' => array(
                'description' => 'status field for the static media assets',
                'type' => 'int',
                'length' => 1,
                'not null' => TRUE,
                'default' => 1,
            ),
        ),
        'primary key' => array('aid'),
    );

  db_create_table('new_table', $schema['new_table']);
}

It does not seem to update my table

Approach to generate a new table without affecting existing table's data.

Declare the table structure in hook_schema because for any new user who will install this module later should get this table so we have to code it here in hook_schema.

/**
 * hook_schema().
 */

function my_module_schema() {
  $schema = array();
  $schema['new_table'] = array(
    'description' => 'Table for storing information about static media
asset .',
    'fields' => array(
      'aid' => array(
        'type' => 'serial',
        'not null' => TRUE,
        'description' => 'Primary Key: Unique aggregator static media asset ID.',
      ),
      'asset_title' => array(
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
        'description' => 'Title of the static media asset title',
      ),
      'asset_file_path' => array(
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
        'description' => 'CDN url path for asset.',
      ),
      'status' => array(
        'description' => 'status field for the static media assets',
        'type' => 'int',
        'length' => 1,
        'not null' => TRUE,
        'default' => 1,
      ),
    ),
    'primary key' => array('aid'),
  );
  return $schema;
}

For the users who have already installed the module and want to create a new table can write a hook_update_n() as below.

/**
 * hook_update_n().
 */

function my_module_update_7001() {
  $schema = my_module_schema();
  if(!db_table_exists('new_table'))
    db_create_table('new_table', $schema['new_table']);
}

Here we will get all the schema and creating the 'new_table' by using db_create_table().

Hope this will resolve your issue.
Thanks.


"Shopping cart form" view breaks after adding a field I'm creating a website using the Drupal Commerce module.
The module implements a view for the customer's cart at "cart/my", listing all the items the customer added to her/his cart.

The view used to render the item list is "Shopping Cart Form".

I edited this view (well cloned it first) to add an image field owned by the product. In order to get this field in the fields' field list, I first had to create a relation called "(Line items referenced by commerce_line_items) Commerce Line item : Product" for that view.
The issue I'm having is that, when the relationship is added (and only then) to get my image field, the view completely breaks when viewed by anonymous or regular authenticated users, and only for these roles. Everything is fine when the cart is viewed by a different role (either a custom role or the administrator role).

I know it sounds crazy, but that's it...
Somehow, addind this relation makes the results found for this view to 0 (as shown in the kpr() function run from mytheme_preprocess_views) and only for anonymous and regular authenticated users. If I remove the relation from the view, all goes well again.

Could it be a permission rule somewhere that I skipped ?

what you're experiencing is actually the same as another user whose anonymous users were not able to view their carts. It's related to Views relationships and the automatic access checks they add to Views queries. For more information, please see my answer here:

Anonymous cannot see cart in cart page


Database log details page blank We're having a problem with our log detail page (/admin/reports/event/XXXXXX):

As you can see, the content is blank.  There are no apparent errors in the Apache logs.  View source shows that the entire page HTML is rendering properly, there's just nothing in the content div.  Watchdog messages are showing up in the Recent Log Messages page (/admin/reports/dblog), it's just that when we click on one to get more detail, we get the blank detail page.

The details page was working a couple of weeks ago, and we haven't made any configuration changes since then.  We had to restart Apache and MySQL recently, but I don't see why that would cause this.

Tried disabling and re-enabling the Database Logging module.

Any suggestions?

Check if there are a user with uid=0 in users database table.
If not, just add a new row with 0 uid and it'll resolve the problem.
Good luck!


menu_tree_all_data() returns empty arrays for custom menus This works.

$tree = menu_tree_all_data('main-menu');

This doesn't work.

$tree = menu_tree_all_data('menu-health-center');

Why doesn't menu_tree_all_data() work for custom menus?

Custom menu machine names always have a prefix of "menu-", e.g.:

$tree = menu_tree_all_data('menu-custom-menu');

Make sure you're using the right machine name. Edit the menu and look at the URL: The last part of it is the machine name for the menu.


If logged in, My Account/Log Out are missing, how can i fix? I have a Drupal Commerce website in development and there is a problem with the User Login  block.

If logged in, it is missing the 'My Account / Log Out' links. But if logged out, is shows the standard links, 'Username/Pass fields, Create New Account, Request New Password' links.

I  have no idea how to fix. can someone please clue me in where to start? This was a PSD to Drupal job so maybe the problem lies in one of the Template files? like Regions.tpl ?

On a standard Drupal install this hasn't been an issue.

The user login block doesn't include "My Account" and "Log Out" links.

user_block_view > user_login_block

However, you can add the "User menu" to that region instead

Admin > Structure > Blocks > "User Menu"

It contains "My Account" and "Log Out" links.


Views Contextual Filter by Day and Night I have a content type with a boolean field, using radio buttons for day and night.

I would like to create a view with a contextual filter, which shows "day content" between 8:00 am - 8:00 pm and "night content" between 8:00 pm and 8:00 am.

Which is the best way for creating the contextual filter or view?

Or if you'd have a better suggestion, I could change my content type and fields too.

your approach is correct.

You can do one thing..Just create a view and contextual filter in view for radio field.
use hook_views_pre_view() hook to add arguments.

function MODULE_NAME_views_pre_view(&$view, &$display_id, &$args) {
  if ($view->name == 'myview' && $display_id == 'page_1') {
    $current_time = date('H'); //24hrs format
    if ($current_time >= 8 && $current_time <= 20) {
      $args[] = "value of day radio button";
    }
    else {
      $args[] = "value of night radio button";
    }
  }
}

Hope this will help


How to get country list array with their corresponding country codes I have used $countries = \Drupal\Core\Locale\CountryManager::getStandardList(); to render array of countries with country code as their keys. But when I debug the variable $countries; print_r($countries);die; it goes into infinite loop and result does not get rendered. It shows 404.

How to get country list array?

You get the infinite loop, because the country name is a translatable markup and print_r() can't handle this object. If you cast the country name to a string, then it is printable in php:

 $countries = \Drupal\Core\Locale\CountryManager::getStandardList();
 foreach ($countries as $key => $value) {
   $country_name = (string) $value;
   print "$key - $country_name\n";
 }

This is not needed for rendering, because twig can handle this object. This is only for debugging.


How to hide programmatically timezone and location on a custom user edit profile page in Drupal 7? I need a custom user_profile_form in a page of my drupal site containing a subset of fields provided by the form. I created it and rendered it this way:

function mymodule_join_experiment_contr_strict_mode($exp_node, &$form, &$form_state) {
  module_load_include('inc', 'user', 'user.pages');
  global $user;
  $user = user_load($user->uid);
  $form = drupal_get_form('user_profile_form', $user, 'account', 'strict_mode');
  return $form;
}

Now in my custom function mymodule_form_user_profile_form_alter(&$form, &$form_state, $form_id) i'm doing

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

in order to hide the field 'picture' and any other field i need to hide. In the form i have two collapsible named 'location' and 'timezone', provided, i think, by 'location' or 'gmap' module. (I didn't realized all this site so i don't really know everything about it.)
Now, even looking at $form i can't see the equivalent for timezone and location. I expected to find something that allowed me to do

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

but i cannot find timezone and location... What i am doing wrong?

EDIT: i'm trying to get what is the right way to do it in drupal, before to surrender and use a 'display:none' on css

Solved. I had to use the solution suggested #35

This is the code i used

<?php
function MYMODULE_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'MYNODETYPE_node_form') {
    $form['#after_build'][] = 'MYMODULE_SOMETHING_MEANINGFUL';
  }
}

function MYMODULE_SOMETHING_MEANINGFUL($form_element, &$form_state) {
  //note that I only have one location on this node type
  $form_element['locations']['#access']=FALSE;
  $form_element['timezone']['#access']=FALSE;

  return $form_element;
}
?>

I have not quite understood what is going on. An explanation about after_build would be appreciated.


After implementing hook_node_access, how to stop node from appearing in view? In Drupal 8, I implemented a hook_node_access function in my module to control access for a certain role under certain conditions and it works fine.

However, all of that content type are still shown on a view when the user views it. This is expected behavior according to the documentation:

  In node listings (lists of nodes generated from a select query, such as the default home page at path 'node', an RSS feed, a recent content block, etc.), ... hook_node_access() is not called on each node for performance reasons and for proper functioning of the pager system. When adding a node listing to your module, be sure to use an entity query, which will add a tag of "node_access". This will allow modules dealing with node access to ensure only nodes to which the user has access are retrieved, through the use of hook_query_TAG_alter(). See the Entity API topic for more information on entity queries.

(Link)

I understand why the view does not check each individual content, but I do not understand what this documentation is asking me to do to fix that. The documentation for hook_query_TAG_alter and on entity queries is not very helpful either.

How do I ensure that only items of this content type that the current user has view access to are shown in a view?

having run into the same problem as you I hope I can save you a headache.
Depending on the amount of results you have I can provide 2 ways to tackle this:

1. Works when you don't need pagination

HOOK_views_post_execute. This will have the rows in the variable. In here you can check the access and unset() the rows not allowed.

2. Works when you need pagination

HOOK_views_query_alter. I've used this solution for a view I needed myself with around 10000 results. I do a custom permissions check based on the user and the groups they are part of. Baed on this I generate a list of ID's of nodes they user is allowed to see. I add these ID's as an "IN" query to the view:

$cond["field"] = "media_field_data.mid";
$cond["operator"] = "IN";
$query->addWhere('1', $cond["field"], $mids, $cond["operator"]);

Where $mids has all the allowed Mids in there.
Hope this helps you get along!


How to rebuild route cache programmatically I installed a module quizzard and after uninstallation I am getting this error

Uncaught PHP Exception Symfony\Component\Routing\Exception\RouteNotFoundException: "Route "quizard.quizard_config_form" does not exist." at /home/paddu008/public_html/core/lib/Drupal/Core/Routing/RouteProvider.php line 190

So how do I rebuild route cache programmatically.

If you would like to clear route cache programmatically in drupal 8, use the following:

\Drupal::service('router.builder')->rebuild();


How to create dynamic select list in form using FAPI I am using Drupal 7. I have created two form (FAPI) fields of type select , State and District.
The district field should contain the dynamic options based on the state selected.

State field:

 $form['state'] = array(
  '#title' => t('Name of your State:') ,
  '#type' => 'select',
  '#default_value' => array(
  ),
  '#options' => $options,
  '#required' => '1',
  );

District field:

 $form['district'] = array(
  '#title' => t('Name of your District:') ,
  '#type' => 'select',
  '#default_value' => array(
  ),
  '#options' => district_list($form_state['values']['state']), // district_list is the function which will return the list of district based on name of state passed.
  '#required' => '1',
  );

The above code doesn't work, is there anything I am missing ?

You need to use the #ajax property in your State select list, with a callback function that returns the district element.  So something like this:

$form['state'] = array(
  '#title' => t('Name of your State:') ,
  '#type' => 'select',
  '#default_value' => array(
   ),
  '#options' => $options,
  '#required' => '1',
  '#ajax' => array(
    'callback' => 'MY_MODULE_state_ajax_callback',
    'wrapper' => 'edit-district',
 );

then create a callback called MY_MODULE_state_ajax_callback($form, &$form_state)
and within the function,

MY_MODULE_state_ajax_callback($form, &$form_state) {
    $form_state['rebuild'] = TRUE;
    return $form['district'];
}

It may be slightly more complicated than this, based on your use-case, but this is the meat of it.


Missing sections, and undefined indices I'm migrating a drupal 7 site from one hosting provider to another.  I've hit some snags along the way.  The main one comes from page.tpl.php.

On the screen I see various messages such as:

Notice: Undefined index: highlighted in include() (line 126 of /public_html/cconn/modules/system/page.tpl.php).

Notice: Undefined index: sidebar_first in include() (line 138 of /public_html/cconn/modules/system/page.tpl.php).

Notice: Undefined index: sidebar_second in include() (line 144 of /public_html/cconn/modules/system/page.tpl.php).

In page.tpl.php the missing sections are defined as such:

    <?php if ($page['highlighted']): ?>
<?php print render($page['highlighted']); ?>
<?php endif; ?>

Does anyone have any thoughts on what's going on and how to remedy it?  The site itself does come up, but as mentioned with these large chunks missing.

It seems some of the variables are not defined properly. It is recommended to define variables properly to avoid some security vulnerabilities or bugs. Although PHP doesn't create any execution error.

To Solve this, you may choose any of below choices.

1.) Properly declare variables - Recommended

$value = isset($_POST['value']) ? $_POST['value'] : '';

2.) Set custom error handler function

set_error_handler('myHandlerForMinorErrors', E_NOTICE | E_STRICT)

http://php.net/manual/en/function.set-error-handler.php

3.) Disable E_NOTICE from reporting - Fix

error_reporting( error_reporting() & ~E_NOTICE ).


Accessing $language inside node content in drupal 7 Normally I would use $language to get the active language on my drupal 7 page. Now I'm doing some changes to a node content (set to PHP code) and I can't seem to get any variables working? I badly need to get the active language inside the node content - how?

If I understand your question:

global $language_content;

This will return a language object with the current language.


How to render HTML from variable I want to render as HTML not string on Twig. I have a variable that hold form HTML but after putting on Twig template it's render as string like given below:

1) Set loginpopup variable in preprocess hook.

function MYTHEMENAME_preprocess_page(&$variables) {
    $variables['loginpopup'] = array(
   '#plain_text' => "

".drupal_render($form)."

"
    );
   }

2) Render on Twig template file as :

 {{ loginpopup }}

But it's visible as string (i.e. double-escaped).. What's the problem and how do I fix it?

You should definitely NOT put HTML into render arrays (I'm not saying you cannot (you can with #prefix and #suffix), you just shouldn't - that's D7 thinking). You should define a theme hook/template for that so that you can use your own template. But if you have to use inline template:

$page['noscript'] = [
  '#type' => 'inline_template',
  '#template' => '
{{ message }}
',
  '#context' => [
    'message' => $noscript_message,
  ],
];


How can I have a URL like www.example.com/about?language=ja to set Japanese for the page? I've enabled the Locale and Content Translation module but am having trouble understanding how to do something that it seems should be working.

Basically I have a page, we'll say '/about' and it's in English.

I click translate, I have a few languages enabled, so I click to add translation for Japanese. It brings up the interface for making a new page. I change some stuff to Japanese, and set the URL alias to be /about ('about') like the english page.

I've setup my language options to use the "Session" detection method.

The result I'm wanting to achieve, but not getting is to have:

www.example.com/about -- to go to english (this works)
www.example.com/about?language=ja -- to go to the Japanese translation, this does not work, it just loads up the English page.

It seems like this would be the normal functionality so I feel like I'm missing something here.

just to be sure:
at admin/config/regional/language/admin_language, enable "Session" Detection method
make sure request/get parameter set to language
make sure you have about page in 'ja' language

try to visit yoursite.com/?language=japanese, it should be translating interface/etc - this way you can check translation is working.


D7 - field_update_instance requiring manual refresh after node save to view new values I'm using preprocess_entity to alter an image's style display setting based on number of entity references within a paragraphs bundle. The display setting value is correctly altered on node save, but the updated image style won't display without an additional browser refresh.

function THEME_preprocess_entity(&$variables) {
  if ($variables['entity_type'] == 'paragraphs_item') {
    if ($variables['elements']['#bundle'] == 'promotions') {
      $promo = $variables['field_promotions'];
      $promo_count = count($variables['field_promotions']);
      $promo_img_styles = array(
        1 => 'promotion_1x',
        2 => 'promotion_2x',
        3 => 'promotion_3x',
        5 => 'promotion_5x'
      );
      $promo_img_style = str_replace(array_keys($promo_img_styles), $promo_img_styles, $promo_count);
      $promo_fields = field_info_instance('node', 'field_promotion_image', 'promotion');
      $promo_fields['display']['full']['settings']['image_style'] = $promo_img_style;
      field_update_instance($promo_fields);
    }
  }
}

Any ideas why field_instance_update is requiring the additional refresh?

the theme function occurs towards the end of the page request lifecyle in the theme layer of a drupal request.

Whereas, the field_update_instance call is updating the database values for this Node's promotion image. The node is already loaded and being used as variables within in the theme at this time. When you refresh the page you're requesting the Node from the database again -- which is "refreshing" the data.


How to change the language of inserted or updated paths to LANGUAGE_NONE using a module? All path aliases are entered by hand. I need them to be language independent. Currently they are created/updated in the language that the user is currently using which does not make sense in case of my site.

I tried using hook_path_insert and hook_path_update but they only receive the $path by value and not by reference and changing the function to hook_path_update(&$path) results in an error.

How to change the language of inserted or updated paths to LANGUAGE_NONE using a module? Alternatively, how can I force all aliases to be language independent automatically when user enters them? I don't think it is not possible; it is possible to allow them to choose the "All" language, but not force it.

If someone needs to have a multi language site, but have all URL aliases language independent (i.e. the same for all nodes and languages), the solution is to create a function:

mymodule_node_validate($node, $form, &$form_state) {
   $form_state['values']['language'] = LANGUAGE_NONE;
}

As a side effect, it also makes all nodes language independent. One possible scenario where this would be useful is:

all nodes are created in a custom language which is also the site default language
the administration interface is in English (this so far requires multi-language)
the administrator users are able to use the same URL aliases as the rest of site visitors, despite the fact that they have English set while the content is in a different language (this requires the trick)

In a real multi-language scenario, URL aliases may need to be different for different languages.


How to use user_external_login_register() with user authenticated by token? So, I'm working on an Oauth2 implementation, and I'm forced to use a custom module as the existing modules all have slightly differing functionalities than my use case, assume Drupal-to-Drupal implementation, or request the user credentials to be submitted to the remote server (which is not how Oauth should be implemented).

Using the standard authflow, the users are redirected and authenticate against a remote server, and are returned with an access code which is then submitted for an auth token, which is finally used to get user info from the remote API. Finally, I take the json response, format it into an array to be created into an user object, and this is where I'm stuck.

The examples presented on the User External Login Register API page seem to assume querying an external database to check for the user's existence. In my case, I have the user info and name, and need to create a user and log them in with that information.
 This is my current attempt which doesn't seem to be working. I modified the API example use the user_load_by_name() function to see if the user exists. Otherwise, I'm not sure how I should approach this otherwise.

So, my question is: 1) How do I correctly use this function? the example uses it without a module prefix, but if I declare it as a regular function I get a fatal error about re-declaring functions.

  $cs_user = array(
        'name' => $user_info['data']['user']['lastname'] . "_psr",
        'mail' => $user_info['data']['user']['email'],
        'pass' => $user_info['data']['user']['lastname'] . "_user_pass",
        'init' => $user_info['data']['user']['lastname'] . "_psr",
        'signature_format' => 'full_html',
        'status' => 1,
        'roles' => array(DRUPAL_AUTHENTICATED_RID => 'authenticated user',
                            22 => 'CS User External',),
        'field_first_name' => array(array('value' => $user_info['data']['user']['firstname'])),
        'field_last_name' => array(array('value' => $user_info['data']['user']['lastname'])),
        'field_chapter' => array(array('value' => $user_info['data']['user']['groups']['0']['title'])),
       );
    //format the user info, feed it to external_user_login_register
    $name = $cs_user['name'];
    $module = 'chapterspot_signon';
    echo "<hr>";
    }
    function chapterspot_signon_user_external_login_register($name, $module){
        $account = user_load_by_name($name);
$account = $name;
        if (!$account) {
        // Register this new user.
        $account = user_save(drupal_anonymous_user(), $cs_user);
        // Terminate if an error occurred during user_save().
        if (!$account) {
          drupal_set_message(t("Error saving user account."), 'error');
          return;
        }
        user_set_authmaps($account, array(
          "authname_{$module}" => $name,
        ));
      }
      // Log user in.
      $form_state['uid'] = $account->uid;
      user_login_submit(array(), $form_state);
      drupal_goto('/members');
    }

Update: The issue here is how to instantiate the function? The API page shows the function being called without a module prefix. When I run the code as user_external_login_register() I get a fatal error. When I try to run the function as mymodule_user_external_login_register nothing happens e.g.

$name = $cs_user['name'];
$module = 'chapterspot_signon';
function chapterspot_signon_user_external_login_register($name, $module){
echo "This is working";
}

Update 2: Apparently, the code within the function works by itself.

It seems a couple of mistakes in your above code.

Your $cs_user array below line should be populated with name instead of lastname

'name' => $user_info['data']['user']['lastname'] . "_psr",

Also, It seems 2nd line of your function function chapterspot_signon_user_external_login_register($name, $module) is not needed. Because if you Initialize your $account variable with $name then your condition if (!$account) { never comes true and the code written into that if condition will never executed.

You can try two approaches it will work for you:

1) Call Built-in function user_external_login_register($name, $module)  from your custom module.

Example:

user_external_login_register("addweb-solution", "your-custom-module-name");
drupal_goto('/members');

2) You can write your own function as below in your custom module:

function test_user_external_login_register($name, $module){
        $account = user_load_by_name($name);
        // $account = $name;
        if (!$account) {
            $userinfo = array('name' => $name,
              'pass' => user_password(),
              'init' => $name,
              'status' => 1,
              'access' => REQUEST_TIME,
            );
            // Register this new user.
            $account = user_save(drupal_anonymous_user(), $userinfo);
            // Terminate if an error occurred during user_save().
            if (!$account) {
              drupal_set_message(t("Error saving user account."), 'error');
              return;
            }
            user_set_authmaps($account, array(
              "authname_{$module}" => $name,
            ));
        }
        // Log user in.
        $form_state['uid'] = $account->uid;
        user_login_submit(array(), $form_state);
        drupal_goto('/members');

}

Hope this will helps you.

Thanks!


Using variable_get() in multiple places, without duplicating $default When using variable_get() in multiple places, how should one avoid duplicating the $default values?

define()?  Or is there some built-in Drupal-specific mechanism I'm missing?

There is no built in mechanism. In fact, there is a long standing issue to add one http://drupal.org/node/145164.

Defining constants, as you suggested, is the only method I've seen to make it a bit cleaner.


SMTP Module not sending email Using XAMPP on Mac

I have installed https://www.drupal.org/project/smtp

After setting up admin/config/system/smtp

It gives above error. Unable to send test email.

Do we have to any setting on gmail or i'm missing anything?

You probably have to be auth to be able to send mail from gmail's SMTP (smtp user/ smtp password).
Moreover, you have to "allow" the sender's email in your google account.

theMailYouSendFrom@whatever.com have to be allowed to send mail with account yourAccount@gmail.com; somewhere in gmail's parameters, you can validate this mail.

I remember there is a limit, 450 mails/day for each google account (this could have change now, that was 3 or 4 years ago), and more with payed gapps.


Save comment dynamically I've made my own module to add commenting to a node (it opens modally in a colorbox - really nice). The form works great, but how do I save the comment?

I know it's got to be done using comment_save. But, as usual, drupal.org is great at showing the code for the function without giving an example...

Has anyone done this before?

I'm guessing it's something like:

$comment = new stdClass();

$comment->nid = $the_node_the_comment_is_for;
$comment->title = $my_comment_title;
$comment->body = $my_comment_body;

comment_save($comment);

Yes you can save comment dynamically using comment_save() function, a working example is given below

<?php

$comment = new stdClass();

$comment->nid = 28; // nid of a node you want to attach a comment to
$comment->cid = 0; // leave it as is
$comment->pid = 0; // parent comment id, 0 if none
$comment->uid = 1; // user's id, who left the comment
$comment->mail = 'email@example.com'; // user's email
$comment->name = 'User name'; // If user is authenticated you can omit this field, it will be auto-populated, if the user is anonymous and you want to name him somehow, input his name here
$comment->thread = '01/'; // OPTIONAL. If you need comments to be threaded you can fill this value. Otherwise omit it.
$comment->hostname = '127.0.01' ;// OPTIONAL. You can log poster's ip here
$comment->created = time(); // OPTIONAL. You can set any time you want here. Useful for backdated comments creation.
$comment->is_anonymous = 0; // leave it as is
$comment->homepage = ''; // you can add homepage URL here
$comment->status = COMMENT_PUBLISHED; // We auto-publish this comment
$comment->language = LANGUAGE_NONE; // The same as for a node
$comment->subject = 'Comment subject';
$comment->comment_body[$comment->language][0]['value'] = 'Comment body text'; // Everything here is pretty much like with a node
$comment->comment_body[$comment->language][0]['format'] = 'filtered_html';
$comment->field_custom_field_name[LANGUAGE_NONE][0]['value'] = 'Some value'; // OPTIONAL. If your comment has a custom field attached it can added as simple as this // preparing a comment for a save

comment_submit($comment); // saving a comment
comment_save($comment);
?>


Multilingual "labels" in views fields? Is there any way to setup multilingual labels in views' fields.

Let´s say I have the ´title´ field and it shows the label ´My Title:´. Then as my site is bilingual (english-spanish) I need to have that label to ´Mi Titulo´ depending on user language.

How can I solve this?
Any module to expand views module?

You want to look into Internationalization Views, which allows you to translate labels and such in a view.


How To Display Node Tokens/Keys/Content Fields In Twig Template I'm fairly new to theming with Drupal, especially using Templates and Twig. After a lot of searching and experimenting I seem that have accomplished my desired view mode the way I want...almost.

I have a field in my content type called Category. The machine name is field_category. I have been able to output the field in my template using the key: {{content.field_category}} But as you can see it also applies a CSS styling I have on the full default Node Page which I would prefer not to have it there.

Going at it a different way, I used a View along with the given replacement patterns and was given the token of {{ field_category }}. After everything was done it does the same thing without any CSS styling since it's not pulling in the HTML markup of class="field field--name-field-category".

My question is I wonder if there is a way to grab the value without the markup? And if so how? Any steps in the right direction would be very much appreciated, I am a complete beginner at Drupal and even more so with Twig. Thank you.

With Drupal 8 you now have two ways to access to the data of a given node/entity.

The first is with the {{ content.* }} this will return the content that went through the display plugins/system (everything which you configure in the "Display mode" of the content type).

You also can access to the raw data with {{ node.*.value }}

It's preferably that you use the way {{ content.* }} as much as possible in order to be able to use the power of Drupal to quickly change the things with display mode.


Error sending e-mail when using webform I know there are already several posts about this subject, but I couldn't find a similar problem.
I have several webforms on my site. Each webform has an email action, sending an e-mail to only one recipient. When submitting the form, I get a "Unable to send e-mail. Contact the site administrator if the problem persists." message. However the e-mail is sent without any problem. When looking into the dblog, I see an error:

  Error sending e-mail (from blabla@mydomain.com to )

Note that the e-mail I wrote is not the real one ;-).
So it seems that my site is trying to send an e-mail to an empty recipient (in addition to the correct recipient). If I look into the database, in the "webform_emails" table I see 1 single line for my webform, corresponding to the right recipient. So, why does webform try to send an e-mail to nothing??
Any idea?
Thanks,
Pierre

My problem is not due to webforms but to a rule that is triggered when a webform is saved. The condition I put in the rule needs to be fixed, in order to run only for a specific webform.


Multi-site - can I route second site to different urls? I've got a multi-site Drupal installation with 2 sub-domains pointing to the same Drupal site. Eg: subdomain1.mysite.com and subdomain2.mysite.com

I have a page set up using hook_menu with the path 'site/%'. Eg: subdomain1.mysite.com/site/test

I want all requests to subdomain2.mysite.com/% to point to this page. Eg: subdomain2.mysite.com/test should point to the same page as subdomain1.mysite.com/site/test

How can I do this?

Redirecting to a different domain

Redirect URLs From Old To New Domain Using 301 Redirects In .htaccess

When you need to switch a website from an old domain to a new domain, you need to  redirect all your page URLs, this is when htaccess is your friend.

The code below will create 301 url redirects for both the www and non-www version of ‘olddomain.com‘ to the new domain  ‘newdomain.com‘.

Add this .htaccess file to the OLD site webroot and upload the files from the old site to the new to see a seamless switch from an old domain to a new one.

So the example below is redirecting all URLs from olddomain.com to newdomain.com

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.olddomain\.com$
RewriteRule (.*) http://www.newdomain.com/$1 [R=301,L]
RewriteCond %{HTTP_HOST} !^olddomain\.com$
RewriteRule (.*) http://www.newdomain.com/$1 [R=301,L]

You can also apply this to a subdomain – so the example below is redirecting all URLs from subdomain.olddomain.com to subdomain.newdomain.com

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^subdomain.olddomain.com$
RewriteRule ^(.*)$ http://subdomain.newdomain.com/$1 [R=301,L]
RewriteCond %{HTTP_HOST} ^www.subdomain.olddomain.com$
RewriteRule ^(.*)$ http://subdomain.newdomain.com/$1 [R=301,L]

For more details


Where are the field formatter settings? When I'm managing a display for an entity and select a field formatter, some formatters have options available (see screenshot 1).
However, when I use that same field formatter in Views, there's no way to set my options.  How can I set my options?

This works.

This doesn't have a way to select options.

4k4's comment was helpful in that it indicated the correct behavior.  This isn't what was happening; the POST requests were returning correctly, but I assume they're not returning a correct part of the dialog to replace.
However, with this knowledge in mind, I was able to use Configuration Management to export the View and the Entity view display, pull the appropriate setting names from the Entity view display, and manually apply them to the View YAML and reimport.  It's imperfect, but knowing that this should be possible was a great help in finding a workaround.


Override Access Permissions from View in Drupal 6 I have a ticket node that can only be accessed by the creator, or an administrator. I would like to display select fields from the ticket to other users in a view.

The problem is that, since the other users do not have access to the ticket node, the entries do not appear in the view.

How can I restrict access to the full ticket, but display selected fields from that ticket in a new view?

In CCK there is a sub module named content_permissions, With this you can set role wise permissions for fields


How do I add a private file to node's file field from Base64 in code I'm struggling to add file to node in code. I know about File::create() but I want to add file to node based on field configuration of the file field on that particular node's content type, and file's data comes as Base64, not URL or form post.

How do you do it? I'm asking as I want to add file via custom REST call as Base64.

I am using the following code.

$node = Node::load($data['case_id']);
$files = $node->field_file;  // unlimited files
/* @var $df \Drupal\field\Entity\FieldConfig */
$df = $node->getFieldDefinition('field_file'); // ??? can i get this config for saving new file?
$file =  file_save_data(base64_decode($data['data']), ??path??);
$files->appendItem($file)->validate();
$node->save();

Am I on the valid course? I have no clue how to set config from $df and before save. How do I use the configuration of that file field during save?

Yurii

my final solution was next:

$node = Node::load($data['case_id']);
$files = $node->field_case_file;
$dfSettings = $files->getDataDefinition()->getSettings();
$destination = $dfSettings['uri_scheme'].'://'.$dfSettings['file_directory'].'/'.$filename;
$destination = \Drupal::token()->replace($destination);
$file = file_save_data(base64_decode($fileData), $destination, FILE_EXISTS_RENAME);

$violations = $files->appendItem($file)->validate();

if(count($violations)) {
//throw error
}

$node->save();


Question about admin role Does the admin role always has access to everything ?

Because even if my AccessResult returns false, my admin still have acces to it (but it's perfectly working for the other roles)

Not the admin role, no. But user 1 does have access to everything, yes.

This is the function responsible, User::hasPermission, you can see the unconditional access check at the top:

public function hasPermission($permission) {
    // User #1 has all privileges.
    if ((int) $this->id() === 1) {
      return TRUE;
    }

    return $this->getRoleStorage()->isPermissionInRoles($permission, $this->getRoles());
  }


Where to put #Ajax Callback in webform twig file I would like to add the Ajax callback settings to my custom composite webform element in the twig file.  Is this possible?  The callback function is in my custom module.  This is NOT a computed twig situation.  The Webform is created entirely from D8 webform GUI.

Custom composite has qty, code, description, price.  Using the callback to verify code and update the description and price.
Could something like below be put in the twig file?

'#ajax' => (
    'callback' => 'validate_srvform_items',
    'event' => 'change',
    'progress' => array(
      'type' => 'throbber',
      'message' => t('Populating line item...'),
    )

You can create a form alter function in your module file and then add the callback property to the respective field

$form['actions']['submit']['#ajax'] = [
  'callback' => 'callback',
  'event' => 'click',
];

See also

Alter Ajax callback on Webforms
How do I add an AJAX action on a select element in a ContentEntityForm to change the value of another select element
Update webform field value using AJAX realtime


How to render a node field I can get the field using entity_metadata_wrapper like this

$node = node_load($nid);
$node_wrapper = entity_metadata_wrapper('node', $node, array(
    'langcode' => $GLOBALS['language'],
    'bundle' => 'unit'
     )
);

$field_value = $node_wrapper->field_photo->value();

And that returns an array which I don't know how to render. I tried drupal_render() but it seems that it doesn't do the job.

So how can I render this field ?

The photo field is an image field? The value() function returns an array which is actual file data linked to the image. To render (or to create a renderable build), you can for example use theme_image function, which prints out an <img> tag.

$node = node_load(43);
$node_wrapper = entity_metadata_wrapper('node', $node, array(
    'langcode' => $GLOBALS['language'],
    'bundle' => 'subject'
));

$field_value = $node_wrapper->field_teaser_image->value();
$build = array(
    '#theme' => 'image',
    '#path' => $field_value['uri'],
    '#alt' => $field_value['alt'],
    '#title' => $field_value['title'],
    '#width' => $field_value['width'],
    '#height' => $field_value['height'],
);

print drupal_render($build);


How to add php in views? I created a view, and I need to put some PHP or JavaScript in it. I would like to add some if conditions.

Is this possible?

Yes, it is possible.

If you want to use PHP in views header, you can go to configure header, select "Global: Text area" and have to change text format to PHP code; you have to first install the PHP filter module.

If you want to use PHP in view fields, you can use the Computed field module.

If you want to use PHP in a view itself, you have to customize your views and then you can easily add PHP code to it.


display only one comment in node page I'd like to display only 1 comment (the most recent one) in node page.
And I don't want the pager to be displayed too.

Is there any way to do it without writing custom module?

Could I use mytheme_preprocess_page($variables){} for that?

Thanks in advance.

First install and configure "Comment goodness" module - it will allow you to sort comments to display newest first.

Then in your template.php create.

function THEME_preprocess_comment_wrapper(&$variables) {
   // Remove pager.
   unset ($variables['content']['comments']['pager']);
   // Leave only latest comment.
   $last_comment_id = reset(element_children($variables['content']['comments']));
   $variables['content']['comments'] = array (
     $last_comment_id => $variables['content']['comments'][$last_comment_id]
   );
}


Ajax callback works only once I am using Drupal 7. I want to rebuild a part of form when a button is clicked. My form looks like this:

$form['me'] = array(
    '#type' => 'fieldset',
    '#value' => t('name'),
    '#prefix' => '
',
    '#suffix' => '
'
);

It contains various text fields and a submit button. The submit button looks like

$form['me']['save'] = array(
    '#type' => 'submit',
    '#validate' => array('save_validate'),
    '#submit' => array('save_submit'),
    '#ajax' => array(
        'wrapper' => 'me-wrapper',
        'callback' => 'me_ajax_callback'
    ),
);

in the save_submit function I set $form_state['rebuild] = true;

in ajax callback function

function me_ajax_callback($form, $form_state) {
    return $form['me'];
}

Now, what happens is first time when I click submit, the ajax returns data and replaces the wrapper. But, 2nd time when I do so, I get a POST Internal Server Error 500.

Looking around the Form API, I set $form_state['no_cache']=true; in submit handler and that prevents the POST error but still the AJAX response is empty.

It works fine if, I reload the page. So, in short, the first time I hit submit I get an AJAX response. On the second time, the response is blank.

Ok, I have solved the issue and this might help someone in future. I was dealing with a form which was actually a collection of various small forms. Each small form had various text fields and submit handler. So, when reloading a small form using AJAX I was setting $form_state['rebuild'] = true, this in process rebuilt the whole form in the back. But AJAX callback only rendered a small part of form into the wrapper. So, when I pressed the button again there was post error as Drupal was expecting values in new rendered form whereas it got a mixture of Old and new form.
    It happens because Drupal while rendering a form into HTML adds id to it, e.g., id = edit-save but when we rebuild it without reloading the page, it changes to something like id = edit-save--2 and which keeps on to increment every time it's rebuilt.
    So, if your form needs rebuilding, reload the whole form else set $form_state['rebuild'] = false and that should allow subsequent AJAX calls without any post error.


Themes, blocks, and content ... Oh my! I am a newbie to Drupal/Acquia Dev Desktop. Please excuse me if this is a dumb question.

I'm trying to grasp the relationship between themes (the one I chose is Corked Screwer), blocks, and content. In Corked Screwer there are images on the top half of the page/node and my content is at the bottom.

Am I understanding correctly that Content/main page content is where my typed-in content is displayed? I can control this with Visibility Settings/Content Types, etc. Yes?

How do I go about customizing the top half of the page to replace the default images with my own? Can you point me to a good video tutorial?

Thanks!

Yes, the Main page content block is where your content will render. Yes those visibility settings control on what page/content type/role will show that block content area. Typically, you want to leave this block alone since it's the main presentation of your content (what's the point of having a page if it doesn't have any content?).

It looks like the CorkedScrewer's default home page is more a demo template to demonstrate its block regions; you can't replace the images without overwriting the existing ones in its images folder.  It can vary based on the theme developer, but usually you can control a theme's slideshow images from its settings page in /admin/appearance.


Pathauto doesn't work anymore when i change the default language I've got a big problem this morning.

I'm working with english as default language Administration » Configuration » Regional and language. It's much more easy to me to work with the interface in english.

But this morning i have to change the default language to french because my boss want the interface in French (and the website is almost finished)

But unfortunately, all my alias doesn't work anymore like before www.example.com/my-article is becoming www.example/node/5.
More precisely, it's only alias from content type who doesn't work fine because taxonomy term are ok.

Does someone has a idea why when i changed the default language in Administration » Configuration » Regional and language (english to french) my alias didn't worked anymore?

This happens because the table url_alias has a language property that doesn't match anymore with the default language. Try to change the language code to your default language or delete the information. (Of course, make a backup before in case of).


Can DS manage "admin tabs" placement for a node? Is there an existing sub-module or someplace i'm not looking for Display Suite to allow me to arbitrarily place the View, Edit, Revisions, Manage Display, Devel tabs that appear when viewing a Node... say I want to move them to a different place in any DS template like Right or Left.

After some looking around, I've found the following two approaches:

Use DS's 'dynamic field'
Use DS's 'preprocessor field'

Dynamic Field

Create a Dynamic Field (in /admin/structure/ds/fields) for Node entities.
Go to the 'manage display' of your content type and place the dynamic field somewhere.
Click 'Select Content' on the field settings (through manage display)
Select 'Page Elements'
Select Tabs, and save

Preprocessor Field

Not 100% working for me right now, however just to give the basic idea:

Create a preprocessor field in DS and add the field to your content type.
In your template.php file, instantiate the field:

function YOURTHEME_preprocess_node(&$vars) {
  $vars['nameoffield'] = print render(menu_local_tabs());
}

I'm currently getting some errors with the preproccessor approach, however the dynamic field approach is working fine.


Order nodes based on entity reference filter In my Drupal 7 website I have an A content type with an entity reference 'parent' field which I use to link to nodes of a B content type.

I have to implement a way to sort A nodes basing on their B parent.

Modules such as Nodeorder and Nodequeue (smartnodequeue) can achieve this with term references. Is there any way to sort them based on entity references without creating vocabularies and term reference fields? I would prefer a draggable solution.

Create a view that shows Content of type "A", add a relationship for Entity Reference: "B".  Then add a sort criteria and sort by Content "A".  Choose the relationship on the sort criteria as the relationship you made earlier.  You can expose the sort order so it can be chosen to sort ascending or descending.  This is not a draggable solution but it does allow you to sort by the referenced entity.


how to setup cron to run everytime when new file is generated in drupal files folder I created webform and saving submitted data into text file in drupal files folder. A remote script performs calculations and outputs new text file  to the same folder . I want cron to run everytime text file is generated, so that i can print result from text file to webform and also save them to database

So far i created custom module for webform and used hook_cron() as shown below

function simulation_ignition_view_cron()
 {
  $uri = 'default/files/simulation/generatedfile.txt';
  if (file_exists($uri)) {
  drupal_set_message("hello cron");
 }
}

Please let me know if my explanation is not clear and please give some suggestions

I want cron to run everytime text file is generated

I think you're misunderstanding what cron is. Cron is

  a command to an operating system or server for a job that is to be executed at a specified time.

It doesn't respond to file system triggers, it's a scheduled task.

If a file is created as part of the normal Drupal content add/edit, you can just implement hook_file_insert():

function MYMODULE_file_insert($file) {
  if ($file->uri == 'foo') {
    // Do something.
  }
}

If you want to start the scheduled jobs running in that hook you can use drupal_cron_run(), but it would probably make more sense not to involve cron in this.


Show password button I'm developing a module and in the settings page I've inserted a text field to allow users to insert a key.

I thought to change this into a password field but I want to also create a Show password button or a checkbox. How could I implement this functionality?

Password Toggle is already doing something of this sort. Code is simple and straight

Its basically a JS to be added at the right time.

function password_toggle_add_js_and_css() {
  $path = drupal_get_path('module', 'password_toggle');
  drupal_add_js($path . '/password_toggle.js');
  drupal_add_css($path . '/password_toggle.css');
}

You can borrow the module's js code for your module.


How to integrate Datatables in my Bootstrap theme (to make it match the look and feel of my site)? I am developing an intranet portal using a custom made bootstrap 3 theme.

One of the views I created is a phonebook with 4 columns: Name, Department, Telephone, Email.

When I use table as the view format, I get a really nice bootstrap table, as shown here:

But when I use the views style Datatables (provided via the DataTables module I have installed), I get a table which is fully functional (i.e. paging, search, sorting, etc works perfectly). But the css is not bootstrap, as shown here:

Any suggestions?

Have a look at what is described in http://www.datatables.net/manual/styling/bootstrap . Here is a quote from that link:

Bootstrap is a CSS framework that lets you quickly and easily build a user interface that has a unified look and feel. The great news is that it is very easy to integrate Bootstrap and DataTables such that your fully featured DataTables will match the same look and feel of the rest of your site.
Bootstrap provides a number of options for styling HTML tables, giving you flexibility over the table, while ensuring they look very slick. The DataTables / Bootstrap integration ensures that you can use all of these features as well as the enhancements that DataTables makes to a plain HTML table.
Installation:
To have DataTables styled by Bootstrap, all you need do, as well as including the DataTables core Javascript file on your page, is include the DataTables / Bootstrap CSS and Javascript integration files. These files simply alter the DataTables defaults, such as class names to use the names used by Bootstrap, and add styling information specific to DataTables.
Both files are both available on the DataTables CDN (below) or you can obtain these files directly from the DataTables integration plug-ins repository on GitHub.

Head over to that link above for more details ...
Bonus tip: there is also an interesting blogpost about this topic ...
PS: I consider Datatables (the module + the library) as one of those hidden Drupal gems, so easy to install/enable, such a great set of features it adds (paging, searching, sorting as you also mentioned). Can't think of a site where we don't use it ... Checkout the questions tagged with datatables for more interesting questions (+ answers) about it.


Disable the cache for a specific view I'm showing my users a random number ({{ random() }}) in a twig which is being rendered in a view. But when I refresh a page it just shows me the same number.

I tried several things but they all failed:

Disabled caching in admin/config/development/performance
Disabled cache in views advanced settings
tried to use cacheexclude module
I even disabled twig cache!

How can I completely disable cache for specefic twig or specefic view?

Update:

By the way in response header there is a header called x-drupal-cache:HIT. (It's MISS for the first time and then HIT after first load) Why?

Update 2:
I uninstalled Internal Page Cache too. the x-drupal-cache is gone now but the page is still being cached! I literally disabled everything but still no luck to show a random number in twig in a view..

This is my response header if it helps:

cache-control:must-revalidate, no-cache, private
content-encoding:gzip
content-type:text/html; charset=UTF-8
date:Wed, 28 Feb 2018 14:26:47 GMT
expires:Sun, 19 Nov 1978 05:00:00 GMT
server:nginx
status:200
strict-transport-security:max-age=15768000
vary:Accept-Encoding
x-content-type-options:nosniff
x-drupal-dynamic-cache:UNCACHEABLE
x-frame-options:SAMEORIGIN
x-generator:Drupal 8 (https://www.drupal.org)
x-ua-compatible:IE=edge

Solution:

I uninstalled Internal Cache module and ALSI big pipe module too.

Unfortunately point 1 doesn't work for anonymous traffic.

You have to uninstall the Internal Page Cache module.

Or trigger

\Drupal::service('page_cache_kill_switch')->trigger();

in a view hook.

When the View is placed on most or all pages then uninstall the Internal Page Cache, because the page cache kill switch also disables the dynamic page cache and you don't want to disable both caches, unless this is only for a few pages which don't have too much traffic.

Additionally you need point 2 (disabled cache in views advanced settings) in any case.

Update:

  By the way in response header there is a header called
  x-drupal-cache:HIT. (It's MISS for the first time and then HIT after
  first load) Why?

This header is generated by the Internal Page Cache, a HIT means it is served from this cache.


How to programmatically update a user role name I would like to update role name programmatically in Drupal 7. Does Drupal provide its own functions to do that, or do we need to query the database and  update the name manually?

Please note that this is not about changing the role a user has, but changing the name of a role.

Information about user roles should never be loaded/saved directly from the database, but using the functions the User module provides, such as:

user_role_load($rid)
user_role_load_by_name($role_name)
user_role_save()

As for changing the role name, that is not as simple as editing the role object and saving it, since the role name is required to be unique. (The name field, in the database, is the unique key for the role table.)

Before saving the role object, the code should verify the name is not already used, as the following code does.

// Load the role object from the database into the $role variable, using user_role_load()
// or user_role_load_by_name().
// The $role_name variable is assumed to contain the new name you want to give to the role.

if (!(bool) user_role_load_by_name($role_name)) {
  // There isn't a role with that name, so it's possible
  // to change the role object and save it.
  $role->name = $role_name;
  user_role_save($role);
}
else {
  // There is already a role using that name.
  // Make the name unique, or abort the operation.
}

Using the functions made available from the User module is preferable, since it allows other modules to react to changes to roles. Those functions invoke at least one of the following hooks.

hook_user_role_insert()
hook_user_role_update()
hook_user_role_delete()
hook_user_role_presave()


Views Question - Related Taxonomy Terms I'm a Drupal noob, so this may be a simple question. I have two taxonomies created, one called Programs and another called Divisions. There is a "Division" field in the "Program" taxonomy. For example:

Programs

Math
English
Art
Communication
Biology

Divisions

Humanities
Science

Art, English, and Communication are all related to Humanities
Math and Biology are related to Science

I have used Views to build a page that will display information for each program. URL format is academics/programs/biology, academics/programs/art, etc.

I'm trying to create a Views pane that will display related programs, but I'm having some difficulty. Essentially, I want it to a display a list of programs that have the same Division. How would I go about accomplishing this since the URL does not have the Division term in it, but rather the Program term?

Any help would be appreciated.

Thanks!

If you put the hierarchical structure into the path you could use a contextual filter to show the related programs in a view. The path would look like: programs/humanities/English

The contextual filter would look at the taxonomy term in position 2 and show related programs (other humanities programs in this example)


Show block only in user own page and for administrator role users What I'm trying to achieve:

User can see block only on his own "user/[uid]/my-page" - he cant see that block on other users my-page.
Users who belong to administrator role can see user block on user own page.

Right now my code shows block for user himself and also to administrator role users BUT for administrator role users it shows block on every page - not only in "my-page".

How to modify code to show block only in "my-page" also for administrator role users?

Here is the code:

<?php
global $user;
if (in_array('administrator', ($user->roles))) {
return TRUE;
}
if (arg(0) == 'user' && $user->uid == arg(1) && arg(2) == "my-page" ) {
return TRUE;
}
else {
return FALSE;
}
?>

I used this code as a base: https://drupal.org/node/134433

This is almost a replica of your code with a small change. I hope it helps.

If you want to allow the admin to see the block on every other user profile page

global $user;
if (arg(0) == 'user' && ($user->uid == arg(1) || in_array('administrator', ($user->roles))) && arg(2) == "my-isn10") {
  return TRUE;
}
else {
  return FALSE;
}

If admin or normal user do not have a difference both can see only on their profile page.

global $user;
if (arg(0) == 'user' && $user->uid == arg(1) && arg(2) == "my-page" ) {
  return TRUE;
}
else {
  return FALSE;
}


"Edit This Page" functionality I've searched around for quite a bit but can't find the anwer. I'm trying to add a "Edit this page" functionality to my admin menu. Is there an existing feature or module that I'm missing which allows an admin to go directly to editing the page being viewed?

If such a module doesn't exist, can I create one?
I tried creating a link on my admin menu , but it doesn't seem to work:

function admin_edit_menu() {
     $items = array();
     $items['admin/misc'] = array(
      'menu_name' => 'management',
      'title' => 'Edit',
      'description' => 'Edit this page',
      'page callback' => 'http://www.mysite.com/node/' . $node->nid . '/edit',
      'access callback' => TRUE,
      'type' => MENU_NORMAL_ITEM,
      'weight' => -15,
    );
}

Assuming you're referring to the Admin menu module then you can head to the configuration page under admin/config/administration/admin_menu and under the System tweaks tab you can check the option for Move local tasks into menu.


Drupal 8, include a subtemplate in a form I created a Class form, then I can access to the page form and submit it. My form use the default template of my website.

When I submitted the form, I want redirect the user to the form page (the same page) and display some elements in front of page. Theses elements depends on the results of the form has been submitted.

I can easily do that with simples drupal messages, but instead, I would like to show more complex messages.

I think I can create a little template file and include it in my form. But I haven't any ideas how can I do that in Drupal 8, can you provide me a very simple example or tell me how I can include a sub-template in my form ?

I think my sub-template looks something like this (Pseudocode, not twig :) ) :

// the form return an array
    foreach formarray as element

element1

property1 : {element[property1}

property2 : {element[property2}

        ...
    end foreach
// I include this template in the form, if the formarray is empty, nothing is displayed (when the user load the forme the first time)

Thanks for help !

Most likely you are looking at adding to the "render array" of the page (or form). A render array can refer to a "type" or Render Element, and that type can render into a template.

The scenario of rendering after form submission on the same form can be done within the Form itself by setting the form state to rebuild.

  public function submitForm(array $form, FormStateInterface $form_state) {

    // Set the rebuild state to TRUE to persist $form_state when the form is reloaded.
    $form_state->setRebuild();
    $form_state->set('display_extra', TRUE);
  }

  public function buildForm(array $form, FormStateInterface $form_State) {

    // Conditionally display something from form state.
    if ($form_state->has('display_extra') && $form_state->get('display_extra')) {
      // Structure the render array here including setting up a custom RenderElement ('#type'), which has a custom template defined in hook_theme().
      $form['display_something'] = [];

    }

    // Rest of form...

    return $form;
  }


Cannot change an existing field's type. in field_update_field() line 240 of field.crud.inc My instance of drupal is throwing an error. The file that is throwing the error is modules/field/field.crud.inc

The error is

  FieldException: Cannot change an existing field's type. in field_update_field() (line 240 of modules/field/field.crud.inc).

A local var dump displays the following results.

Variable $field

array (
  'active' => 1,
  'cardinality' => 1,
  'deleted' => 0,
  'entity_types' =>
  array (
  ),
  'field_name' => 'field_address',
  'foreign keys' =>
  array (
    'format' =>
    array (
      'columns' =>
      array (
        'format' => 'format',
      ),
      'table' => 'filter_format',
    ),
  ),
  'indexes' =>
  array (
    'format' =>
    array (
      0 => 'format',
    ),
  ),
  'locked' => 0,
  'module' => 'text',
  'settings' =>
  array (
    'max_length' => 255,
  ),
  'translatable' => 0,
  'type' => 'text',
)

Variable $prior_field

array (
  'translatable' => '0',
  'entity_types' =>
  array (
  ),
  'settings' =>
  array (
  ),
  'storage' =>
  array (
    'type' => 'field_sql_storage',
    'settings' =>
    array (
    ),
    'module' => 'field_sql_storage',
    'active' => '1',
    'details' =>
    array (
      'sql' =>
      array (
        'FIELD_LOAD_CURRENT' =>
        array (
          'field_data_field_address' =>
          array (
            'country' => 'field_address_country',
            'administrative_area' => 'field_address_administrative_area',
            'sub_administrative_area' => 'field_address_sub_administrative_area',
            'locality' => 'field_address_locality',
            'dependent_locality' => 'field_address_dependent_locality',
            'postal_code' => 'field_address_postal_code',
            'thoroughfare' => 'field_address_thoroughfare',
            'premise' => 'field_address_premise',
            'sub_premise' => 'field_address_sub_premise',
            'organisation_name' => 'field_address_organisation_name',
            'name_line' => 'field_address_name_line',
            'first_name' => 'field_address_first_name',
            'last_name' => 'field_address_last_name',
            'data' => 'field_address_data',
          ),
        ),
        'FIELD_LOAD_REVISION' =>
        array (
          'field_revision_field_address' =>
          array (
            'country' => 'field_address_country',
            'administrative_area' => 'field_address_administrative_area',
            'sub_administrative_area' => 'field_address_sub_administrative_area',
            'locality' => 'field_address_locality',
            'dependent_locality' => 'field_address_dependent_locality',
            'postal_code' => 'field_address_postal_code',
            'thoroughfare' => 'field_address_thoroughfare',
            'premise' => 'field_address_premise',
            'sub_premise' => 'field_address_sub_premise',
            'organisation_name' => 'field_address_organisation_name',
            'name_line' => 'field_address_name_line',
            'first_name' => 'field_address_first_name',
            'last_name' => 'field_address_last_name',
            'data' => 'field_address_data',
          ),
        ),
      ),
    ),
  ),
  'foreign keys' =>
  array (
  ),
  'indexes' =>
  array (
  ),
  'id' => '132',
  'field_name' => 'field_address',
  'type' => 'text',
  'module' => 'text',
  'active' => '1',
  'locked' => '0',
  'cardinality' => '1',
  'deleted' => '0',
  'columns' =>
  array (
    'value' =>
    array (
      'type' => 'varchar',
      'length' => NULL,
      'not null' => false,
    ),
    'format' =>
    array (
      'type' => 'varchar',
      'length' => 255,
      'not null' => false,
    ),
  ),
)

This is my solution to this problem, i'm going to also document how I found the solution.

If you see the message that something went wrong stop and look at the logs that Drupal reports back to you and take the time to read them.

In this example I was getting this error due to a specific module and when Drupal was faulting out the module basic_cart_order was the last one to be rebuilding based on the logs.

Now that I knew what module was faulting out it was time to find out why. I found the fields that where causing the message field_address and I looked within in that module for that value.

grep -R "field_address"

That brought me over to this file

sites/all/modules/basic_cart/basic_cart_order/basic_cart_order.features.field_base.inc

I opened up that file and made a couple of changes to all the fields that where causing a conflict to the database. You can find all the fields that cause the error in your log message. I added a prefix to all the fields with basic_cart_order.

This fixed the problem down to the line that was throwing the error.


Ajax Exposed filter isn't changing URL There must be something obvious I'm missing as it seems from other posts that Exposed Filters in views should generate URLS from its results out of the box.

I've got some filter with ajax enabled and they work fine, but the url doesn't change when using the filter.

How to I achieve this and become able to link to a specific setting on the filter?

Exposed filters do create/update the page URL. You can construct a link with a combination of values for your Exposed filters and the Views results will react to it by displaying the "correct" results narrowed down to what is set in the URL.

The confusion you're having is the Ajax option. Ajax (asynchronous JavaScript and XML) option fetches only a particular part of the page data and replaces the old set of that part of the page.

Ajax doesn't reload the entire page.

URL requests are related to entire pages, the URL in your browser can't change without a Page Reload/Refresh.

The Ajax option in Views even tells you:

  Options such as paging, table sorting, and exposed filters will not initiate a page refresh.

With Ajax option turned on the Exposed filters are still working correctly, you get changes in your results based on the applied Exposed filters. But the changes happen without the page reloading so the URL doesn't change. It can be confusing if you at that moment compare the currently enabled Exposed filter options with the Exposed filter values in the URL, because they won't match. But that is just the circumstances of using Ajax.

With Ajax on you get better responsiveness/speed just because there is no page reloading, but the URL might be misleading, if that is what your users pay attention to at that moment.

But turning Ajax on doesn't prevent you from constructing specific Exposed filter combinations in URLs!

You can create different URLs for a Views page, add them to a menu, when the user clicks on it they will get the filtered out results and the Exposed form options will match the URL ones. Then users can interact with the Exposed form and with Ajax on the URL will not change but the results will.

Without the Ajax option turned on each change in the Exposed form will trigger a page reload, which makes things less interactive/fast, but the URL options will match what you see on the Exposed form.


Is it possible that a view list entities that are not related to other (like a not in (select ...) )? I have been trying to build a view to list entities A that are not related with entities B.

Entities A are users. Entities B are submissions. I need to list users that don't have submissions for a certain year.

In SQL it would be: select uid from users where uid not in (select uid from submissions where year = NNNN).

Is there a way to do this using Drupal 7 and Views 3?

Views is a simple query builder, it's UI doesn't really support this out of the box.

I recommend looking at Views Custom Conditions:

  This Views Custom Conditions module facilitates the site administrator
  to inject custom conditions into a views query. ‘Views’ is a powerful
  and highly flexible module that provides website builders with
  critical list making abilities. It generates a dynamic SQL query
  according to views construction for displaying data. So, adding a one
  more step to filter your data as per your requirement, this module
  will really be helpful.

  This module adds the condition specified by the site admin to any
  views where clause with the existing conditions implemented by views
  itself in conjunction with AND operator.

Also if you want to do custom calculations on Fields see Views Raw SQL or Views Calc.


How to make custom URL mandatory? I'd like to force users to customize URL. How to make the following field mandatory?

The path alias is a field, so you just need to alter the form and set the #required property on the element:

function module_form_node_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $form['path']['widget'][0]['alias']['#required'] = TRUE;
}


ul list with ajax items is not build correctly I have an ul list, which is build with default items, depending on a dropdown value.
When I change the dropdown, the area with the ul should be replaced by ajax with new items depending on the selected dropdown value.
The problem is:
After replacing the div with the ul inside, the ul tag is opened and closed immediately, the li items are generated directly after the ul closing tag.
Here is some sample code:

 $drop_value=isset($form_state['values']['dropdown'])?$form_state['values']['dropdown']:$default_value;
 $form['images']['drop_area'] = array(
  '#markup' => '

        '.get_items($drop_value).'

',
  '#prefix' => '
',
  '#suffix' => '
',
);
function get_items($drop) {
  ...
  //builds li elements
  return $li_elements;
}

The ajax event is assigned to the dropdown.
The output is correct after loading the page with the $default_value.
After changing the dropdown, the li elements are generated correctly, but the resulting html looks like this:

item

...

Why do the li elements are generated outside the ul, although the function for generating the items is called inside the ul markup?
I also tried to declare a variable before the markup, holding the result of the get_items function, but this has the same effect...

Thx.

$drop_value=isset($form_state['values']['dropdown'])?$form_state['values']['dropdown']:$default_value;
$form['images']['drop_area'] = array(
'#markup' => '

    '.get_items($drop_value).'

',
'#prefix' => '
',
'#suffix' => '
',
);
function get_items($drop) {
  ...
  //builds li elements
  return $li_elements;
}

In your above code try after remove the "/" at the end of ul tag.

Then your code should be :


Is there a tool to covert any template to drupal 7 theme? Is There any tool to convert any template (wordpress, joomla, static html/css etc) to a drupal theme

Nope! :)

There is, however, a nice page full of information to convert Drupal 6 themes to Drupal 7: link


How can I add a variables to my page.html.twig file? I'm trying to add a variable that i can use in page.html.twig that will add a class to the header region if a field in the node exists.

In template_preprocess_page() i've tried doing the following and have not been able to add a variable:

function theme_preprocess_page(&$variables){
  $variables['header_attributes']['class'] = [];
  $variables['header_attributes']['class'] = array_merge($variables['header_attributes']['class'], ['myClassHere']);
}

I based this off the example for menu preprocess but no new class was added to the  ta

There is no index called header_attributes inside $variables array no need to create it, there is page index just use it:
Try this out:

function [yourThemeName|yourModuleName]_preprocess_page(&$variables){
  $variables['page']['header_attributes']['class']= 'myClassHere';
}

Note don't forget to clear cache.
In your twig you will get your class by:

page['header_attributes']['class']


EntityFieldQuery HAVING clause Is there any way I can use having clause with EntityFieldQuery? I want to get the nodes which have same field value similar to HAVING clause in SQL. Or do I need to do other ways? Please suggest if there is any good way to do this.

You could subclass EntityFieldQuery and add a having() method, or (probably quicker) you can add a tag to the query, and use hook_query_TAG_alter() to alter it when it's a standard SelectQuery:

function MYMODULE_query_my_tag_alter(QueryAlterableInterface $query) {
  $query->having('some_field > :val', array(':val' => $some_val));
}

To use that with your query:

$query = new \EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->fieldCondition(...)
  ->addTag('my_tag');


How to use Drupal Code Sniffer in windows? How do you configure and use Drupal Code Sniffer in Windows?

On the project page there are instructions for each IDE.

The one you're after (Eclipse) is here.

In case anyone uses something else, the other instructions are as follows:

Vim, Sublime Text, and Komodo

Netbeans

PHPStorm (install the Codeing Standards globally first, as described here, then Drupal should be available in the list or rulesets.

You won't get this working in Notepad.

On another note, I'd probably also just stop using Notepad.  If you must use a basic tool, then Notepad++ is a million times better.


What is replacement of SSL/HTTPS in drupal to encrypt login credentials I have one question, in my website i am not using ssl so my drupal login send id and password as plain text, then i have used the encrypt_sumissions module but that is use jcryption library but this is not useful, I want to know how can i encrypt login credentials without ssl/https.

Should I change in drupal core, I am new to this please provide me detailed information.
Thanks

Save yourself the headache and use TLS/SSL. Drupal won't, and isn't meant to, solve your problem. It isn't worth trying to cobble something together. If the cost of the certificate is an issue, go to https://letsencrypt.org/ and get a free cert.


What are [meta] issues on D.O? On drupal.org, what are exactly meta issues? Meta issues meaning issues that contain the word [meta] at the beginning of the issue queue on drupal.org.

Issues that contain other smaller issues?

'meta' loosely means 'about', like the discussions on the meta site here. They are about the site, not drupal. Meta Tags are about the page, placing it in context. The [meta] issues are not about functionality, but rather about policy, code-cleanup, documentation, standards etc., rather than regular (functional) issues which are about achieving a result through code.


How to open pop up window in javascript in drupal 6? I have made a custom module in Drupal 6 and want to implement the following: When I click on my link it should open in a pop up window in javascript. But I don't know it how to implement pop up window in Drupal.

Please help me.

This is my link code.

l('open pop up','admin/state_user/stateadmin/state/user/disable/'
  . $result -> uid, array('attributes' => array('title' => t('open pop up'))),TRUE);

Use the Colorbox module.

  Colorbox is a light-weight customizable lightbox plugin for jQuery. This module allows for integration of Colorbox into Drupal.

  Images, iframed or inline content etc. can be displayed in a overlay
  above the current page.

You need to activate the iframe method and add the custom iframe class to your link.


Overriding an entity add/edit form through alterroute I want to create my own version of the add/edit form for an entity defined in contrib module (drupal_commerce). I assumed i'd be able to adapt the example here http://www.foreach.be/blog/how-manipulate-forms-drupal-8 to alter route for entity forms. However i am getting the following when i try to load edit

  Fatal error: Call to a member function getEntityTypeId() on a non-object in C:\xampp\htdocs\tocyn\core\lib\Drupal\Core\Entity\EntityForm.php on line 82

My route subscriber looks like:

    if ($route = $collection->get('entity.commerce_product.edit_form') ) {
        $defs = $route->getDefaults();
        $route->setDefault('_form', '\Drupal\mymod\Form\EventForm');
    }

And my new form:

class EventForm extends Drupal\commerce_product\Form\ProductForm
{
   public function buildForm(array $form, FormStateInterface $form_state)
   {

      // doing nothing much here
      return $form;
   }
}

Do i need to do something with _entity_form also??
Grateful for any feedback
Mathew

Alternatively, you can use hook_entity_type_alter() to override the default form handler classes. It would be something like:

/**
 * Implements hook_entity_type_alter().
 */
function mymod_entity_type_alter(array &$entity_types){
  $entity_types['commerce_product']->setHandlerClass('form', array(
    'edit' => 'Drupal\mymod\Form\EventForm'
  ));
}


How to get CCK optionsfield value, if I have the key for that value? I have a CCK select list where I defined key|value pairs.

When I execute a node_load for that node, I only get the key (in my case an integer) stored in Drupal.

How can I get the value of that key easily? Is there a Drupal function?

something like, cck_value('field_name',$key) ?

Node_load will return fully-populated node object.

Value of cck fields in node object are usualy accessed in this way:

 $my_node_object = node_load($nid);
 $myVar = $my_node_object->field_your_field_name['0']['value']

You can see what $node object contain if you do

dsm($my_node_object); // Devel module must be turned on

Hope this helps.


Fatal error when altering the user login form i want to customize login block in a fancy login box.

i used this code in a template.php

function bootstrap_form_user_login_block_alter(&$form, &$form_state, $form_id) {
  $form['name']['#size'] = 30;
  $form['pass']['#size'] = 30;
  $markup = l(t('Forgot your password?'), 'user/password', array('attributes' => array('title' => t('Request new password via e-mail.'))));
  if (variable_get('user_register', USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL)) {
    $markup .= ' ' . l(t('Sign up'), 'user/register', array('attributes' => array('title' => t('Create a new user account.'), 'class' => 'register-link')));
  }
  $markup = '
' . $markup . '
';
  $form['links']['#markup'] = $markup;
  $form['links']['#weight'] = 10000;
}

this code working fine, but on clicking singup link it giving error

  Fatal error: [] operator not supported for strings in C:\xampp\htdocs\drupal\includes\common.inc on line 2445

How do I resolve it?

Looks like the problem is your class definition.

['attributes']['class'] should be an array but you are setting it as a string.

Your line:

$markup .= ' ' . l(t('Sign up'), 'user/register', array('attributes' => array('title' => t('Create a new user account.'), 'class' => 'register-link')));

Should be:

$markup .= ' ' . l(t('Sign up'), 'user/register', array('attributes' => array('title' => t('Create a new user account.'), 'class' => array('register-link'))));


How to stop same-state state changes in Workflow state change block? I am using Workflow with a custom content type. I have the Workflow state transition form as a sidebar on my node view page. I made the workflow states into buttons so that you can choose which state to transition to.

How can I remove buttons that are the same state as the node? For example: If the node is already in Draft state, the Draft button should not be shown. If it's in Declined mode, the Declined button should not be shown.

Implement hook_form_workflow_transition_form_alter().

/**
 * Implements hook_form_form_id_alter().
 * Alter transition form to remove current state button.
 */
function MYMODULE_form_workflow_transition_form_alter(&$form, &$form_state, $form_id) {

  // Get current state to remove current state button.
  $current_sid = $form['workflow']['workflow_sid']['#default_value'];
  unset($form['workflow']['workflow_sid']['#options'][$current_sid]);

  // By default workflow button label became (Update workflow) if the options
  // count equal one. So, We will use the state label name instead of
  // (Update workflow).
  // Check if option count equal one.
  if (is_array($form['workflow']['workflow_sid']['#options']) && (count($form['workflow']['workflow_sid']['#options']) == 1)) {
    $submit_label = current($form['workflow']['workflow_sid']['#options']);
    $form['workflow']['actions']['submit']['#value'] = $submit_label;
  }
}


How to filter views result using the views_php module? I have 2 integer fields in views , first field is 'field_code' and second field is 'field_rank',
Finally I want filter views result, with views_php module.
I use this code but it does not work,

$math = ($row->field_code / $row->field_rank) * 100;
if ($math < '30') { return TRUE; }

Please can someone help me to fix this problem.

It is a Drupal bug that is in active state until date but there are some work-arounds, one of them I am sharing with, if it could help you out.
Use $data variable to access your fields value because $row only gives numbers, which appear to be node ID's (Drupal Bug).

Use the following code I wrote in Global:PHP 'filter code' text area

$field_code = $data->_field_data['nid']['entity']->field_code['und']['0']['value'];
$field_rank = $data->_field_data['nid']['entity']->field_rank['und']['0']['value'];

$math = ($field_code / $field_rank) * 100;
if ($math < '30') {
  return TRUE;
  // If you dont want to display the result otherwise use FALSE in place of TRUE
}

Use this code as it is in your view. It works perfect; I have tested it.


Views does not show content if any of fields from relationship are empty I have a view which displays fields from a content type but it also has a relationship to any entities which have a reference field to a node of this content type.

I have things like a title and body text plus some custom text fields on the view, the title and body are from the node.

However these do not display unless the referenced fields are not empty.

How can I get the view to display these fields still when the entity fields are empty?

You can achieve your requirement by unchecking Require this relationship option on relationship field.


How to write inner subquery in db_select() method? How can I write a subquery in Drupal 7? My query is the following:

SELECT N.nid AS n_nid
FROM   workflow_node WN
LEFT OUTER JOIN node N
ON WN.nid = N.tnid
WHERE ( WN.sid IN (SELECT WT.sid
  FROM (SELECT sid,
    Concat(',', roles, ',') AS role_stamp
    FROM workflow_transitions) AS WT
  WHERE  role_stamp LIKE '%5%')
AND N.language = "en" )

You can assign your sub query to a new variable say subquery and pass it to the db_select using

$query->condition('WN.sid', $subquery, 'IN');

You can know more about this by visiting this page.


Create table while installing my custom module My custom module name is "person" and its .install file has the following code.

<?php
/**
 * Implementation of hook_install().
 */
function person_install() {

  drupal_install_schema('person');
}

/**
 * Implementation of hook_schema.
 */
function person_schema() {

  // Static (meta) tables.

  $schema['person'] = array(
    'fields' => array(
      'pid'            => array('type' => 'int', 'length' => 11, 'not null' => TRUE, 'default' => ''),
      'name' => array('type' => 'varchar', 'length' => 50, 'not null' => TRUE),
      'city'        => array('type' => 'varchar', 'length' => 50, 'not null' => TRUE),
      'country'        => array('type' => 'varchar', 'length' => 50, 'not null' => TRUE)
    ),
    'primary key' => array('pid'),
  );
return $schema;
}

But when I installed my module the table has not been created.Any thing wrong with this code?

In your schema your setting pid  as primary key. You are setting '' value for primary key. Remove that default value for pid and try.

Then your code should be:

<?php
/**
 * Implementation of hook_install().
 */
function person_install() {

  drupal_install_schema('person');
}

/**
 * Implementation of hook_schema.
 */
function person_schema() {

// Static (meta) tables.

$schema['person'] = array(
  'fields' => array(
    'pid'            => array('type' => 'int', 'length' => 11, 'not null' => TRUE),
    'name' => array('type' => 'varchar', 'length' => 50, 'not null' => TRUE),
    'city'        => array('type' => 'varchar', 'length' => 50, 'not null' => TRUE),
    'country'        => array('type' => 'varchar', 'length' => 50, 'not null' => TRUE)
  ),
  'primary key' => array('pid'),
  );
return $schema;
}

After edit the code don't disable and enable the module, hook_install will only call at module install process, so you should first disable the module, unistall the module and then install the module again.


Taxonomy menu expanded with count I have an accordion menu (taxonomy menu) as a block.

I want to have a very similar block but this time I want to have all taxonomy items expanded. I am thinking to something like this:

How can I accomplish that?

I have scoured the web, banged my head on the keyboard a few times, and finally settled to the fact that there is currently no viable way of achieving this with taxonomy menu.

A simple solution that should work though I have not tried it is using views to achieve the desired effect. I quickly googled that up and came across someone with the same/similar requirement here; http://drupal.org/node/165417. Their questions seem to have been answered and I will therefore try my hand in that direction tomorrow.

Hope this helps.

Edit: Tried using views but had to upgrade to using the 6.x-3.0-alpha3 version. After that it worked perfectly. I used content taxonomy for the relationships with the settings to update core taxonomy vocabularies. Then, using views, I selected HTML list as the style and grouped by the cck taxonomy field.


CSS file is not attached I set at the .info module file the parameter to add a css file,

stylesheets[all][] = css/style.css

but it is not attached even if I clear the cache.

I have look for the web to get the reason but apparently is all I might have to do.

Anybody could tell me what am I missing please? Here the code: https://github.com/jmvelasco/drupal

The js files are attached.

Thanks in advance.

It could be as simple as just clearing cache or just visiting the 'modules' page in your admin. The content of .info files is cached and isn't reloaded with every page visit.


Views partial Contextual Filter on username I have a view of users with a contextual filter for username which works great for whole usernames, but I need to allow this to work with partial names, or specifically whole words (userames are full names with spaces in this case), so if someone search for 'David' it will list all the 'David's, regardless of their surname.

Any help?

EDIT: a bit more googling revealed this, which was able to solve my problem: http://n00bsys0p.co.uk/blog/2012/08/21/drupal-views-3-contextual-filter

You can achieve it by many way...make a relation with content:author and you will get all available options under user like (User: Name, User: First Name,User: last Name,User: Authentication name, User: Authmap ID, ) under contextual filter.


Can I override a theme function from a contributed module Per this question, Can I modify guestbook.module safely? I have overridden theme_guestbook_entry() from the guestbook.module file.  The problem is that my modifications are not taking effect. (Yes, I rebuilt the cache.)

I am following these instruction here, http://drupal.org/node/11811. I notice they don't mention contributed modules at all. Am I able to override these?

The page you are referring is for Drupal 5.

In Drupal 6, you alter a theme function defined in a module by defining the theme function, as in the following code. (Replace mytheme with the short name of your theme.)

// Drupal 6
function mytheme_guestbook_entry($uid, $entry, $comment_entry = NULL, $zebra, $confirm_delete = FALSE) {
  // Your own code.
}

// Drupal 7
function mytheme_guestbook_entry($variables) {
  // …
}

In Drupal 7, if you just want to alter the variables passed to the theme function, you need to implement the preprocess function for that theme function.

function mymodule_preprocess_guestbook_entry(&$variables) {
  // Alter the values passed to the function, such as $variables['uid'], $variables['entry'],
  // $variables['comment_entry'], $variables['zebra'], or $variables['confirm_delete'].
}

The code I shown works whatever a theme function is implemented in Drupal, or a third-party module.


Rewrite View Header into first views-row I need to rewrite/move the header of one View into the first row of that View.

Current View output:

view header text

output

output

output

output

output

output

Desired Output:

view header text

output

output

output

output

output

output

How can this be accomplished?

The views-row divs are then displayed inline in a responsive flex grid, so that each views-row div has the same height as its neighbor divs on that same row. Each views-row div is 25% width, so they are displayed in 4 columns (4 divs across the page, with subsequent divs wrapping in 4 additional columns below as needed).

I need the header to be part of that flex grid. I tried applying the flex grid markup to the "view-header" div and the "view-content" div, but it does not provide the desired result.

Thanks!

You can use hook_views_post_execute() or hook_views_pre_render() hooks. Provide you just an example, so you have to add validations and change format of $item variable youself, it depends of your views configuration.

/**
 * Implements hook_views_post_execute().
 */
function mymodule_views_post_execute(&$view) {
  $item = (object) array('node_title' => $view->header['area']->options['content']);
  array_unshift($view->result, $item);
}


New user email notification not being sent This is my first day using Drupal, and I apologize in advance for such a basic question.  I am using Drupal 7.26 with no modules installed and when I try to sign up new users the e-mail notification is not being sent.  I tried signing up with two different e-mail addresses and checked the spam folder in each account.  I also tried to find an answer on the internet but I'm not having much luck.  Can anyone provide some suggestions on how I might troubleshoot this issue?  I've been to my Administration>Account Settings and Administration>Site Information but I'm not seeing anything that looks obviously amiss.

Install and use the SMTP module: https://drupal.org/project/smtp - Period. Nothing comes close to using SMTP and you'll avoid current and future headaches. Details are below. Good luck!

Why sending via the server is bad:

The post recommended by Anil Sagar is good. However, based on my expertise with web hosts, especially DreamHost, you want to avoid at all costs sending emails from your server.

By default, Drupal sends email via the server it's residing on. That server might not have email configured. That server might have email configured now, not properly configured in the future. That server might get spam listed in the future. In summary, a lot of things might happen that leave you without email sending capabilities, and most probably you will not be notified of the issue.

Also, you're lucky that your email is "not working" as, in most cases, some emails via the server will be sent, others will not, which is even worse as you'll not even know you have a problem to fix.

Why sending via SMTP rocks:

When you send via SMTP, you're relying on an external dedicated mail server. Choose a solid mail server provider (Gmail, Yahoo, Zoho, etc) and you'll be on the safe side. They handle maintenance and everything for you and all you have to worry about is the first step which is setting up and installing the SMTP module.

Note about SMTP sending limits:

If you're sending a large number of emails, most good email providers will have a daily limit that you'll reach and they'll stop sending your emails. This is a way for them to fight spam. For Gmail, I think the daily limit is 250 emails, which is plenty for most needs. If you have larger volumes, you might want to buy a paid SMTP account with a large limit or consider something like: http://www.mandrill.com/ - You can send up to 12,000 per month for free. They also have a Drupal integration module: https://drupal.org/project/mandrill

And if you're sending a large number of emails via your own server, you're ending up on a spam list from day one and your emails will soon not even reach junk mail.


D7 - hook_menu causes page duplicates I want to create a page that render a template (.tpl) file with this:

hook_menu

    $items['news'] = array(
    'title callback' => 'check_plain',
    'title arguments' => array('News'),
    'page callback' => 'theme',
    'page arguments' => array('news', array()),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
);

hook theme

$items['news'] = array(
    'template' => 'templates/news',
);

All works well if i go to www.mydomain/news

But if i go to www.mydomain/news/aaaaa (that is a non existing page) i will see again the template page and not a 404 error page, why?

Is this a normal d7 behaviors and i need to fix this in a callback function?
...or i need to check into other code/modules that cause this bug ?

Yes, that's expected behaviour. From the hook_menu() docs:

  If there is no other registered path that fits the requested path better, any further path components are passed to the callback function.

Here's the bug report that was closed as "works as designed":

https://www.drupal.org/node/1091068


When using the boxes module, is it possible to export the region and visibility settings? I just installed the Boxes module and I added a box to my feature.  The box description and body were exported successfully, but the region settings (where in the theme(s) the box appears) and the visibility settings (show block on specific pages, etc.) were not.

How can I export the placement information for boxes as well?

Ah, I just realized there is an issue for this in the boxes queue.  As of May 2012, the issue has been resolved and this is now possible.