Menu callback error : Undefined offset: 4 in _menu_translate() I have created a menu item with form. Everything is working fine, but I am getting the following error message on the menu page.

  Notice: Undefined offset: 4 in _menu_translate() (line 777 of /home/sysop/old-server/heisenberg/includes/menu.inc).

The code I am using is the following.

/*
 *implements hook_menu
 */
function planet_extension_menu() {
 $items['admin/structure/feeds_admin'] = array(
'title' => 'Planet Extension',
'page callback' => 'main_table',
'access arguments' => array('access administration pages'),
'file' => 'planet_extension.admin.inc',
'type' => MENU_CALLBACK,
);

    $items['admin/structure/feeds_admin/manage/%/delete'] = array(
    'title' => 'Delete',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('delete_feed',4),
    'access arguments' => array('access administration pages'),
    'type' => MENU_LOCAL_TASK,
    'file' => 'planet_extension.admin.inc',
    );

    $items['admin/structure/feeds_admin/manage/%/submit'] = array(
    'title' => 'Approve',
    'page callback' => 'submit_feed',
    'page arguments' => array(4),
    'access arguments' => array('access administration pages'),
    'type' => MENU_LOCAL_TASK,
    'file' => 'planet_extension.admin.inc',
    );
    return $items;
}

file : planet_extension.admin.inc

/**
 * Function main_table().
 */

function main_table() {

  $header = array(

    array('data' => t('ID'), 'field' => 'id', 'sort' => 'asc'),

    array('data' => t('Title of Feed'), 'field' => 'title'),

    array('data' => t('Feed URL'), 'field' => 'url'),

    array('data' => t('TYPE'), 'field' => 'category'),

    array('data' => t('Submitted By'), 'field' => 'email'),

    array('data' => t('Operations'), 'colspan' => 2),

  );

  $query = db_select('planet_extension', 'p');

  $query->fields('p', array('id','title','url','category','email'));

  $table_sort = $query->extend('TableSort') // Add table sort extender.

                      ->orderByHeader($header); // Add order by headers.

  $pager = $table_sort->extend('PagerDefault')

                      ->limit(20);

  $result = $pager->execute();

  $rows = array();

  foreach($result as $res){

    $rows[] = array($res->id, $res-> title, $res->url, $res->category, $res->email,(l(t('Approve'), 'admin/structure/feeds_admin/manage/' . $res->id . '/submit')),(l(t('Decline'), 'admin/structure/feeds_admin/manage/' . $res->id . '/delete')));
}
  // If rows are not empty theme and display the rows.

  $output = '';

  if (!empty($rows)) {

    $output = theme('table', array('header' => $header, 'rows' => $rows, 'attributes' => array('id' => 'sort-table')));

    $output .= theme('pager');

  }

  else {

    $output .= t("No results found.");

  }

  return $output;

}

/*
 *Delete function
 */
function delete_feed($form,&$form_state,$variable) {
      $form['feed_id'] = array(
      '#type' => 'value',
      '#value' => $variable,
      );
    return confirm_form($form, t('Are you sure you want to delete this feed %variable ?',
    array('%variable' => $variable)), '/admin/structure/feeds_admin', 'Warning!! Would you like to continue with delete?', t('Delete'));
  }

/**
 * Delete given field
 */
function delete_feed_submit($form,&$form_state) {
    $id = $form_state['values']['feed_id'];
    $num_deleted = db_delete('planet_extension')
      ->condition('id', $id)
      ->execute();
    drupal_set_message(t('Feed %id successfully removed.', array('%id' => $id)));
    drupal_goto('/admin/structure/feeds_admin');
  }

/**
 *submit handler
 */
function submit_feed($variable) {
}

What is the % parameter in the url used for - a feed item maybe?

For that type of UI, you may need to add a load function and use a named parameter instead for the %

e.g:

/**
 * Implements hook_menu
 */
function planet_extension_menu() {
 // ...
 // ...
    $items['admin/structure/feeds_admin/manage/%pe_feed_item/delete'] = array(
    'title' => 'Delete',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('delete_feed',4),
    'access arguments' => array('access administration pages'),
    'type' => MENU_LOCAL_TASK,
    'file' => 'planet_extension.admin.inc',
    );
 // ...
 // ...
}

/**
 * Menu callback load function for pe_feed_item argument
 * This function loads the feed item
 * which is then passed as a page argument to the menu callback function
 */
function pe_feed_item_load($fid) {
  // Load feed item somehow from feed id and return it, e.g:
  return db_query("SELECT * FROM {pe_feed_item} WHERE fid = :fid", array(':fid' => $fid))->fetchObject();
}


Sort Views table field by alphabet Table field 'Manufacturer' is set to sort by ascending or descending and when you sort it. At first it looks like it's sorting by alphabet, it starts with A, B, C etc. but eventually ends up with A again at the bottom?

The Manufacturer field is a taxonomy term. I can recreate that on a new view just with this field and it still won't sort. Title field sorts fine.

update Looks like you can't sort a taxonomy term alphabetically in a Table View, to reproduce that just create a random view for a content type that has a random taxonomy field that is limited to 1, so you can enable Sort in the Table settings. And if you try to sort, it makes no sense, not alphabetical at all.

Taxonomy term fields are entity reference fields. They only store the reference to the entity, which usually a number that is the ID for that entity. In case of Taxonomy the reference fields store the TID (taxonomy term ID) which is the number you can see in the path when you edit the term in the admin area.

When you sort your table using the reference field, it will follow the number sort of the term IDs.

But you want to sort alphabetically using term names.

Term names aren't stored in node tables in the database, taxonomy module has its own tables. You have to pull the term data into your node views in order to use it as a sorting criteria.

To pull related data into views use Relationships.

In your case you have to add the Relationship for the Manufacturer taxonomy term field. After you add that Relationship you will be able to add a new field to your views called Taxonomy term: Name. You will be able to sort your table using that field, and the results will be sorted alphabetically!

Remove your original Manufacturer field if you don't need it for anything else, the Term name field should be able to work as a full replacement while also providing the alphabetic sort criteria.


Recursive multilevel taxonomy feeds Drupal 7 I am currently using 2 feeds of module Feeds to load a simple structure of nested taxonomies, with just 2 levels. I use two CSV files, one with the parent taxonomies, and the other with the children (see attached image to see the relationship through a PGUID, parent id).
But now the problem is that my client will want no 2 fixed levels, but 3, 4, or more, varying depending on demand. So I do not know how to optimize the load (it is running in a cron in Elyisia cron right now).
Must I create a new feed for each level? What happens if the levels differ from day to day? Is there any recursive solution to this - Multilevel Feeds or something ?

Note: the handling of the multilevel taxonomies should be done in just a single CSV file.

You can solve this by double running an import with only one master CSV and using the Skip hash check & Update existing terms settings within your importer.

Feeds tracks each imported item in the feeds_item table. As entries are imported, it adds the imported guid to the table and stores hashed value of the imported row within hash. This hash value is checked upon reprocessing so Feeds can skip any unnecessary updating (if the source data hasn't changed it doesn't need reprocessing).

If Skip hash check is enabled with Update existing terms set to Update existing terms, this forces Feeds to update regardless. For your purposes, the first import run will ensure that each feed item is in the feeds_item table. On the second import run, the hierarchy integrity will be restored as each pguid will have a valid guid reference in the feeds_item table.


Views taxonomy exposed filter, show tree/hierarchy in drop down menu I have an exposed taxonomy filter that allows the user the filter by term. The vocabulary is 2 tiers, however in the exposed filter menu the hierarchy appears flat.

Is there a method/module to show the hierarchy with indentation or prefixing child terms with "-", similar to the taxonomy term selection menu from the node edit form itself.

x-post from https://stackoverflow.com/questions/6222875/drupal-views-taxonomy-exposed-filter-show-tree-hierarchy-in-drop-down-menu

SOLUTION:

The filter Taxonomy: Term ID (with Depth) will display the option "Show Hierarchy In Dropdown" when you select the Dropdown widget.


Display Parent Menu Item in Menu Block I have a menu block that displays the sub-pages of a parent page. In addition to the sub-pages I would like at least the name of the parent page displayed but I cannot figure this out.

So in the image above, I would like to have 'About' displayed instead of the title of the block and with its sub-pages (children) below. It would be nice if I could do it in the block's template but I am sure it is more involved than that.

I found the answer through a patch in the menu block module.


Filebrowser thumbnails "can not create img for private://" I am using Drupal 8.7.5 and PHP 7.3.7 running on Apache 2.4.6.

UPDATE: I'm trying to make available a library of images to the public. I chose the content type of 'Directory listing' to do this. In the Directory listing I have configured a private file path (i.e. located outside of Web root) to hold the images. Apparently I have done something right as it is working except for the thumbnails. I get constant 404 errors in my apache logs and the other errors through the web interface seen in the images below.

What have I missed in terms of getting the thumbnails working? Am I missing an binary or library to render the thumbnails? Did I not create or configure a path for the thumbnails?

Below are some of the steps I have done to configure the Directory listing.

UPDATE On the server I have installed Druapl 8 using composer and drush to $APACHE_CONTENT/drupal. The drush site-install then goes to $APACHE_CONTENT/drupal/web (drupal app_root) and have added a 'private' path as $APACHE_CONTENT/resources. This puts the 'private' path outside of the drupal site's DocumentRoot. The permissions and ownership for the 'private' path are 775 and apache.apache. Also, a .htaccess file was auto generated for the 'private' path. It contains the following:

# cat .htaccess
# Deny all requests from Apache 2.4+.
<IfModule mod_authz_core.c>
  Require all denied
</IfModule>

# Deny all requests from Apache 2.0-2.2.
<IfModule !mod_authz_core.c>
  Deny from all
</IfModule>

# Turn off all options we don't need.
Options -Indexes -ExecCGI -Includes -MultiViews

# Set the catch-all handler to prevent scripts from being executed.
SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
<Files *>
  # Override the handler again if we're run later in the evaluation list.
  SetHandler Drupal_Security_Do_Not_Remove_See_SA_2013_003
</Files>

# If we know how to do it safely, disable the PHP engine entirely.
<IfModule mod_php5.c>
  php_flag engine off
</IfModule>

In drupal/sites/default/settings.php I have:

$settings['file_private_path'] = $app_root . '/../../resources';

Viewing the Configuration->Media->File system is see:

I've configured a private file path to use with content created via
Content->Add Content->Directory listing.

I have then used scp to copy files into the private path.

Through the web interface, I can browse through the content but I never see the thumbnails. I get errors above my content.

In the apache logs I see 404s for the thumbnails:

GET /system/files/styles/thumbnail/private/Images/JPG/Marshal_Hub.jpg?itok=QwQds55m HTTP/1.1" 404 11730

I have GD installed.

While I can browse all of the content in the 'private' paths, none of the thumbnails get generated.

What do I need to do to get the thumbnails working?

This is a workaround I used to solve the issue:

[https://www.drupal.org/project/private_files_download_permission]

I don't consider this 'magic' to be a fix. There is a lack of documentation and/or a bug in the filebrowser module.

How can one raise an issue with the developers?

PS: Also, now have another issue with the filebrowser module: sort order is not being honoured in Grid view!


Problem with multiple domains First of all, let me apologize in advance as this may be a poorly worded question.  My knowledge of Drupal is limited so I'm not even sure of the exact area where my problem is.  I'm looking for pointers in the right direction so I can do more research on my own for an answer.

The Original Situation

I have two domains - let's call them example.com and example.net.  The site was originally built for example.net and it is hosted at BlueHost with the following folder structure:

/root
    /public_html
        /drupal
            ... standard Drupal folders
            /sites
                /all (this is where all my site files are)

So basically, the entire Drupal installation is in a subdirectory of public_html. I can access URL's such as http://example.net/contact with no problem.  So far, so good.

The Wrinkle

Where it starts to get complicated is when we bought example.com.  As the primary domain, it points towards /root/public_html.  So, I dusted off my Apache skills and fashioned an .htaccess file to redirect .com to .net, like so:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^(www.)?example.com$
RewriteCond %{REQUEST_URI} !^/drupal/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /rings/$1
RewriteCond %{HTTP_HOST} ^(www.)?example.com$
RewriteRule ^(/)?$ drupal/index.php [L]

The Problem

Now, if I go to http://example.com/contact, it does come up with a Drupal page, so I know that the rewrite rules are working.  However, I get a page that says that The requested page "/contact" could not be found.

I want users to be able to use either domain.  That is, http://example.com/contact and http://example.net/contact should go to the same page.  So this is where I'm stuck.  I'm not even sure where the general area of the problem is.  Do I need to set up a multi-site configuration?  That doesn't sound right because I'm only running one site.  Is it something to do with the domain access module?  That sounds more like something to run multiple sites of one Drupal installation.  Any pointers at all will be greatly appreciated.  Thanks in advance!

If you're on Cpanel just point both domains to same siteroot folder.

Otherwise create a symbolic link of folder2 to folder1 where folder1 and folder2 and siteroots of each domain.


How to export only content, strictly core content like articles, pages, users, taxonomy ect? How to export only content, strictly core content like articles, taxonomy ect?

Is there a way to export content only, no data about modules, only content that will work with drupal core install.

Just data that is  not affected by modules and configurations.

With Joomla I could do this via PHPmyadmin.

Any easy way to do this with Drupal 7, any module?

I see an exclude tables option in backup migrate.

You may omit specific tables, or specific table data from the backup
file. Only omit data that you know you will not need such as cache data, or tables from other applications. Excluding tables can break your Drupal
install, so do not change these settings unless you know what you're doing.

But I'm looking for an include only option, not exclude what you don't want.

There are several ways to achieve this

Use migrate module
Use Node Export Module
Use Feed Module
Or you can use web services to achieve this. For example expose data in services and import those data back in the other drupal site. (Very easy approach)
You need to check the database structure a bit and write a custom php script to take data from one table and insert it into another.


How should I use drupal_lookup_path()? I want to get the node ID to load the nid fields.
How can I get the node ID from the current URL using this function?

That's not what drupal_get_path() is for; it's for getting the internal router path for a URL given a path alias, and vice versa. It also allows you to wipe aliases, but it's not a good way to try to get the current page's node ID.

What you're looking for is the arg() function, which simply splits the current router path (the value contained in $_GET['q'], which for a node page will be, for example, node/1).

// With a router path of node/123
$entity_type = arg(0); // $entity_type is equal to 'node'

$nid = arg(1); // $nid is equal to 123


Setting a View's Menu Item to a Sub-Menu I'm using Drupal 7.10 and Views 3.1.

This seems like it should be simple but I can't find an answer. I have a menu structure similar to the following:

Main >
    About Us >
        History
        Contact Us
    Members >
        Wiki
        Tasks

The problem is that tasks is a view page but I can't seem to add the view to anywhere but a direct child of Main, there doesn't seem to be a way to add it so that it is a child of Members.

I can simply add a link to the page by adding another menu item but this causes the sub-menu to disappear so that, in this case Wiki disappears.

Is the only way to do this to add a block and add that block to a page? Or am I missing something?

Thanks!

Okay, so if I understand correctly you have a View Page that is part of your main site hiearchy (main menu).  Unfortunately you can only assign a View (at least through the View interface) to a particular menu, but not any of the children of that menu.  This should be a feature request in the Views issue tracker.

What you need to do is go edit the Main Menu through Administration -> Structure -> Menus, list links for Main Menu, and then find your Tasks page that was dropped in their (should be on the first level) and re-position it to where you want it in your menu hierarchy.


Hook to run code after a rule has been executed I have a module which performs a specific task. The task itself runs fine, though it also needs to be exectued when a specific rule is triggered. Is there a hook for rules which I can use in my module to check if a specific rule has been fired?

You can make that "specific task" as an action to a rule using hook_rules_action_info and add that action for the rules which you want to exectue.


7.26 /admin, /user not found on Localhost I am new to Drupal. I developed a site on a server and now migrating it on my personal computer (Windows 8.1). The site is working fine as it should.

My problem on localhost is that when I log in to my site (using this url: localhost/drupal_site/user/login) with an admin userid, it redirects me to the "404 Page(url: localhost/drupal_site/user)" on submission of correct username/password, And neither the admin menu bar occurs on the site.

I've tried modifying .htaccess, httpd.conf, cleaned cache tables in database and clean urls etc.

In .htaccess i've write:

'RewriteBase /drupal_site'

In httpd I've wrote:

<Directory "C:/xampp/htdocs/drupal_site">
    AllowOverride All
</Directory>
AccessFileName .htaccess

Its ironic that I've tried various solutions found with drupal community, but none of them really worked for me.

My Drupal Version is 7.26.

Xampp: Apache/2.4.10 (Win32) OpenSSL/1.0.1i PHP/5.6.3

Can anyone help me resolving this?

This issue might be a variation of the question about "drupal /?q=user is working but /user not working". So verify if you can use an URL containing ?q=user or ?q=admin. If that gets you going, then probably tuning RewriteBase in your .htaccess (as described in the accepted answer of that question) should help.

It might be worth trying to further enhance your .htaccess file, by adding a line after that existing RewriteBase, which looks like so:

RewriteRule . index.php [L]

For more details on the above line, refer to the (accepted) answer in this question on StackOverflow.

Another option for debugging is to retry using another browser. If via that brower you are able to login, then it's probably a cookie problem (in your original browser).

If none of these suggestons help, then re-edit your question by adding more details about which modifications to your '.htaccess file, httpd.conf, etc' you already tried (and didn't work).

PS: Are you aware of the security issue fixed in Drupal version 7.32? Hurry to get your "site on a server" (as in your question) upgraded to the most Drupal core version!


Views PHP Field - Comparing two date fields I'm trying to compare two date fields in a php field inside a view

I already have this working so far so good...

The php field looks like this:

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

$start_value = $node->field_tria['und'][0]['value'];
$end_value = $node->field_data_de_resoluci_['und'][0]['value'];
$timezone = $node->field_tria['und'][0]['timezone'];

$start_date = new DateObject($start_value, $timezone);
$end_date = new DateObject($end_value, $timezone);

$difference = $start_date->difference($end_date, 'days');
return $difference;

This returns me the day difference value, but always in positive.
The desired result should be something like this:

Day difference:

Example 1 (negative value):

2 days ago (or -2)

Example 2 (positive value):

2 days

It also looks like loading every node first doesn't seems to be the most efficient way to do this... but it works.

Thanks a lot

Here is my final code:

$nid = $data->nid;
$node = node_load($nid);
$timezone = $node->field_tria['und'][0]['timezone'];

$start_value = $node->field_tria['und'][0]['value'];
$day = substr($start_value,8,2);
$month = substr($start_value,5,2);
$year = substr($start_value,0,4);
$date = "$year-$month-$day";
$value1 = new DateObject($date, $timezone);

$end_value = $node->field_data_de_resoluci_['und'][0]['value'];
$day2 = substr($end_value,8,2);
$month2 = substr($end_value,5,2);
$year2 = substr($end_value,0,4);
$date2 = "$year2-$month2-$day2";
$value2 = new DateObject($date2, $timezone);

$difference = $value1->difference($value2, 'days', FALSE);
return $difference+1;

You might need to add the $absolute parameter in your call to DateObject::difference(), in order to be able to get the sign:

$difference = $start_date->difference($end_date, 'days', FALSE);

According to the DateObject::difference documentation, the $absolute parameter:

  Indicate whether the absolute value of the difference should be
  returned or if the sign should be retained. Defaults to TRUE.


Empty cart functionality with a link, (no form) in Ubercart I'm trying to make a link (not a form submit) to empty the cart; my link would be /cart/empty.

I can't find where to make a case or something for the URL to work.
I know I have to use uc_cart_empty(uc_cart_get_id()) to empty the cart.

Check Cart Links API page:
http://www.ubercart.org/node/1427

So, you have to enable Cart links module (included in Ubercart) and your link will be:

http://example.com/cart/add/e

Ubercart wil ask for confirmation for this action. If you don't want this confirmation I think you will have to write your own empty cart routine:

Define in your own module hook_menu an entry for your desired path. Then, assign as callback a function of your own. Inside that function, call uc_cart_empty(uc_cart_get_id());

For example:

  function mymodule_menu() {
    $items['your/path'] = array(
      'page callback' => 'mymodule_empty_cart',
    );
    return $items;
  }

  function mymodule_empty_cart() {
    uc_cart_empty(uc_cart_get_id());
    return 'Your cart has been emptied.';
  }

Note that have to provide a message to show the user.

If you want to use the link with AJAX (so no page reload is done) you will need to something like this:

 function mymodule_menu() {
    $items['your/path'] = array(
      'page callback' => 'mymodule_empty_cart',
      'type'          => MENU_CALLBACK
    );
    return $items;
  }

  function mymodule_empty_cart() {
    uc_cart_empty(uc_cart_get_id());
    print 'done';
  }

You will have to add the jQuery code to do the AJAX call. The print statement is sent back to user's browser but it will not be shown (at least if you do not show it to the user in your jQuery code).

For both examples you may adjust the other menu options (access restrictions, for example). Check hook_module documentation:
http://api.drupal.org/api/drupal/modules--system--system.api.php/function/hook_menu/8


variable_get('var') VS $GLOBALS['conf']['var'] Let's say I set a variable in settings.php:
$conf['var'] = foo;

In my module or theme code, I can access this with either:
variable_get('var'); or $GLOBALS['conf']['var'];

Which is the preferred method and why?

It is preferable to use variable_get() instead of $GLOBALS['conf']['var'].

Despite being gone in Drupal 8, you always want to program to the API instead of programming to the implementation.

It is highly unlikely, but there could be some change that pops up in Drupal 7 where there is a difference between the two.  For example, a future version could include a hook_variable_alter() to allow modules to muck with variables between the database and their usage.


Ajax field default value on edit form I want ajax dependent fields in one of my node's form so I am altering the form.

here is the code

    function mymodule_form_alter(&$form, &$form_state, $form_id) {
      $selected_first = isset($form_state['values']['field_first'][LANGUAGE_NONE][0]['nid']) ? $form_state['values']['field_first'][LANGUAGE_NONE][0]['nid']: '0';
    $form['field_first'][LANGUAGE_NONE]['#ajax'] = array(
      'callback' => '_first_callback',
      'wrapper' => 'second-field-wrapper',
    );
    $form['field_first'][LANGUAGE_NONE]['#default_value'] = $selected_first;

    $form['field_second'][LANGUAGE_NONE]['#prefix'] = '
';
    $form['field_second'][LANGUAGE_NONE]['#suffix'] = '
';
    $form['field_second'][LANGUAGE_NONE]['#options'] = _get_second_options($selected_first);
}
/**
 *
*/
function _first_callback($form, $form_state) {
  return $form['field_second'];
}
/**
 * Ajax callback for second field
 */
function _get_second_options($occ_id) {
  //array which contains some int values
  return $second_options;
}

Some more information: field_first is select list of type node reference and field_second is checkboxes.

  Issue: This works fine while creating the node. But when I edit the
  same node, the second field doesn't show and also values selected for
  this field while creating the node are also not checked by default.

You can try to use this module https://www.drupal.org/project/dfv


D7: Add a class to a list item when the created date is less than 14 days old Using Drupal 7 and Views, I currently have a view that produces a list of 5 teasers of the content type "News." 5 teasers is a hard rule. I'd like to conditionally format the rows so that when their "created date" is less than 14 days old so that I may styles them as "New" with CSS styles. So if there are 3 "New" rows, the balance are 2 unmarked rows.
How to do so?
Update
I had the idea of using the "time ago" date format to populate the class name. However, the format for "time ago" changes. Unfortunately, I can't set the granularity to "days" which would have allowed me to add the text as a class, i.e., date1 through date24 for the past 2 weeks.
Update #2
My genesis subtheme is ignoring any preprocessor routines, see more here. However, I can add the routine to my base template.php.
Update #3
Thanks to Елин Й. for the working code:
function genesis_preprocess_views_view_list(&$variables) {
  $view = $variables['view'];
  if ($view->name == 'recent_news_widget') {
    foreach ($view->result as $key => $result) {
      if (time() - strtotime($result->node_created_day) < 14 * 24 * 60 * 60) {
        $variables['classes'][$key][] = 'new';
        $variables['classes_array'][$key] = isset($variables['classes'][$key]) ? implode(' ', $variables['classes'][$key]) : '';
      }
    }
  }
}

In an offline discussion, Елин Й. explains why this works; "I took a look in the views theme.inc and found out that, the classes array is flattened to another variable called 'classes_array' you need to do it as well in order to get your new class also added in this array.

You can do that using a preprocessor function for the view you created. You need to preprocess the view and check the creation date of nodes for each row and give them a relating class.

Given that your view's machine name is recent_news_widget, your diplay format is HTML lists, and your theme name is genesis. You need to use template_preprocess_views_view_list() function in /sites/all/themes/genesis/template.php file

genesis_preprocess_views_view_list(&$variables) {
  $view = $variables['view'];
  if ($view->name == 'recent_news_widget') {
    // dpm($view);
    // Here comes your logic
  }
}

In the above code you see 2 lines commented out. First one is a helpful function for developers to print out the given array/object/string etc in a browsable style. This function comes with Devel module, which I would strongly recommend to install it.

After browsing the variables, you will probably find where the results are listed and where the classes for the rows are assigned. You need to browse the variables until you find all values you need to build your logic to assign new classes, for example the 'created date' of the node. After you have all the variables you need, you can loop through the results, check the creation date and add a relating class.

UPDATE:
The preprocess functions for other display types than HTML List:

Grid: template_preprocess_views_view_grid()
Table: template_preprocess_views_view_table()
Unformatted: template_preprocess_views_view_unformatted()

UPDATE #2 (According the discussion on chat and your updates on the question):
I find the code in your Update #3 was in the right direction, but with a few mistakes. The corrected version should look like that:

function genesis_preprocess_views_view_list(&$variables) {
  $view = $variables['view'];
  if ($view->name == 'recent_news_widget') {
    foreach ($view->result as $key => $result) {
      if (time() - strtotime($result->node_created_day) < 14 * 24 * 60 * 60) {
        $variables['classes'][$key][] = 'new';
        $variables['classes_array'][$key] = isset($variables['classes'][$key]) ? implode(' ', $variables['classes'][$key]) : '';
      }
    }
  }
}

The 2 mistakes in your code were:

You passed the argument as &$variables to the function, but used $vars to assign classes, $vars is not defined in the function so the class was not added.
You wanted to use the key number of the result but in foreach you loop only through the values, and $result variable is an object. In the corrected version of your code above, I used $key => $result by defining the loop so that I can access the key number as well.

UPDATE #3 I added a new line that flattens the classes into classes_array.


Limit user registration by email domain I want to allow people only with an email ending with a specific format and domain such as foo.bar@mail.school.edu to register for the site that I am building. How can I do this in the Admin Tool Bar?

You can use domain_registration to allow or dissalow emails from certain domains to register.

Setup is very simple as seen from the instructions on the project page

  Install the module
  visit 'admin/config/system/domain_register'
  Choose if you want to only allow, or disallow the domains from registering
  Enter the domain names you wish to allow/deny (one per line) in the format of 'foo.com'. Wildcards are allowed.
  Enter the error message you wish to show to the end user if the email address
  doesn't validate


How to use entityQuery to find nodes with a specific multi-value field containing one specific value (and no others)? I have a node type "group" with an entity reference field "field_things" that can reference zero or more "thing" nodes. I'd like to use entityQuery to find all "groups" that have exactly one value for field_things, and that value is a specific "thing".

I can't tell from the docs how to combine those two requirements.

So it appears entityQuery() can't do this, but entityQueryAggregate() can. Below is an example that achieves the goal of the original post:

$thing_id = 101;
$q = \Drupal::entityQueryAggregate('node')
  ->condition('type', 'group')
  ->condition('field_things', $thing_id)
  ->groupBy('nid')
  ->conditionAggregate('field_things', 'COUNT', 1);
$res = $q->execute();

Running dpm($res) will show:

Array
(
  [0] => Array
    (
      [nid] => 85
      [field_things_count] => 1
    )

  [1] => Array
    (
      [nid] => 33
      [field_things_count] => 1
    )

  [2] => Array
    (
      [nid] => 57
      [field_things_count] => 1
    )

  [3] => Array
    (
      [nid] => 54
      [field_things_count] => 1
    )
)


Page caching with multiple versions of the cache My site is very much faster with page caching on. However, I have a custom module that serves 5 different slightly different versions of my content. In other words, people in New York see East Coast stories, but not California stories, but everyone sees national stories. This is mostly done through a custom Views filter that checks for a cookie.

Each node is tagged with an internal taxonomy that determines which areas to show that content in lists generated by views. The actual content isn't hidden or different based on the cookie, just the lists of events, local stories, etc.

Is there a way of serving cache A to people with cookie A, cache B to people with Cookie B, etc?

Code from the custom Views filter-

function query(){

  $this->query->set_distinct(TRUE);
  $invert = $this->options['invert'];
  //Get the taxonomy id corresponding to the user's location from a cookie.
  $office_tid = MCC_location_get_cookie("tid");

  //Get the taxonomy id of the country- code used on 2 sites
  $country_name = variable_get('MCC_location_site')?"U.S.":"Canada";
  $country_tid = taxonomy_get_term_by_name($country_name,'regions');
  $country_tid = current($country_tid)->tid;

  if($office_tid == $country_tid){
    // An area without an office was selected, such as Yukon, filter should act as if no province has been selected
    $case = $this->options['office_not_set'];
  }

  $join = new views_join();

  $join->definition = array(
    'table' => 'taxonomy_index',
    'field' => 'nid',
    'left_table' => 'node',
    'left_field' => 'nid',
  );
  $join->construct();
  $this->query->add_table("taxonomy_index", NULL, $join);
  $this->query->add_table("taxonomy_index", NULL, $join, "taxonomy_index_for_office");

  $this->query->add_where_expression($this->options['group'], "taxonomy_index_for_office.tid = ".$office_tid." AND taxonomy_index_for_office.nid NOT IN (SELECT taxonomy_index_for_office.nid FROM taxonomy_index AS taxonomy_index_for_office WHERE taxonomy_index_for_office.tid = ".$country_tid.")");
}

If you're using Varnish, you can simply add the cookie as a hash key - there's lots of information about how to do this.

One example and one based on mobile devices.

If you mean Drupals internal page cache then maybe look to this module.


Node token in rules (Events: When an order is first paid in full) In comments there is Product reference-Inline entity form-Single value, so when a product is posted in comments, it can be bought by somebody.

Is it possible to have a node token in Conditions or Actions in rules when in Events 'When an order is first paid in full' is used? For example, it would be nice to have a node token in Conditions-'Entity has field' and in Actions-'Set a data value'.

You can have a node token for that action, but you must load one manually using Fetch entity by id.


How to show year/months in archive block? I want to create a archive block for blogs. I tried by using default archive view block, bot that structure is not suitable for my requirement. I need years to display and when I click on years, months should display like below:

           2016
             Jan 2016
             Feb 2016
           2015
             Jan 2015
             Jan 2015
           2014
           2013
           2012

In the same way after a click on year/month, related data should get display.

Use the Views module, then add the creation date of the blog to your views fields; it will be displayed.

Create a new view that shows only nodes whose content type is blog
Select the format you want
In the fields section, add the title and other fields you want to display
Add the date field
Save it; you should get what you wanted


How do I trigger a modal from a template that points to a controller returning an AJAX response I am trying to trigger a modal from a twig. The path of the modal is a controller that returns an AJAX response as below:

Routing code

usgbc_myaccount.get_badges_evidence_controller:
path: '/account/get-badges-evidence/{badge_type}'
defaults:
_controller:
'\Drupal\usgbc_myaccount\Controller\GetBadgesEvidenceController::getEvidence'
_title: ''
 requirements:
_permission: 'access content'
_format: 'html'

Controller code

namespace Drupal\usgbc_myaccount\Controller;

class GetBadgesEvidenceController extends ControllerBase
{
/**
* @return AjaxResponse
*/
public function getEvidence($badge_type)
{

    $options = [
      'width' => '50%',
    ];

    $response = new AjaxResponse();
    $response->addCommand(new OpenModalDialogCommand(t('Modal title'),
 $badge_type , $options));

    return $response;
}
}

Call to router from twig template

{{ 'Read more'|t }}

When I click on the link I get the response in JSON in text area on another page. What is missing? It the approach correct? Any help will be appreciated.

Thanks

You're trying to trigger your modal in multiple ways. Right now your twig is saying to open the href in a modal, but your controller is not return html, it's returning a json/ajax response to open its content in a modal.

To fix this you should do one of the following:

Update your twig to just point to the link, don't do anything there to trigger a modal. Your current ajax response from the controller is handling opening the content in a modal.
Update your controller to return html and leave your twig as-is. In this scenario your twig is handling making the content open in a modal.

I'm not sure about the _format parameter in your route definition, but I think you can just omit it.


How to theme simplenews unsubscribe page? I'am trying to theme Unsubscribe Page for my Newsletter to much the Newsletter Design.
Does anyone know how to theme unsubscribe page in Drupal 6:

example.com/newsletter/confirm/remove/*

I am going to answer this just so that people that are looking for the answer will see it.

As @AgA said:

You can install the Themer Module, you will require the Devel Module.
Enable these modules and go to the path that you would like to theme.

The Themer module will give you suggested naming conventions that you can use to override that page's theme.

In your case it was the content type newsletter, coming to the suggested name of page-newsletter.tpl.php but there will be more suggestions which you can use to override an already overridden more general tpl.


Can region be defined outside of the theme's .info file? Basically I'm trying to reverse-engineer a theme that was developed by another guy. The problem is that I'm not yet quite firm on Drupal ground.

So I'm looking onto a management page for blocks and see a specific region, which is not defined in theme's .info file...

Can regions be defined elsewhere? Or inherited from somewhere else (another theme maybe)?

UPDATE:
Since to inherit something this should be a sub-theme, which should be denoted by:

  base theme = themeName

line in themeName.info file. But there is no such line in this theme... :( This undefined region should be coming from somewhere else...

Drupal 7 has 5 default regions:

regions[sidebar_first] = Left sidebar
regions[sidebar_second] = Right
sidebar
regions[content] = Content
regions[header] = Header
regions[footer] = Footer
regions[highlighted] = Highlighted
regions[help] = Help

Regions aren't inherited by parent themes: https://drupal.org/node/225125.

If I'm not mistaken you used to be able to define regions in theme_region(), but I believe that's no longer being used.


Running drush entity:updates claimed successful but not changing anything I am working on a project with custom entity type. My module works fine in my local environment. But when I deployed to my staging site, things are strange.

For instance, I tried to change my entity definition and then run the drush command:

drush entity:updates -y

The command gave me positive response:

The following updates are pending:

dharmasun_payment entity type :
The Field 1 field needs to be installed.
The Field 2 field needs to be installed.

 // Do you wish to run all pending updates?: yes.

 Finished performing updates

Except the database was not changed at all. So when I re-run the command, it gives me the exact same output.

The staging site might have some different module installed than my development environment. But I cannot make breaking change on the staging platform (or my workmates would be mad).

My questions:

How do I begin to debug this? Is there anyway I can get better log messages with the drush entity:update command?
Or is there any alternative way to update entity definition and make changes to database?

Thanks.

For deploying entity schema updates use an update hook and the entity definition update manager. See the release note of Drupal 8.7.0 and the change record Support for automatic entity updates has been removed.

drush entup is moving from core to contrib: https://www.drupal.org/project/devel_entity_updates

  This project aims to restore this functionality as a developer-only
  tool. This module depends on Devel and is not meant to be enabled in
  production environments or relied upon in deployment workflows.

"Or is there any alternative way to update entity definition and make changes to database?"

Yes, there is. Don't use base fields other than for the very basic things that never change (if core makes changes necessary you'll probably find then examples how to write the update hook). Instead use configurable fields (bundle fields), so that you can deploy easily through configuration.


Form Display: How to move elements out of the advanced container? I want to tweak the node add/edit form for one of my content-types and rearrange the fields in different groups.

I use the Field Group Module to setup the different groups.

On the Manage Form Display settings of the content-type I rearrange the Fields, which works fine for all fields but "Authored by", "Promoted to front page" and so on. All this fields are rendered in an "advanced" container, no matter what.

This is also part of the classy theme file node-edit-form.html.twig

    {{ form|without('advanced', 'actions') }}

    {{ form.advanced }}

Is there any way to break this up, so I can move the containing fields into different groups, just like any other field?

These Fields are organized in different groups in NodeForm::form.

So the settings from Manage Form Display wont work until the #group property of the fields is unset or the surrounding container is unset.

This can be done with one of the form alter hooks in your theme or custom module.

For example the hook_form_BASE_FORM_ID_alter:

function your_theme_form_node_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
    unset($form['author']);
}

This will unset the author container. The containing fields Authored on and Authored by can than be moved around with the Manage Form Display Form.


Issues settings up drush + phpunit I'm trying to set up drush + phpunit, following these two guides:

the official Drush/tests/README.md
Getting Started Testing Drush Commands which is the most recent guide I could find

Here's what I have so far:

macOS Sierra 10.12.2
PHPUnit 5.7.5 at /users/wim.mostrey/.composer/vendor/bin/phpunit
Drush 8.1.9 at /users/wim.mostrey/.composer/vendor/bin/drush
Drush tests at /users/wim.mostrey/.composer/vendor/drush/drush/tests
a simple test migrateManifestTest at /users/wim.mostrey/.composer/vendor/drush/drush/tests/migrateManifestTest.php

I try to run the test using the following command:

UNISH_NO_TIMEOUTS=1 UNISH_DRUPAL_MAJOR_VERSION=8 ./unish.sh --filter=migrateManifestTest

However I get the following error:

PHP Fatal error:  Class 'Unish\UnitUnishTestCase' not found in /Users/wim.mostrey/.composer/vendor/drush/drush/tests/bootstrap.inc on line 51

I tried searching online for this error but got no results at all. I tried running both unish.sh and phpunit from different locations and using different configuration options, to no avail.

Any help would be highly appreciated.

Alright so here's what I did, with help from MegaChriz.

The dev dependencies for Drush need to be installed and the phpunit version that comes with Drush should be used instead of a 'general' phpunit. So not the one I installed through composer.

Git clone of Drush from my home folder (/users/wim.mostrey)

git clone https://github.com/drush-ops/drush.git
cd drush
git checkout 8.1.9

Install Drush with dev dependencies using Composer while being inside the Drush folder

composer install

Execute built-in tests pointing to the phpunit version from Drush:

UNISH_NO_TIMEOUTS=1 /users/wim.mostrey/drush/vendor/bin/phpunit --configuration /users/wim.mostrey/drush/tests --filter=ImageCase

or for Drupal 7 tests:

UNISH_NO_TIMEOUTS=1 UNISH_DRUPAL_MAJOR_VERSION=7 /users/wim.mostrey/drush/vendor/bin/phpunit --configuration /users/wim.mostrey/drush/tests /users/wim.mostrey/Sites/drupal7/sites/all/modules/feeds/tests/drush


Which are the differences between hook_node_view_alter and hook_preprocess_node? I have to remove some elements from a node before show it, but I can't understand where it's better to put the code.
Mainly I can't understand the differences between hook_node_view_alter and hook_preprocess_node. It seems they do the same thing as they receive a render array as parameter.

I think the best option should be to use the hook_node_view but it isn't the right way to do this because in this hook only $node->content is editable.

hook_preprocess_node is more generic, and thus more limited, and happens after hook_node_view_alter.

Both operate on the similar array, basically, but hook_node_view_alter operates at earlier stage. So, first reason is ordering of actions, second is accessing a bit different data sets, as they changes between stages of execution. dpr() or var_dump() their arguments to see exact differences. That's all. Nothing much to it, really.


How do I add "Update Status of User" action to a view? I want to create a user list with the Views module, to change the user status. I use the Views Bulk Operations module, but it has no Change status or Active user action.

How can I enable (or change the status of) users in a view table list with one click?

If you have entity forms and rules, create an entity form with an entity reference to users, add another field for your preferred action, and use rules to perform the action.


VBO Send email to CCK E-mail field I have a content type called "Business", and a user can have multiple "Businesses".

Each business has a "business e-mail" field. This is different from the users email address, and is different for every business.

I want to be able to use VBO to send an email to all selected businesses. I have the view set up ok, and in the recipients field on the send email page I add the token....

[node:field-business-e-mail]

and I also tried...

[node:field_business_e_mail]

But I still get the error :

  Enter a valid email address or use a token e-mail address such as
  [node:author:mail].

Is there a way to get around this?

You can do this by updating code on system.module file. Below are the code :

   function system_send_email_action_validate($form, $form_state) {
       $form_values = $form_state['values'];
       $has_tokens = count(token_scan($form_values['recipient'])) > 0 ? TRUE : FALSE;
       if (!valid_email_address($form_values['recipient']) && !$has_tokens) {
          form_set_error('recipient', t('Enter a valid email address or use a token e-mail address such as %author.', array('%author' => '[node:author:mail]')));
       }
}

For any help, I have refer you to this PATCH.

This is not working directly try to do it manually.


Add Commerce Checkout progress bar and extra stage I believe as such there is no template file for checkout? So how I want to add the following graphical navigation to the top of commerce checkout?

Can i target checkout with a page.tpl.php? Alternatively a hook in template.php?

At each stage/page of checkout the navigation images will change.

You want the Commerce Checkout Progress module.


How to allow users unsubscribe without logging in by changing the value of a custom field? I have a Drupal 7 site with a checkbox (Boolean field) that users check on registration to receive promotional emails.

However, Gmail started blocking some of my emails because they want every email to have a link that users can click to unsubscribe without logging in.

The first idea that came to mind is to link to a webform and then process the unsubscriptions manually, which doesn't sound like any fun.

This can be solved using the form API.

Define a path using hook_menu().
Define an unsubscribe form for the menu path.
Write a validation handler to check the email address.
Write a submit handler for the form.


How to change default value of taxonomy term in View exposed filter drupal 7? I have created view page to find events from Start date - End date and category(taxonomy terms). I have enabled expose filter on fields. How do I show '-select-' instead of '-any-'

or else is there any other method to show no result until user does not add filter value?

To display Results Only when Criteria is selected :

In your view, change Advanced Settings -> Exposed form style to Input required

In Exposed Form style settings you could define the text to be displayed on no results

OR

To Alter Exposed form options:

You need to implement hook_form_alter()
Here is a sample code of it:

function mymodule_form_alter(&$form, &$form_state, $form_id) {
    case 'views_exposed_form_id':
    $name = 'Vocabulary_name';
    $myvoc = taxonomy_vocabulary_machine_name_load($name);
  $tree = taxonomy_get_tree($myvoc->vid);
    foreach ($tree as $term) {
     $tax[$term->tid] = $term->name;
    }
    $form['field_taxonomy']['#options'] = $tax;
}


How to assign a confirmed user role upon email confirmation without logintoboggan? Is there a way to assign an confirmed user role upon account validation/email confirmation?

there is this possibility mentioning logintoboggan:

How do I assign a role to a user after the user's email is confirmed?

My problem is that I am using email registration and genpass (so the user only needs to enter his email) and the modules don't work together.

I'm fairly good with rules and started looking into development. I'm not a programmer though and I don't know how I should implement a corresponding rules condition that checks whether the user has validated his account.

Any suggestions?

If you're only allowing the user to login once they validate their email (which would make sense if you're using email confirmations) then you could just create a rule that assigns the role to the user when the user logs in:

{ "rules_add_user_role_at_login" : {
    "LABEL" : "Add user role at login",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "user_login" : [] },
    "DO" : [
      { "user_add_role" : { "account" : [ "account" ], "roles" : { "value" : { "5" : "5" } } } },
      { "entity_save" : { "data" : [ "account" ], "immediate" : "1" } }
    ]
  }
}

Now, if you're allowing a user to login without having to validate their email (which makes less sense) then you'll need to write a bit of code that hooks into the user reset form and adds the role to the user when that form submits.


Checking site performance on remote vs. locally I had read a blog article recently describing how to set the settings on your local host to be a reasonable comparison to a remote host in order to test Drupal configurations and performance issues before pushing code up to the remote.

What settings should I change?
Is it true that the performance should be about the same if the settings are comparable?

a: Make your settings the same as your production system.

b: Performance measurements are only meaningful if you compare apples to apples. Your test environment needs to match your production environment - same cpus, same ram, same everything. A dev workstation rarely performs the same way as a web server. It's better to have a duplicate of your production system to use for testing / staging. i.e. if you were using amazon, you'd want second ec2 instance that matches your production system.


Getting $_POST empty in AJAX callback I just want to send address information to drupal for check content existence through the AJAX.

Request is sending successfully and callback function also executing.
but I am not getting any data in $_POST array.

here is my AJAX code.

    var address = [{'add1':'address line1','add2':'address line2','add3':'address line3'}]
    $.ajax({
            url: Drupal.settings.property_check.base_url + '/search/property-by-address',
            type: 'POST',
            data: JSON.stringify(address),
            headers:{
              'Content-Type': undefined,
            }
        })
        .done(function(response) {
            console.log(response);
        })

This is callback routing & function

  $items['search/property-by-address'] = array(
     'title' => 'property by address',
     'page callback' => 'search_property_by_address',
     'access arguments' => array('access content'),
     'type' => MENU_CALLBACK,
   );

  return $items;

function search_property_by_address(){
  drupal_json_output($_POST);

}

At where I am making mistake? is there any other way? Or is there any problem with headers?

Try something like this:

$.ajax({
   url: Drupal.settings.property_check.base_url + '/search/property-by-address',
   type: 'POST',
   data: {
       'add1':'address line1',
       'add2':'address line2',
       'add3':'address line3'
   },
   headers:{
       'Content-Type': undefined,
   }
}).done(function(response) {
        console.log(response);
})

or

 var address = {'add1':'address line1','add2':'address line2','add3':'address line3'};

 $.ajax({
     url: Drupal.settings.property_check.base_url + '/search/property-by-address',
     type: 'POST',
     data: address,
     headers:{
         'Content-Type': undefined,
     }
 }).done(function(response) {
     console.log(response);
 })


function theme_field__content_type() isn't working I'm trying to modify all fields output for a specific content-type called Netrunner-Card.

After digging through Stack Exchange I ran across someone that suggested using:

function theme_field__content_type()

But it isn't working. My implementation is:

function blinks_responsive_field__netrunner_card($variables)
{
    $output = 'TEST';
    return $output;
}

Which if I understand correctly, this should remove all field data for a content type of 'Netrunner Card' but it doesn't.

I have multiple fields for each card. There are also card types which I want to output differently, (i.e. An Operation card should look like this, an Identity card should look like this, etc.). So I want to use a switch function (PHP) to check the card types and adjust fields as needed. First I have to get access to the fields and I'm trying to do this inside of ONE function versus a separate function for each field which would add a lot of duplication.

My theme is called blinks_responsive. My content type is netrunner_card.
I am out of ideas.

UPDATE: I don't know if it matters but I discovered that I had a field.tpl.php file in my theme templates folder. Wondering if that caused me issues. Still not working tho.

The problem lies in having other functions that alter OTHER fields of the SAME content type.

Earlier in my development, I created two functions, one each, for two specific fields. Even though my adjustments for those fields were minor (added classes to one and added an img tag to another) it still caused the generic function to fail.

Because I had those other functions...

theme_field__field_name__content_type

It made the generic function for all fields...

theme_field__content_type

...not work.

Once I removed those other functions? Suddenly theme_field__content_type started working instantly.


Changing user register/login pages into secure sub domain I need to change my user registration and login pages into a secure sub domain of my site, how is it possible ?
In detail,

When user logon to http://www.mysite.com/admin that must be redirected to https://admin.mysite.com and he can login from there to our main site .Is it possible ?

Yes it is possible through Services module.

First you need to redirect http://www.mysite.com/admin URL to https://admin.mysite.com/ URL either through Apache redirect or through drupal redirection. Then you will capture all the information of user at this site (https://admin.mysite.com/) and consume the same at http://www.mysite.com/admin site through services module.

You can send user information in JSON or XML format, some other formats are also available there these too are more in use.

Now let's take a example:

Site: https://admin.mysite.com/
1. Created user signup page here with some fields. Here I am taking following fields and send these fields data using JSON to respective URL (http://www.mysite.com/user-register/user/register).

{
    "name": "testuser",
    "pass": "12346",
    "mail": "test@example.com",
    "conf_mail": "test@example.com",
    "field_mobile_number": {
        "und": [
            {
                "value": 12345678
            }
        ]
    },
}

2. Similarly for Sign in page, create form with two fields name and password and prepare following JSON that we would consume to this URL (http://www.mysite.com/user-register/user/login).

{
    "username": "admin",
    "password": "admin123"
}

That's done from this site. Now move on to another site.

Site: http://www.mysite.com/

Enabled Services module.
Create services end point.
For more security you can also use Oauth module.
Please go through following tutorial and follow the same steps and you would be ready to consume above services on this site.

Register User with Services (JSON) with Custom Fields

http://www.wdtutorials.com/2013/04/11/drupal-7-tutorial-web-services-basics


How to create .install custom file How to create and add .install file for druapl8 custom form data storage...my file is custom_form.install but my custom module not load this file

<?php
/**
* Implemetation of hook_schema()
*/
function custom_form_schema() {
$schema=array();
  $schema['custom_form'] = array(
       'description' => 'An example form table',
    'fields' => array(
      'fe_id' => array(
        'description' => 'The primary identifier for a form.',
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),

      'firstName' => array(
        'description' => 'A field storing text',
        'type' => 'text',
        'length' => 50,
        'not null' => TRUE,

      ),
'lastName' => array(
        'description' => 'A field storing text',
        'type' => 'text',
        'length' => 50,
        'not null' => TRUE,

             ),

'emailId' => array(

        'type' => 'varchar',
        'length' => 50,
        'not null' => TRUE,

             ),

'pass' => array(
                'type' => 'varchar',
        'length' => 50,
        'not null' => TRUE,

      ),

'likes' => array(
       'description' => 'A field storing Likes',
        'type' => 'text',
        'length' => 200,
        'not null' => TRUE,

      ),

'gender' => array(
        'description' => 'A field storing Gender',
        'type' => 'text',
        'length' => 50,
        'not null' => TRUE,

      ),

'description' => array(
        'description' => 'A field storing Description',
        'type' => 'text',
        'length' => 255,
        'not null' => TRUE,

      ),

),

     'primary key' => array('fe_id'),
  );
  return $schema;
}
?>

You need to create the schema using the following code

$schema = Database::getConnection()->schema();
$schema->createTable('custom_form', $spec);

For further details visit here


Form ajax add more button added via another ajax callback not working I have a form button which I want to add another field with another button on that form( I am able to do this) but second button is not clickable. Any idea. Following is my code-

This is my form code-

function create_report_form($form, $form_state) {
$form['title'] = array(
    '#type' => 'textfield',
    '#title' => t('Report ttitle'),
    '#value' =>'',
);

$form['actions'] = array(
  '#type' => 'actions',
);

$form['actions']['submit'] = array(
  '#type' => 'submit',
  '#value' => t('Save'),
);
$form['conditions'] = array(
  '#tree' => TRUE,
);
$form['conditions']['report_type'] = array(
  '#title' => t('Report type'),
  '#type' => 'select',
  '#prefix'=> '

',
  '#multiple' => false,
  '#options' => get_report_type()
);

 $form['conditions']['submit'] = array(
   '#type' => 'button',
   '#value' => t('Add condition'),
   //'#name' =>   '_add_another_outcome',
   '#ajax' => array(
      'callback' => 'reports_add_conditions',
      'wrapper' => 'report-form',
      'method' => 'replace',
      'effect' => 'fade',
   ),
  );
   return $form;
}

Now, when I click on this button it will call the following function and generate another form element(select list) with another button which will call another ajax function (this is what which is not working).

function reports_add_conditions($form, &$form_state){
$values = $form_state['values'];
$form_state['rebuild'] = TRUE;
$type = $values['conditions']['report_type'];
$form['attributes'] = array(
  '#tree' => TRUE,
);
$form['attributes']['submit'] = array(
    '#type' => 'button',
    '#value' => t('Add attribute condition'),
    '#ajax' => array(
      'callback' => 'reports_add_attribute_conditions',
      'wrapper' => 'report-form',
      'method' => 'replace',
      'effect' => 'fade',
    ),
);
$form['attributes']['attribute'] = array(
    '#type' => 'select',
    '#title' => '',
    '#options' => get_options($type),
    '#size' => 22,
);
  return drupal_render($form);
}

As you can see from the code I am not able to call "reports_add_attribute_conditions" function for the button.

This is my second call back code-

function reports_add_attribute_conditions($form, &$form_state){
$form_state['rebuild'] = TRUE;
$values = $form_state['values'];
$type = $values['conditions']['report_type'];
$form['attribute'] = array(
    '#type' => 'select',
    '#name' => $type,
    '#title' => '',
    '#options' =>  get_options($type),
    '#size' => 22,
);
$form['attributes']['submit'] = array(
    '#type' => 'button',
    '#value' => t('Add attribute condition'),
    '#ajax' => array(
      'callback' => 'reports_add_attribute_conditions',
      'wrapper' => 'report-form',
      'method' => 'replace',
      'effect' => 'fade',
    ),
);

 return drupal_render($form);
}

Any idea is greatly appreciable

@NabajitRoy my idea is

Never use drupal_render() manual calls (return $form array as-is)
Move all the form generation code into form constructor( create_report_form() ), AJAX
callback should not create new elements for form but only
create_report_form() should
AJAX callbacks should only return element form (not generate them)
e.g. return $form['attributes']['submit'] and may be
$form_state['rebuild'] = true; if needed.
To know in create_report_form() if it was called by AJAX request
button check the $form_state['triggering_element'] in it.
I feel that using '#type' => 'submit' instead of '#type' => 'button'
is better

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


Auto Assign Role weight I am using Auto Assign Role Module to allow users to choose their role during registration. Block to choose role appears as first block, before the default fields (username, email and password).

Is there a way to move AAR block to the bottom, after the default fields?

Yes. You can reorder any Drupal form elements by altering its #weight property. To make the auto assign element appear above the other account registration elements just adjust its weight lighter.

This can be done in hook_form_user_register_form_alter() invocation:

/**
 * Implements hook_form_ID_alter().
 */
function MYMODULE_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  // Set the autoassignrole_user element 1 unit lighter than account form element
  $form['autoassignrole_user']['#weight'] = $form['account']['#weight'] - 1;
}


Authentication error when deploying site's content I have two sites site01 and site02 each having some content (book pages) in them. I want to copy the content of site01 to site02 without overwriting its existing content.
I am using Deploy module to do this, by following this procedure.
Everything is OK until I click "Deploy" on site01. When I do I get the following error:
I see that someone else got a similar error, but I was not able to understand the solution applied by the person. Does anybody have any clue about this?
UPDATE
I tried same scenario using two different machines in LAN, and it worked fine! I was able to do the deployment smoothly.
But, on same server it is failing. I don't know what may be the reason.

My guess would be that on this step:

  For Endpoint URL, enter
  'http://your-destination-site.example.com/services/rest'. Click
  'Finish'. Note that it appears that any path other than
  '/services/rest' on either origin or destination generates a Request
  response error: -1002 missing schema.

Your entering the incorrect url. Make sure you are using clean url's. If not, make sure to include the "?q=" part for the path.


Pathauto not updating path portion of new path When using the following replacement pattern for all nodes (to get 'hackable' urls that respect the menu hierarchy):

[node:menu-link:parents:join-path]/[node:title]

I then create a node with title 'Subnode' which is a child of the node 'Parent node'. This will give me a node with the alias /parent-node/subnode. Now when I move the node one level up and change its (menu)title, so that Subnode is now a 'toplevel' node. The [node:title] part gets changed but the [node:menu-link:parents:join-path] not.

The 'Generate automatic URL alias' checkbox is checked.

Now when choose 'Update URL Alias' from the dropdown list in the content pane (/admin/content) the url does get updated properly.

Why doesn't it get updated right away?

I'm running into the same problem, I tried to trace the code and it looks like that token replacement is never called. Not sure if its a bug in token or pathauto module.


Create a post method in Drupal 8 I've been trying to create a post method in Drupal 8, I used the following code:

custom_rest/src/Plugin/rest/resource/CustomRestResourceUserCheck.php:

<?php

namespace Drupal\custom_rest\Plugin\rest\resource;

use Drupal\Core\Session\AccountProxyInterface;
use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Psr\Log\LoggerInterface;

/**
 * Provides a resource to get view modes by entity and bundle.
 *
 * @RestResource(
 *   id = "custom_rest_resource_user_check",
 *   label = @Translation("Custom User Check"),
 *   uri_paths = {
 *     "canonical" = "/api/v1/custom/user_check"
 *   }
 * )
 */
class CustomRestResourceUserCheck extends ResourceBase {

  /**
   * A current user instance.
   *
   * @var \Drupal\Core\Session\AccountProxyInterface
   */
  protected $currentUser;

  /**
   * Constructs a Drupal\rest\Plugin\ResourceBase object.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param array $serializer_formats
   *   The available serialization formats.
   * @param \Psr\Log\LoggerInterface $logger
   *   A logger instance.
   * @param \Drupal\Core\Session\AccountProxyInterface $current_user
   *   A current user instance.
   */
  public function __construct(
    array $configuration,
    $plugin_id,
    $plugin_definition,
    array $serializer_formats,
    LoggerInterface $logger,
    AccountProxyInterface $current_user) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $serializer_formats, $logger);

    $this->currentUser = $current_user;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->getParameter('serializer.formats'),
      $container->get('logger.factory')->get('custom_rest'),
      $container->get('current_user')
    );
  }

  /**
   * Responds to POST requests.
   *
   * Returns a list of bundles for specified entity.
   *
   * @throws \Symfony\Component\HttpKernel\Exception\HttpException
   *   Throws exception expected.
   */
  public function post() {

    // You must to implement the logic of your REST Resource here.
    // Use current user after pass authentication to validate access.
    if (!$this->currentUser->hasPermission('access content')) {
      throw new AccessDeniedHttpException();
    }

    return new ResourceResponse("Implement REST State POST!");
  }

}

I have activated:

I tested this functionality in Postman but I get the following error:

Someone may know that something is wrong?

Edit 1

Drupal version: 8.1.9

Solution:

We need a different path:

 * @RestResource(
 *   id = "custom_rest_resource_user_check",
 *   label = @Translation("Custom User Check"),
 *   uri_paths = {
 *     "https://www.drupal.org/link-relations/create" = "/api/v1/custom/user_check"
 *   }
 * )

Source:
https://www.drupal.org/node/2799383#comment-11619919


How to create a view with a list of items and item clicked? I want to create a view which shows a list on the left side and the content of the item in the center. When a user clicks on an item in the list on the left side, the item must be shown in the center region or column. It should be done without page refresh.

Think of a view showing articles. The left side list will show a small image, title and trimmed description, whereas, the middle column will show the actual item clicked.

How to do that?

Note: I can use panels as well.

Views does have an Ajax option in the advanced setting, although it may or may not be appropriate or have enough features for what is being described above.

See the previous answers https://stackoverflow.com/questions/3016747/drupal-use-ajax-to-update-views-content and How to load and display a view with Ajax in Drupal 7? and Using AJAX to access the content of a view .

Any solution may or may not require customization.


How to reduce HTML output on Drupal forms How to let Drupal print only necessary HTML in forms. I want to override fields input.

This is the current code for node add form:

<form ...>
...

          Price
          <input class="text-full form-text required" type="text" id="edit-field-price-ad-und-0-value" name="field_price_ad[und][0][value]" value="" size="60" maxlength="55" />

Text

          Video
          <input type="text" id="edit-field-video-ad-und-0-input" name="field_video_ad[und][0][input]" value="" size="60" maxlength="1024" class="form-text" />

Text

...
</form>

I want something like this:

<form ...>
...

          Price
          <input class="text-full form-text required" type="text" id="edit-field-price-ad-und-0-value" name="field_price_ad[und][0][value]" value="" size="60" maxlength="55" />

Text

          Video
          <input type="text" id="edit-field-video-ad-und-0-input" name="field_video_ad[und][0][input]" value="" size="60" maxlength="1024" class="form-text" />

Text

...
</form>

Using theme_form_element I was able to remove third div (form-item). I cannot figure out how to edit first 2 div wraps.

With Display Suite and sub module Display Suite Extras you can remove unnecessary wrappers.


Help debugging "cron run exceeded the time limit" I have written a custom module (for Drupal 7 and PHP 5.3) that utilizes hook_nodeapi() and doesn't allow access to a specific node type and simply redirects (with drupal_goto()) to the main listing page with a warning message.

However I have a suspicion that the Boost module (with "Don't cache pages with messages" enabled) chokes on cron runs when it gets to these content types and keeps getting redirected (I don't know how Boost exactly works but I guess it caches few pages on cron runs?).

The reason for my suspicion, and the real problem is that the cron, after a certain number of runs, starts failing with an error message, "Cron run exceeded the time limit and was aborted.", and immediately after this message on Watchdog there's the following message, "There are Drupal messages on this page, preventing boost from caching."

I put a debugging piece of code on module.inc (hacked core as was suggested here) to see which module was responsible for this failure, and everytime the cron fails, the last module that accessed the Cron seems to be the "Search" (core) module:

  boost  22/02/2012 - 9:00am There are Drupal messages on this ...   Anonymous
      cron    22/02/2012 - 9:00am Cron run exceeded the time limit and was aborted.   Anonymous
      cron    22/02/2012 - 9:00am hit search cron Anonymous
      cron    22/02/2012 - 9:00am hit node cron   Anonymous
      cron    22/02/2012 - 9:00am hit filter cron Anonymous
      cron    22/02/2012 - 9:00am hit dblog cron  Anonymous
      boost   22/02/2012 - 9:00am Expired stale files from static page cache. Anonymous
      cron    22/02/2012 - 9:00am hit boost cron  Anonymous

I have since then reduced the number of pages to index but it didn't help. The cron that runs after the Search cron is the "System" cron but I have no idea what exactly this cron does.

The annoying thing is when you access the cron page through typing in the browser http://address/cron.php or through commandline wget http://address/cron.php it runs Ok. But from the system's cron jobs it eventually runs into this problem after few successful cron runs.

I would appreciate any help in getting to the bottom of this problem or a push in the right direction. Thanks.

/**
 * Implements hook_nodeapi().
 */
function rhask_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  switch ($op) {
    case 'view':
      if($node->type == 'question' && arg(0) == 'node' && !user_access('administer questions')){
        drupal_set_message('Access Denied - You cannot access this content directly. Please use this page.', 'warning');
        drupal_goto('ask');
      }
      break;
  }
}

I guess I could do a redirection without setting any message. That might solve it if indeed Boost is causing problems with the cron, I'll edit this post when I get any result by doing so.

Edit:
The cron has been running successfully every 30 minutes since yesterday and the change I've made to the XMLSitemap module's settings seems to have done the job. I will continue to monitor this website for few more days.

Edit2:
Cron still fails. I've removed the drupal_set_message so now it redirects without setting any messages. However it doesn't prevent the cron from failing. Boost doesn't complain anymore and just logs that "Expired stale files from static page cache". I don't know how to proceed from here to isolate this problem.

I suspect you could check that arg(0) == "node" and is_numeric(arg(1)), which would detect the internal path for a node display and not cron.  You would also need to check arg(2) for "edit" and a few others, that may (or may not) appear as local tasks for your nodes.


Conditionally expose filter I have a view for which I want to expose a filter only to users with certain roles and/or permissions. For users without, I do not want them to be able to use this exposed filter. The documentation for hook_views_pre_render() isn't clear on whether it can be used to modify exposed filters. How would I go about conditionally hiding/removing an exposed filter in code?

I would make a view with your base settings, and then make two displays: one with the exposed filter, and then one without.  Then use your normal access control methods to show the proper display at the proper setting.

For example, if you use views-as-blocks, add visibility rules.  If you use panels, use a new page variant w/ access settings, or add access settings to the content pane.

Otherwise, your best option is to implement the view hooks and experiment.  See what $view looks like with the exposed filter and without.  Add your logic, and make the one look like the other.  Unfortunately, what you can do in view hooks is rather sparsely documented; I always tackle this through trial and error.


How to add css class to block using mytheme_preprocess_block() hook? I need to add some css classes to each list item in a menu block that I created. I thought I could accomplish this by using the following code:

function mytheme_preprocess_block(&$vars) {

  if ($vars['block_html_id'] == 'block-menu-block-7') {
    $i = 1;
    foreach ($vars['elements']['#content'] as $key => &$item) {
      // get each list item and add some css
      if (strpos($key, '#') === FALSE) {
        $item['#attributes']['class'][] = 'col-' . $i++;
        if ($i > 3) {
          $i = 1;
        }
      }
    }
  }
}

However when I try this, I do not see the new class being added when I inspect the element although it does look like it is being added with this code. What am I doing wrong? I am using Drupal 7 by the way.

Thanks.

function MYTHEME_preprocess_block(&$vars) {
  if ($vars['block_html_id'] == 'block-menu-block-7') {
    $vars['classes_array'][] = 'CSS_CLASS_NAME';
  }
}

If you want to add a class to each individual item (li or/and a)use something like this:

function MYTHEME_menu_link(array $variables) {
  // replace MENU-MACHINE-NAME appropriately
  if ($variables['element']['#original_link']['menu_name'] == 'MENU-MACHINE-NAME') {
    // Add menu-li class to each li
    $variables['element']['#attributes']['class'][] = 'menu-li';
    // Add menu-li-a class to each anchor link
    $variables['element']['#localized_options']['attributes']['class'][] = 'menu-li-a';
  }
  return theme_menu_link($variables);
}


How to get the human readable content type name in a node template I have created node template for my node, and its working fine.

I need to print content type name, which is like "Whitepaper" and has machine name "w1" in my node template. If I use variable {{ node.bundle }}, its printing the machine name. But I need the human readable name.

I tried many elements of node, content and page variables but I'm not able to print the human readable content type name.

Can anybody help?

You should be able to get the human-readable name of the content type (or the "label") by using the following snippet in your node Twig template.

{{ node.type.entity.label }}


A ton of errors in panels content editor There's a whole slew of errors at the top of my panels varient content editor page and I have no clue where to start in even fixing them.  Most of these errors have been here since I started working and I have no clue how they got there or how to fix them.  I've had this exact problem on more than one site.

Also, my content got messed up and it won't let me change settings or anything. It stopped letting me change things after I added the Responsive Navigation modules block.

The theme I'm using is aurora and all it's suggested modules:

Magic
HTML5 Tools
jquery update
modernizr
blockify
borealis suite
fences
panels

The site is built on top of the Bear Distro.

Attached is a picture of what I'm looking at.

Known CTools bug - see https://drupal.org/node/1991496 and https://drupal.org/node/1925018

Fixed in http://drupalcode.org/project/ctools.git/commitdiff/280ccd0 and the fix is available without patching if you use 7.x-1.x-dev.


Create template pages Using Drupal 7 and Clean theme. And my main module is Views. And i want, create template tpl.php file for every page.

I know node id method but don't know how create tpl file for views pages.

Please help, thank you.

In the views ui, click on 'advanced' and go to 'theme information'. This gives you a number of suggestions for the template file and what code should be in it.


Drupal 7 Site for Displaying PPT or JPG I am relatively new to Drupal and am about to develop a tribute site.  It will have a few informational pages but it's main focus is photographs.

There are about 150 photographs which have been sorted into about 10 categories.  I have these in raw form, and also in a powerpoint deck.  My preference would be to display the photos individually, but I'll use the powerpoint if it proves too difficult.

Ideally users would be able to navigate to a category of photos, then flick through them one at a time, or 'play' a slideshow.  Also, if it was not too difficult, I'd like to annotate some or all of the photos.

Where should I start with this?  I have installed Drupal 7 but see there is a wide range of modules and approaches for displaying photos.  I have experience with CSS, jQuery and PHP...

Any pointers much appreciated!

There are many, many ways to do this in Drupal but I'll outline two basic approaches for D7.

First, you'll definitely have a much easier time working with .jpg than .ppt.  As Drupal is open source, it supports open file formats (jpg) much better than proprietary ones (ppt).

Warning: this is not a complete tutorial; writing one would have far too many steps and is out of scope for this site.

APPROACH 1

Views Slideshow:  This relies on the Views module.  If you're new to Drupal, you should definitely learn how to use Views first; Node One has an excellent tutorial on Views.  Using Views slideshow, you would roughly do the following:

Create a content type for your images.
Create a vocabulary Categories using the Taxonomy module and add each individual category as a term.
Create a node of content type image for each picture.
Configure Views Slideshow to show each gallery on its own page.

Why use this approach?  Each picture will be its own node.  This allows you to later add different fields to each picture such as a rating (with Fivestar) or the name of the photographer, etc.

APPROACH 2

Field Slideshow: This approach allows you to store all of the pictures for each gallery on a single node.  To do this:

Create a content type for galleries and add a field to hold the pictures.  Make sure it allows for multiple values.
Create a node of content type gallery for each category.
Configure Field Slideshow.

Why use this approach?  It is somewhat simpler to set up and requires less tinkering with Views.  However, it is less flexible.


Can't see the block body I'm working on a drupal site. Its already done by someone else but I have to change some things. I want to edit a block but when I want to edit, it doesn't show the block body. http://i.imgur.com/ntIM5QI.png

That is because it is a block provided by a view.
Look at the block edit page url, it usually gives you a hint wich module provides the block: "admin/structure/block/manage/views/what_we_offer-block"...


How can I set up a "blog" area? I am very new to Drupal and Twig.

I've a custom Drupal theme I've built, but my client now wants a "blog" system as well. This includes the following features:

Show most recent article in a blurb on the home page
List out articles with pagination on an archive page
Assign categories and/or tags to articles which when visited list out articles similar to the main archive page
Show "posted on" date on article page

I've got the last item working just fine, but I can't find anything useful Googling around for the first three items.

I'm using Drupal 8 and twig templates if that makes a difference.

Everything you listed is super common, almost basic in Drupal projects. So you can find plenty of tutorials and introductory articles about how to do those features.

You can create the latest article blurb Block using Views module (it's in D8 core), then place the Block in a theme region and adjust its visibility to only show on the front page
You can create "Archive" page using Views (pagination is also a feature in Views)
Tag articles with the Taxonomy module (create a Vocabulary with terms inside, then add a Taxonomy reference field on Article Content type). There is a out-of-box View "Taxonomy term" that automatically creates pages for each term and lists the articles tagged with that term
Submitted by and on can also be controled through the interface by editing the Content type settings (you only need twig if you need to override the HTML output)

So get yourself some Drupal Views and Taxonomy tutorials ;)


I can't translate description of front page in my multilingual site I have a multilingual drupal 7 site.

I want to translate my description metatag of my English frontpage version of my site. Any other page show ok in site Greek and English.

The problem is it only show the Greek version.

I have i18n and metatag module.

What i have try is to navigate to en/admin/config/search/metatags/context
and add my English url (www.mysite.gr/en) so i can add manually the description there. But it didn't worked.

All major translation issues for metatag module are now fixed (see: https://drupal.org/node/1282620, https://drupal.org/node/1688286)

All you have to do is:

Go to metatag settings page: /admin/config/search/metatags
Override your frontpage (/admin/config/search/metatags/config/global:frontpage) and write
your infos in default language
Save your modifications
Go to your homepage
Flush site cache
Switch site language for every other language (this way all strings can be generated for translations)
Go to /admin/config/regional/translate/translate and search (in default
language) all strings you have to translate and translate them

This should be enough.

If you are using metatag submodules like Context be aware that translations issues are not still full fixed (see: https://drupal.org/node/1986032)

Hope this help


Embed form inside a block I am using a module (donate) that produces a form at a specific URL, for example, http://example.com/donate. I would like to put this form inside a block and display it on another page. Do you guys know the best way to do this? Thanks for reading.

If you switch to 'donation' module and 'simple_paypal'
You can create a block with the content:

<?php
require_once(drupal_get_path('module', 'donation') .'/donation.module');
print donation_form();
?>

Make sure to set input format to PHP code


How to clear cache bins via the admin interface Drush will allow you to selectively clear caches. CSS/JS or views for example.

Is there a way to do this via the admin interface, or a contrib module to do it? I don't have access to drush on a server and the cache rebuild is not reliable so it would be nice to just clear the cache bin that I need to.

In D6 install the admin menu. By clicking on the favicon on the left hand side of the menu you can clear all/seleted caches.


How to load a webform via ajax inside custom JS? I'm trying to load a webform block via ajax.

Right now I have:

$.ajax({
    url: '/form/contact-us',
    success: function (response) {
        console.log(response);
    },
    error: function (error) {
        console.log(error);
    }
});

How do i get the form as a block and not by the full page/node?

Try the following steps :

Create follow this how to create contact form block
Create route for example form/contact-us-block :

custom_module.routing.yml

custom_module.get_contact_form_block:
  path: '/form/contact-us-block'
  defaults:
    _controller: '\Drupal\custom_module\Controller\TutorialController::getContactFormBlock'

getContactFormBlock Action in your controller

public function getContactFormBlock() {
    //- Set your block id here
    $bid = 4;
    $block = \Drupal\block_content\Entity\BlockContent::load($bid);
    $build = \Drupal::entityTypeManager()
      ->getViewBuilder('block_content')
      ->view($block);
    return render($build)->__toString();
  }

Get the block html in your Js.

    (function ($, Drupal) {
      $(document).ready(function ($) {
        $.ajax({
          url: 'form/contact-us-block',
          success: function (response) {
            console.log(response);
          },
          error: function (error) {
            console.log(error);
          }
        });
      });
    })(jQuery, Drupal);


How to convert a block with views content into code? I'm running into limitations of views. For example, I would like to add additional logic and formatting to a view shown in a block.
Is there a good way of taking the existing SQL and formatting from the view to create a custom module?

For example:
I want to show a table with taxonomy terms, including their hierarchy. Parent terms will have links to one one, children terms will have links to a different view.
For children terms I want to show the number of nodes with that term, the number of comments, etc.
This can currently not be done using views or would be rather complex to setup.

Rather than starting from scratch writing a module is there a good way to use a similar view and reuse the query and the formatting?

You could also use something like this:

$view = views_get_view('view_name');
$view->set_display('block_display_name');
$view->set_arguments(array($arg1, $arg2)); //only if you need arguments
$view->execute();
foreach($view->result as $res) {
  // extra stuff here
}


Profile 2, update separate database on submit? I want to know where and how to plug/hook into profile 2, so that when the user updates a specific profile ("new_profile"), that this then fires off a chunk of custom php code. The event must only be fired off IF validation passes. Which leads me to believe that I can't really just add another submit handler.

How would I be able to fire off this "second update" to a seperate database, if I only want to hook into the part after validation has passed?

Every module which exposes hooks are documented in module *.api.php file. In your case it's just hook_profile2_update .

/**
* Respond to a profile being updated.
*
* This hook is invoked after the profile has been updated in the database.
*
* @param $profile
*   The $profile that is being updated.
*
* @see hook_entity_update()
*/
function hook_profile2_update($profile) {
  db_update('mytable')
    ->fields(array('extra' => $profile->extra))
    ->condition('pid', $profile->pid)
    ->execute();
}

Refer http://cgit.drupalcode.org/profile2/tree/profile2.api.php for more details.


Debugging the result property in a ViewExecutable I need to debug the $result property of the ViewExecutable object passed to hook_views_post_execute but for what ever reason, Drupal can't handle it. $view->result is an array of type ResultRow, and because it's an array, I'm attempting to log it like so:
\Drupal::logger('foo')->notice('<pre>' . print_r($view->result, TRUE) . '</pre>');

When I do this and then load the view I'm attempting to mess with, it loads the page without css and then the recent log messages just shows up blank, no errors or anything that would actually be helpful.
I've tried a number of different ways but this is always the result. Why can't this logger print a simple array?
I've even tried looping through the array and printing just the value:
foreach($view->result as $key => $value) {
  \Drupal::logger('bar')->notice(print_r($value, true));
}

And that will render the view without css and then the logger doesn't print anything at all. I double checked and printed a regular string and that worked, but when I attempt to print the value it just breaks and doesn't do anything.

Your code works fine for me so perhaps your view has no results?
Anyways, the Drupal log is not really meant to be used for printing variables for debugging purposes. Use an appropriate tool like Devel which has/comes with another module called Kint, enable Kint.
use Drupal\views\ViewExecutable;

/**
 * Implements hook_views_post_execute()
 */
function mymodule_views_post_execute(ViewExecutable $view) {
  kint($view->result);
}

Flush cache and you'll see this

For more info on how to use Kint, see Welcome to Kint 101


Disable/remove javascript does anyone know how to disable a javascript loaded by drupal?

<script src="/profiles/ncr/themes/contrib/bootstrap/js/bootstrap.js?ny8c02"></script>

I tried the following in the template.php file but no luck.

function bootstrap_ncr_js_alter(&$javascript) {
    $path = drupal_get_path('module', 'js_theme');
    unset($js[$path . '/bootstrap.js']);
}

So it seems like the JavaScript file you are trying to remove is actually coming from a theme. You were also trying to unset array item in non existing variable $js. You could try if this works for you:

function bootstrap_ncr_js_alter(&$javascript) {
  $path = drupal_get_path('theme', 'bootstrap');
  unset($javascript[$path . '/js/bootstrap.js']);
}


Ajax Call on image button I want to use ajax call on image button

here is my code.

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

    if($form_id=='user_profile_form') {

       $form['linkb'] = array(
            '#type' => 'image_button',
            '#href' => '',
            '#title' => t('something'),

            '#name' => 'linkb',
            '#ajax' => array(
                'method' => 'html', // this is important without this if else condition for ajax will not work.
                'effect' => 'fade',
                'callback' => 'clicktell_verification',
                'wrapper' => 'replace_textfield_div',),
        );
        $form['cardnresp'] = array(
            '#type' => 'hidden',
            //'#default_value' => '',
            '#title' => t('This is where msg comes'),
            '#prefix' => '
',
            '#suffix' => '
',
        );
        $form['#validate'][]='clicktell_error';

    }
    return $form;
}

and

function clicktell_error($form, &$form_state) {
  //my code
}

function clicktell_verification($form, &$form_state) {
 //my code
}

But now when i click on image button it jst refresh the page and no ajax call happnes

Does anybody have idea regarding this

Thanks

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

    if($form_id=='user_profile_form') {

       $form['linkb'] = array(
            '#type' => 'image_button',
            '#href' => '',
            '#title' => t('something'),

            '#name' => 'linkb',
            '#ajax' => array(
                'method' => 'html', // this is important without this if else condition for ajax will not work.
                'effect' => 'fade',
                 'prevent' => 'mousedown',
                'callback' => 'clicktell_verification',
                'wrapper' => 'replace_textfield_div',),
        );
        $form['cardnresp'] = array(
            '#type' => 'hidden',
            //'#default_value' => '',
            '#title' => t('This is where msg comes'),
            '#prefix' => '
',
            '#suffix' => '
',
        );
        $form['#validate'][]='clicktell_error';

    }
    return $form;
}

This will run ajax but you may feel form is submitting but there is no actual submitting of form


View exposed filter with month and remove year I have an issue that needs the help of everyone. I created the page in view to filter the node. I created a filter Date created in "view exposed filter" for filter by  Date created.

I configured for the Filter granularity is check month,  that filter will display 2 dropbox to me to choose, i.e. month and year dropbox. But I want to display only months option and defaults year is the current year. Do not know if anyone can help me handle the matter.

Thank you very much

Using CSS and jQuery you can achieve your requirement.

Step 1: Using jQuery, on change() event of month select list assign current year to year select list.

$(".date-month").change(function(){
    //write code to set current year to year select list.
});

Step 2: Now using CSS, hide year select list.

.date-year {
    display: none;
}

  Note: You can also achieve the same functionality using Drupal custom hooks.