Listing top level terms in views including those without children My vocabulary looks like this

Level 1a

Child a
Child b
Child c

Level 1b

Child a
Child b
Child c

Level 1c

Level 1d

Child a
Child b
Child c

Level 1e

I have managed to display parents and children terms using Taxonomy term: Parent term and filter on (Parent) Taxonomy term: Parent term (not empty). But terms without children on the same level with "parent" are not displayed.

To get the children I used filter “(Parent) Taxonomy term: Parent term (not empty)”. If I set the same filter to “is empty”, I get all level 1 terms including those terms without children just like I want it. So right now it seems like an either-or situation. I can only get the top terms or the children terms but not both.

How do I get the top level terms including those without children and corresponding child terms for those with children?

If you add a filter to parent term = "empty (NULL)" it will display all terms that have no parent above them.

For more detailed steps, try this blog post I wrote: http://fdiv.net/2012/08/11/taxonomy-views-browser-arbitrary-depth

Taxonomy Menu Module can help you with this.


Drupal Forms API how to get degree sign onto submit button I'd like to have a submit button with "°C" value on it. But when I just copy paste the degree sign, I get an empty value. When I try HTML code for degree sign (&deg;) it is escaped so I get &deg;C.

This is my submit button element in my hook_form function:

$form['wrapper']['F'] = array(
    '#type' => 'submit',
    '#name' => 'F',
    '#value' => '°F',
    //'#value' => '&#176; F',
    //'#value' => '&#x00B0; F',
    '#attributes' => array('id' => 'fahrenheit-button'),
    '#weight' => 20,
  );

Any ideas? Thanks, Tomas

Buttons in Drupal by default are being generated by the theme_button() theme function which uses drupal_attributes() to handle all of the button's attributes which always escapes an attribute's value using check_plain().

Visit api.drupal.org/api/drupal/includes%21form.inc/function/theme_button/7 for the theme_button() function and click under the Code section on a function name to see what it does.

I think there are two possibilities:

You write your own implementation of theme_button(): copy the original function, paste it into your template.php file and rename it to something like YOUR_THEME_button();
Or just use the bare unicode character as you did in your question. I read at stackoverflow.com/q/3627720/328272 that this does not work on Windows XP, but I successfully tested it on IE7 and IE8 on XP using browserstack.com.

<input type="submit" value="&#x00B0;C" />

This website is useful for converting characters: http://rishida.net/tools/conversion/


Can I rewrite a view's query SQL directly? Can I modify the SQL generated by the Views Query Builder? Views doesn't support subquery out of the box, so I'm just wondering if I can add the final line to my query manually?

Background info:
The query I'm trying to perform looks a little like this:

select full_name, email, users.uid
from
cloudsponge
inner join
`users` on users.uid = cloudsponge.importer_uid
where cloudsponge.email not in (select mail from users)

It's worth pointing out that all tables have millions of rows so performance is also important (I haven't checked this query on a large dataset yet).

try hook_query_alter. Views queries should pass though this hook allowing you to alter them. https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_query_alter/7

OK, I solved this by hacking it. This is NOT the cleanest solution, but I see it as being the cleanest way out. I ended up creating a the query I want with MySQL's CREATE VIEW syntax. I then loaded the MySQL VIEW into Views as a table; this did the trick. It's not pretty, but it's the best solution I could come up with for my purposes.


How to prevent all UPPERCASE body text? Some users enter body copy and comments with the caps lock on. All uppercase is considered shouting and I would like to convert it to lowercase or "natural" with uppercase characters at the beginning of a sentence.

Any easy solutions?

Converting the post to all lower case would be pretty simple; you can implement your own filter like so:

function MYMODULE_filter_info() {
  $filter['allcaps_filter'] = array(
    'title' => t('Disallow ALL CAPS posts'),
    'description' => t('Rudimentary filter which converts all text to lowercase'),
    'process callback' => 'MYMODULE_allcaps_filter_process'
  );

  return $filter;
}

function MYMODULE_allcaps_filter_process($text) {
  // Attempt to make the first letter of the first word uppercase. This is very
  // likely to fail as the inputted string will probably be HTML.
  return ucfirst(strtolower($text));
}

Once you clear the caches you'll be able to add that filter to any text format you want.

It's worth noting that the description rudimentary in the comments is very, very apt...for example this will also convert any HTML attributes/tags to lowercase which might break embedded image paths etc. It might provide a good place to start though.

Constructing more naturally cased alternatives is going to be very tricky, mainly because you haven't just got text in there...you've got HTML as well. I can't think of a decent way to do this at the moment to be honest, short of importing the string into a DOMDocument and looping through every element, converting the text in chunks as you go.

I'd provide an example for that but I think you've got one ;)

text-transform:uppercase;

use this in css


Drupal load form with ajax callback in Bootstrap modal I need to load a form into a 'bootstrap modal dialog' which will submit data via ajax callback to callback function.

The form display properly when the modal dialog is launched:

The menu 'document/share call the function 'modal_share()' that display the modal content

...
content
...

Within this function modal_share(), a form is called for render:

function modal_share($fid) {

$f = drupal_get_form('modal_share_form',$fid);
....
....
echo
 .... ".drupal_render($f) .".....

}

So far so good and the modal is correctly output with the form 'modal_share_form' as per below structure:

function modal_share_form($form,&$form_state,$fid) {
form['share_list'] = array(
  '#type' => 'select',
  '#multiple' => TRUE,
  '#options' => $option ,
  '#title' => t(""),
  '#description' => "",
  '#required' => false,
  '#default_value' => $default

);

$form['share'] = array (
        '#type' => 'button',
        '#value' => " ".t('record')."",
        '#ajax' => array(
          'callback' => "modal_share_form_submit",
          'wrapper' => 'shareMessage',
          'effect' => 'fade',
          'method'=>'html'
        ),

        '#id' => 'modalsharebutton',
);
return $form;
}

Now the problem is the the #ajax function in the button is not rendered by drupal as it should.

the html rendering is:

<button id="modalsharebutton" class="btn btn-primary form-submit" type="button" value="record" name="op">

without the "ajax-processed" class attached

The thing is that if I load the form on a main page ajax function is rendered properly.

So my conclusion is that when building the form for modal, it is not going through the proper ajax build process...

But I can't see the solution.

Thanks for help.

I solved this issue differently by adding '#attribute' with event...

$form['share'] = array(
        '#type' => 'button',
        '#value' => " " . t('Record') . "",
        '#ajax' => array(
          'callback' => "modal_share_form_submit",
          'wrapper' => 'shareMessage',
          'effect' => 'fade',
          'method' => 'html'
        ),

        '#id' => 'modalsharebutton',
        '#attributes' => array('onclick' => "share_submit($fid);"),

);

Thank you.

For me seems like parsed html is quite broken.

Button markup should be something similar to

record

Drupal input type button will not work as expected. You could try markup. Maybe it will work out.
I would use input type submit and then style it as needed.


Setting php E_NOTICE within my .module file I want to set E_NOTICE only within the .module files which I create. How can I do it?

I want to catch mis-spelled variable names which are difficult to catch.

I've never tried this, but if you don't mind modifying core on your dev server you can change drupal_error_handler(): examine the results of debug_backtrace(), decide if the error came via your module and act appropriately.

You can not set E_NOTICE only to your module files.
In PHP when you activate the notices, it will be activated for all running scripts.

To display errors, warning and notices:

ini_set('display_errors', 'On');
error_reporting(E_ALL | E_STRICT);


How to handle enabling new modules with Drush via makefile At work we are moving to getting our new sites set up in git and doing local development. So far I've created a drush make file along with an installation profile, and I have this scripted via puppet so that when a user does a fresh clone of a repository it will download all of the packages and run a basic site install. This works OK.

Now, my question is for when I need to use a new module for a site. For example, we build a new module for the site. I want the other developers to pull from git and have the new module automatically installed. Adding it to the drush make file will only cause it to be downloaded, and running 'drush si' will cause the site to be reinstalled, wiping out all of the data.

What's the best way to accomplish this?

Edit

I feel I haven't explain this properly. I'm looking for a way to automatically enable modules based on the makefile entries in drush. The idea is the user checks out a project, and then I'll have puppet run 'drush make' and 'drush si' if no settings.php file exists. What I need to figure out is for when the next time the user does a pull and we've added a new module, how to have that automatically enabled through some script. If I need to I'll write something to parse the makefile and run 'drush en' manually, but I'd like to find something that is pre-built to do this.

I worked for a company that had a large dev/stage/prod flow that tried to automate as much as possible.  Everything had to be done in code, scripted either using features or update hooks.

Basically, what you wanting is to have 1 custom module that exists to contain update hooks.  This way, when a developer pulls an update to the code base, they run the db update, and that can perform whatever module enable/disables need to happen.  The update hooks do not affect a new installation, because it is assumed that the module is already up to date when it is installed, and will only execute newer updates.

To summarize:

Continue using your installation profile to perform the necessary installation tasks (enabling modules, etc.).
Use a custom "update" module which uses hook_update_NXXX() to enable/disable new modules and otherwise keep your site's administrative tasks in sync.

Here is a post that talks about a similar approach and gives code examples.

How about using a Drush Make file in conjunction with a Drupal Installation Profile?
see: https://drupal.org/node/1022020


Link to create new node with taxonomy term from url already selected? I need to make a link to create a new node. I need this link to appear on taxonomy term pages so I was going to put it in a block. Nodes can be tagged with taxonomy terms.

How can I make it so the create node form has the term (from the page the link was on) already selected? So if you were on mysite.com/term/1 and and clicked the create node link, the node would have term 1 already selected.

Ive found this module but its in dev for D7 so there another way?
http://drupal.org/project/prepopulate

Thanks

Yes, you need to download and enable the Prepopulate module.

The syntax you use to prepopulate taxonomy terms with D7 is (AFAIK) not documented anywhere and the syntax it is also radically different from the syntax used in D6 that is demoed in a number of screencasts of the Preopulate module.  In D7 taxonomy terms are fields.  If you read the source code, you'll find that you prepopulate taxonomy terms as would prepopulate other field.

I.e. if your taxonomy term field is field_tags and you want to prepopulate with the term "myterm", you use the following syntax (with clean URLs):
/node/add/article?edit[field_tags][und]=myterm.

I think the Prepopulate module is in fact safe. It has a large number of sites using it and was mentioned in a mustardseed media screencast.
http://drupal.org/project/prepopulate


add flag to product display view I have a product display using facets that I have tried in vain in views to add a flag/unflag link to with views I already built a separate comparison view with the relationship to flag and the ability to unflag but I want to be able to flag products from the facets display (if it's even possible) rather than a second display that looks the same as the facets display except that it uses content linked to the product entity and wont show the facets

Does anyone know if it's even possible to add a flag to a view of type "Product Display"?(Correction: "Product Display" was the name of my search api index being exposed to views)

For now I have this working by exposing the flag link on the product displays themselves which is a pain in the neck to flip back and forth and some users probably aren't going to be able to be techie enough to figure it out

I am having the same problem. It seems like there is no way to add 'flag' relationship in view used by facets..
The way I have done this is:

I installed the module 'Views PHP'
(https://drupal.org/project/views_php)
Added a 'global PHP'
field in my faceted view.
called the function to create flag
link and printed the link in the global php field: print flag_create_link('bookmarks', $data->entity)

Dont know why, my php view cudn't render $row->nid, thus I used $data->entity for node id.

Remember to enable php filter once views php is installed.

Hope It helps.


How do I create a link? Say I am extending The blockBase class to create a custom block, and I am implementing the blockBuild method to create some markup for my block. Something like this:

 class YourModuleBlock extends BlockBase {

   /**
     * Implements \Drupal\block\BlockBase::blockBuild().
     */
     public function build() {
      return array(
        '#markup' => 'This is a block!',
      );
     }
   }

If I wanted to provide a link in this markup, in D7 I would have used the l function, but this is no longer available (see here). So, I need to make available the new D8 method for generating links. I could just use an <a> tag, but this was never best practice in D7.

So, what is the right method to use for creating links and how do I make it available to my function?

\Drupal::l is deprecated.
Maybe this case will be useful for somebody

  use Drupal\Core\Url;
  use Drupal\Core\Link;
  $url = Url::fromRoute('entity.node.edit_form', array('node' => NID));
  $project_link = Link::fromTextAndUrl(t('Open Project'), $url);
  $project_link = $project_link->toRenderable();
  // If you need some attributes.
  $project_link['#attributes'] = array('class' => array('button', 'button-action', 'button--primary', 'button--small'));
  print render($project_link);


Remove 'Switch to plain text editor' in CKEdtior Where do I disable the switch to plain text editor link from the CKEditor. I checked the settings and I don't find anything that support this.

I tried to disable it with display:none; through CSS but it wont respond to it. Here is the code

Switch to plain text editor

I both tried with the id tag and the class to disable it but it dosen't work.

.ckeditor_links a {
display: none;
}

does not work :(

Any suggestions?

You do not need to use CSS. There is an option within the CKEditor profile.

Go to Configuration > Content Authoring > CKEditor then select edit next to the profile you want to effect. This way you can also limit this too certain users.

Then select editor appearance and scroll down to "Show the disable/enable rich text editor toggle" then select hide and save the profile.

You can do it programmatically.

Include this code into the hook_form_alter function of your module:

drupal_add_js(
  'jQuery().ready(
    function() {
      jQuery(".ckeditor_links").hide();
    }
  );',
  'inline'
);

Greetings


Drupal8 Oaut2 add a grant type “password” to client I work on Drupal8 project and created Rest API, everything works fine until I want to add Oauth2 when I try to get a token I got an invalid grant type error.

This is the error code:

{
    "error": "invalid_grant",
    "message": "The provided authorization grant (e.g., authorization code, resource owner credentials) or refresh token is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client.",
    "hint": "Check the configuration to see if the grant is enabled."
}

This is the url that i called:

http://myserver/oauth/token?grant_type=password&client_id=6db9da8d-b831-4381-b279-381bc5a57e90&scope&username=webmasterrest&password=webmasterrest&client_secret=$S$EamACyfemGWic74kmkwUvphMmr9FL132KC297mI1GEkTKhyBJyAo

I added a client, but I can't add a grant type "password" to this client, any help please?

To add Oauth 2 authentification
Install the module using Composer: composer config repositories.drupal composer https://packages.drupal.org/8 && composer require drupal/simple_oauth:^2. You can use any other installation method, as long as you install the OAuth2 Server composer package.
Generate a pair of keys to encrypt the tokens. And store them outside of your document root for security reasons.
openssl genrsa -out private.key 2048
openssl rsa -in private.key -pubout > public.key

Save the path to your keys in: /admin/config/people/simple_oauth.
Go to REST UI and enable the oauth2 authentication in your resource.
Create a Client Application by going to: /admin/config/services/consumer/add.
Create a token with your credentials by making a POST request to /oauth/token. See the documentation about what fields your request should contain
(Not shown) Permissions are set to only allow to view nodes via REST with the authenticated user.
Request a node via REST without authentication and watch it fail.
Request a node via REST with the header Authorization: Bearer {YOUR_TOKEN} and watch it succeed.
From this

NOTE: I user drupal/simple_oauth version 2.x because i got an exception n version 3.x


How do I replace a string when altering the output of a view field? I have some text I'd like to alter in the custom output of a view field.  For example, if the output contains pancakes, I'd like to replace it with waffles.
The following code doesn't work.
{{ field_recipe_prep__value | replace({'pancakes': "waffles"}) }}

How do I replace a string when altering the output of a view field?

Remove the __value part.
{{ field_recipe_prep | replace({'pancakes': "waffles"}) }}


Should modules be in source code management? I am new to Drupal and I am using Drupal 7.61.

Should the Drupal modules folder be git ignored or included in the source code management for best practices and continuous integration sake?

As Jaypan and leymannx say in the comments above, if you use Composer to manage dependencies, you can just include composer.json and composer.lock in your version control repository. Then you can use Composer to rebuild your project when you deploy. This has the advantage of keeping all third party code out of your repo.

https://www.drupal.org/docs/develop/using-composer/using-composer-to-manage-drupal-site-dependencies

The documentation linked above shows how to use Composer to install Drupal core, contrib modules, and even patches and libraries.

This approach is the emerging standard. But it has its pros and cons. Here are some Drupal and Composer "gotchas" to look out for:

https://www.jeffgeerling.com/blog/2017/composer-and-drupal-are-still-strange-bedfellows

If you don't use Composer, it's probably a good idea to keep core, contrib, patches and libraries in version control.

For Drupal, it is best practice to add settings.php, public, and private files to the .gitignore file like as following:

# Ignore configuration files that may contain sensitive information.
sites/*/settings*.php

# Ignore paths that contain user-generated content.
sites/*/files
sites/*/private

You can learn more about source code management by using git from here:
https://www.drupal.org/node/803746


How to load a menu item and its children menu items? I have the menu item id. I want to display that menu item with its children.

Suppose for example I have menu item test and it has two children menu items. So I want to load them and display it as

test
  test1
  test2

I tried to load the menu item with the following code.

$menu_content = current(\Drupal::entityManager()->getStorage('menu_link_content')->loadByProperties(array('id' => 1)));

But I am unable to get the children from the variable. Can someone help me here?

Try these:

// Select the parent menu link with 49 id.
$menu_link_content_id = 49;
// Use the 'menu_link_content' entity storage.
$menu_content_storage = \Drupal::entityTypeManager()->getStorage('menu_link_content');
/** @var \Drupal\menu_link_content\MenuLinkContentInterface $menu_link_content */
// Fetch an entity with parent menu link.
$menu_link_content = current($menu_content_storage->loadByProperties(['id' => $menu_link_content_id]));
// Build a specific value for a parent property.
$parent_prop = "menu_link_content:{$menu_link_content->uuid()}";
// Load child menu items by 'parent' property.
$menu_link_content_childs = $menu_content_storage->loadByProperties(['parent' => $parent_prop]);

Try this:

 $menu_tree = \Drupal::menuTree();
            $parameters = $menu_tree->getCurrentRouteMenuTreeParameters($menu_name);
            $tree = $menu_tree->load($menu_name, $parameters);
            $manipulators = array(
            array('callable' => 'menu.default_tree_manipulators:checkAccess'),
            array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'),
            );
            $tree = $menu_tree->transform($tree, $manipulators);
            $list = [];
            $i =0;
         foreach ($tree as $item) {
             $title = $item->link->getTitle();
             $url = $item->link->getUrlObject();
             $menu_url = $url->toString();
             $list[] = array('id'=> $i, 'value'=>$title ,'img_url' =>'' ,'menu_link_url' => $menu_url);
             $i++;
           }


How do I put the copyright / name site in footer In the four themes I tried before choosing the one I have now, the name of my website was always featured with the copyright in the footer of my webpages, but now all it says is "Copyright © 2013, ."

Is there an easy way for me to adjust the code so it does credit the site after that comma and before the period? I'm not very familiar with code so I'd be ever so grateful for an easy way. I tried searching for the copyright sign and the year in a few pages but they didn't show up so I suspect there are other ways to describe those in code, right? :)

First, make sure your site name is stil configured correctly. You can do this by going to yoursite.com/admin/config/system/site-information.

If the site name is there and still does not show up, then the theme you've selected is likely not working correctly. Head over to yoursite.com/admin/appearance and click on 'Settings' next to the theme you're using. Browse around and see whether there are any options to set the copyright message.

Failing that, modify the message directly in the template files. You will have likely installed your theme to /sites/all/themes/theme_name or /sites/default/themes/theme_name. Browse to this folder and look for a file called page.tpl.php (it may be in a subdirectory). This file will likely contain the copyright message which you can change right then and there. Alternatively, the copyright message maybe in the html.tpl.php file, which should be in the same location as page.tpl.php.

With Drupal 7 you can save the Text Format of the block as PHP code, so you can add the <?php echo date("Y"); ?> and it will display the year.


How do I add a custom textarea into the checkout screen? I want to add 'Notes' textarea for adding addtional message by customer while placing the order.

I have added additional textarea in 'Order types' page (/admin/commerce/config/order-types/default/edit/fields). It is displaying in order page but not in checkout page.

Example: Customer is placing an order for Toys and they want to add message saying 'Please deliver in 2 days..'

Edit: I have seen same question in Drupal 7. But there is no 'Commerce Fieldgroup Panes' module in Drupal 8.

You will need to write a custom checkout pane plugin, I'm afraid.

Docs here: https://docs.drupalcommerce.org/commerce2/developer-guide/checkout/create-custom-checkout-pane

You can add custom fields using profile > Customer by following path.

/admin/config/people/profiles/manage/customer/fields

You must have installed Profile module also with Commerce 2


How to display the currently logged in user's details I am using D7 and views for one of my projects. I have created a view that displays the name, age, role and orders of the user. I would like these things to displayed only for the logged in user. For instance user/1 should get his name,age,role and orders only, he should not be able to see the other's details. Similarly each and every user must be able to see their own details. I know i can use the uid from the url, but not sure how to achieve this.

Thanks

Create a custom module and add following function.

function login_user_fn(){
   global $user;
   //print_r($user);
   $fid = $user->picture;
   $file = file_load($fid);
    if($file !=''){

    $user_pic  = theme('user_picture', array('account' => $user , 'path' => $file->uri,));

    return ('Hello '.$user->name.'<br/>'.$user_pic);
  }
}

And than call custom function " login_user_fn()" in our drupal custom block body.

You want the global variable $user...

http://api.drupal.org/api/drupal/developer!globals.php/global/user/7

Then the user_load() function...

http://api.drupal.org/api/drupal/modules%21user%21user.module/function/user_load/7


How to set the size attribute of a select field? When you use a "select" field with multiple values Drupal generates this HTML:

<select multiple="multiple" name="..." id="..." class="...">

How can I inject the size="..." attribute? This will cause the box to show more values.

You might be able to do it with the #size property of the Form API. I am not sure, but you might need to also set the #multiple property to TRUE in order for the #size to be honored.

It it also not clear from the question if you are creating your own form using the Form API, modifying an existing Form API form using a hook_form_alter(), or writing your own form HTML (which I imagine - and hope - you are not doing).

Try this to modify Select list Height & width drupal Way

// Increase Height of Select list
$form['field_example1']['und']['#size'] = 15;

// Increase Height of Select list
$form['field_example2']['#size'] = 20;


Problem in deploying Drupal 8 application I am trying to deploy a Drupal 8 application to another folder from development.
Using PGSQL as database server.
I have database named xyz.
I am copying that database to another one named abc.
The problem I am facing:
When I use old database xyz for new code base, it is running fine.
But, when I use abc, which is exact copy of xyz, it is showing error.
Following is the error I am facing:

Array
(
    [%type] => Recoverable fatal error
    [@message] => Drupal\Core\Render\Markup Object
        (
            [string:protected] => Argument 1 passed to Drupal\Component\DependencyInjection\Container::__construct() must be of the type array, boolean given, called in /PROJECT-PATH/core/lib/Drupal/Core/DrupalKernel.php on line 890 and defined
        )

    [%function] => Drupal\Component\DependencyInjection\Container->__construct()
    [%file] => /PROJECT-PATH/core/lib/Drupal/Component/DependencyInjection/Container.php
    [%line] => 119
    [severity_level] => 3
    [@backtrace_string] => #0 /PROJECT-PATH/core/includes/bootstrap.inc(552): _drupal_error_handler_real(4096, 'Argument 1 pass...', '/Applications/M...', 119, Array)
#1 /PROJECT-PATH/core/lib/Drupal/Component/DependencyInjection/Container.php(119): _drupal_error_handler(4096, 'Argument 1 pass...', '/Applications/M...', 119, Array)
#2 /PROJECT-PATH/core/lib/Drupal/Core/DrupalKernel.php(890): Drupal\Component\DependencyInjection\Container->__construct(false)
#3 /PROJECT-PATH/core/lib/Drupal/Core/DrupalKernel.php(465): Drupal\Core\DrupalKernel->initializeContainer()
#4 /PROJECT-PATH/core/lib/Drupal/Core/DrupalKernel.php(655): Drupal\Core\DrupalKernel->boot()
#5 /PROJECT-PATH/index.php(23): Drupal\Core\DrupalKernel->handle(Object(Symfony\Component\HttpFoundation\Request))
#6 {main}
)

The website encountered an unexpected error. Please try again later.

Can somebody please help me solving this.

EDIT:

I have correctly changed settings.php file for new code base and also changed the correct database name.

The error indicates that Drupal is failing at boot(). Check if your DB connection settings in settings.php that is located in the sites/default directory points to your new database.


Contextual filters and node types I have a block that is displaying related content to the node being viewed. Currently it's displaying node titles for three content types : hotel, tour operator and transport.
I would like it to display only content type that is similar to the content of the node currently viewed and filter out the two other content types.

I have been trying to set this up using contextual filers in views but I can't get it to work.

Is it something that can be done using contextual filters without writing any code ? Or do I need to write some php (I can't) to get this to do what I need.

Thanks

It might be possible to add a conditional filter on the node type and then add custom PHP code to get the default value based on the currently viewed node. The code to do this should look like this: (should work both in D6 and D7):

if ($node = menu_get_object()) {
  return $node->type;
}

It would be cleaner to do that in a views handler, that is however quite a bit more complicated to set up than pasting the above code in the textfield in the views UI.

Instead of using contextual filter, you can just simply just add three blocks, each for one content type (hotel, tour operator and transport).

Something like this:
display hotel content listing block only for hotel node, transport listing block only for transport node.

Don't forget to exclude the current node from the block view, so it won't show duplicated content.


Post or upload file to specific user I am new to Drupal, I wonder how can I post file(s) that should be viewable to specific user? for example upload a pdf invoice to a specified user? Thank you!

If you want to send private message with file, use Privatemsg module. It used to have issues with attachment privacy, but it is Closed (fixed) - should work for you.

Step 1: Install following modules and enable it.

Entity reference

Chaos tool suite (ctools)

Entity API

Views

Step 2 : Create Content Type:

Here you can add extra field
One for upload file and
another for select user who can acess this file(Which is generated from user list of our site using entity reference module).

Please see:

Edit Field select user:
If you want to allow file to many users then choose Number of values : Unlimited (its give option to checkbox)
If you want to allow file to acess only one user then choose Number of values : 1.

Step 3: Now Add content.

Step 4 : Create view.

Step 5 : User can only see files which is accessible/permission


Define ckeditor add media library location we're currently using ckeditor successfully, but when i go to add media from the library tab it loads up all media, we want to exclude profile images from this, is it possible to define the ckeditor library path, or would we really want to move the profile images to private directory

You could use the Views Media Browser module

  This module adds a Views based Media browser to the site that allows filtering files based on fields attached to the various file types.


Images in CKEditor don't retain size I can't seem to figure out how to retain image sizes in CKEditor.  When an image is sized, and the content is saved, and then edited again, I want the size to stay the same as set originally.

Is there a way to configure this?  If not, I can write JavaScript, so is there an implementation I could approach?

You are looking for Insert module, using this module you can retain the sizes with the help of image cache.

  Insert is a utility that makes inserting images and links to files
  into text areas or WYSIWYGs much easier. It adds a simple
  JavaScript-based button to FileField and ImageField widgets. When used
  with ImageField and ImageCache, images may be inserted into text areas
  with a specific ImageCache preset.

Support for all major WYSIWYG editors, including tinyMCE, CKeditor, the WYSIWYG project (the recommended approach), and plain text areas.
Insert images using ImageCache presets
Maximum width setting for inserted images (for combined use with the Image Resize Filter module)
Per-field insert configuration

I was able to do this with the Picture module:

  The proposed HTML "picture" element (see responsiveimages.org, but has
  not been accepted for HTML 5) is implemented as a display formatter
  for image fields. This module is a backport of Drupal 8 picture
  module. This module will deliver alternate image sources based on
  device capabilities to prevent wasted bandwidth and optimize display
  for both screen and print.


Updates for custom module not showing in update.php list I've created a custom module for my Drupal 7 website, under sites/all/modules/custom/tm_general which has the following updates in the tm_general.install (please see image attached).

The site is being installed from scratch, meaning the DB is empty when installing. After installation, I have enabled the custom module through the UI.

The problem I'm encountering is that when visiting mysite.local/update.php the updates won't show up. It says No pending updates.

What am I missing?

Thanks a lot in advanced!

The 'system' table in your db contains the current "version" of modules, so I would check there first.

Also, if these modules are dependencies, you can just include them in your module.info (writing module .info files in Drupal 7) by simply adding

dependencies[] = devel
dependencies[] = views

and so on.

If you are freshly enabling the module, all updates will be applied by default.
If you are upgrading that module from previous module to new one..then you will see those upgrade messages on /update.php


How do I get rules to select a random node? I'm working on my cron rule that will post to twitter every cron run. Thing is for this rule I need it to post a random node that either conforms to specific values in certain fields, or does something else if that value is false. I could use some help figuring this out.

Basically if The value of X=y I want the view to respond with one action, but if the value of X <> y then I want it to do another. And I need it to do this on random nodes of a sepcific content type.

Any ideas?

See How to Use EntityFieldQuery, particularly the section "Random ordering".


formatting a select custom field I created a custom field with the following definition:

  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {

    $value = isset($items[$delta]->value) ? $items[$delta]->value : '';

    $element += [
      '#type' => 'select',
      '#title' => $this->t('Select item'),
      '#options' => [
        'empty' => $this->t('Select an item'),
        'key1' => $this->t('value1'),
        'key2' => $this->t('value2'),
        'key3' => $this->t('value3'),
      ],
      '#suffix' => '

',
      '#attributes' => ['class' => ['edit-custom-field-widget']],
      '#attached' => [
        'library' => [
          'custom_field/my_js_custom_field',
        ],
      ],
    ];

    return ['value' => $element];
  }

In Formatter class I wrote this:

  public function viewElements(FieldItemListInterface $items, $langcode) {
    $elements = [];

    foreach ($items as $delta => $item) {
        $elements[$delta] = [
          '#type' => 'html_tag',
          '#tag' => 'p',
          '#value' => $item->value,
      ];
    }
    return $elements;
  }

When I show content type item with my custom field I see

"key1" but I would like to see: "value1"

Is it possible to show "value1" directly or are other operations necessary?

For the select Form element, the array key is the value, and the array value is the display of the option. That's why you're getting 'key1' for example.
If you want to achieve your goal you can write it this way:

'#options' => [
    'empty' => $this->t('Select an item'),
    $this->t('value1')->render() => $this->t('value1'),
    $this->t('value1')->render() => $this->t('value2'),
    $this->t('value1')->render() => $this->t('value3'),
],

Although this doesn't seem right :D
Also, while you're at it, you should check 'Select' form element documentation as you shouldn't add 'empty' value but rather use the '#empty_value'and '#empty_options' properties.


How do I change the machine name of a field once it's been created I spaced out while typing the field name an now the machine name is not what I wanted it to be. I know it's just an annoyance. but I'm wondering if there is some way to alter the machine name of a field once it is created.

I suppose this leads me into the second part of my question. if I created a field, and it is no longer being used, how do I go about deleting it, does this have to be done from the database, or can it be done somewhere in the UI.

My procedure is to use drush to clone the field first, then copy the field data with DB queries into the new field table. After I verify the contents of the cloned field, I delete the original field.

I do it this ways because I think the drush method of cloning fields will always be at least as reliable as any cloning code I might craft myself, the data copy query is pretty simple, and I get to check the new field before deleting the original.

drush field-clone field_my_field field_my_field_clone
Insert rows into field_my_field_clone, e.g., INSERT field_my_field_clone SELECT * FROM field_my_field;
Verify the contents of field_my_field_clone.
Delete the field using the UI, e.g., admin/structure/types/manage/my-content-type/fields

Export the SQL file of your database, use the command line sed to replace all occurrences of the term to change, and re-import your database.


ERROR:Cron run exceeded the time limit and was aborted. why? My Drupal installation's cron runs fail when run manually or by cron script.

I thought it might be the Simple News module, but I've disabled then uninstalled that and the problem is still present.

My PHP max_execution_time is set to 120 seconds, but only takes 2 seconds before I'm redirected to domain.com/user/1/edit with no error message is displayed.

When I look in the dblogs I can see:

  Message:    Cron run exceeded the time limit and was aborted.
    Severity:   warning

I have looked in the Apache logs and no PHP error is given. How can I debug in fix this?

Often a drupal_goto() call in a page or module will be sending the execution of the cron run off course.

This often happens when the core Search module tries to index a page with such a drupal_goto() call. The solution is to find that page (or module) and remove the call, or change it so it doesn't fire during a cron run.

Try installing Elysia Cron to allow you to run each Drupal cron task in turn to work out what's causing the problem. From there you'll be able to debug it or look for ideas on the Drupal.org issue queue.

You can see Cron run exceeded the time limit and was aborted

If you have a nginx or any frontend server, it can make this problem.


How do I remove a character from the replacement pattern? In view I call the field field_store_car_model

settings of this field:

formatter: link
result URL is:veyron-164

So far as expected.

But I need this URL: vehicles/veyron-164.
Because of this I have to rewrite the link.

I check rewrite result, format is plain text, I write in the field vehicle/[field_store_car_model]

Result here: vehicles/veyron-16.4.

Now I have this punctuation in the URL! where does the decimal point come from?
From my vocab because view grabs the term BEFORE pathauto cleans it up.

So how can I get rid of the decimal point?
I am sure there is some PHP but WHERE I have to put the PHP code?

Any ideas?

I'm not sure I completely understand your question. But I'm guessing this is what you're looking for.

In Views, under FIELDS, click on the name of your field
Click on REWRITE RESULTS
Enable Output this field as a link
In Link path, insert something like vehicles/[field_store_car_model], where
[field_store_car_model] is one of the available Replacement patterns.

Hope this helps.


Extracting a specific data part of a Field Collection Item I've been playing around with this for the better part of a few days now with no luck. Here is my Collection data:

Collection name: field_video_collection

Within the collection there is a field called: field_video_file_col

My fields print fine in my custom field-collection-item--field_video_collection.tpl.php template, I followed the documentation according to this issue to get my template name and I simply print the fields as <?php print render($content['field_video_file_col']); ?> etc... within that template.

Now for the fun part, I'd like to extract the fid for each field_video_file_col item in the collection in any given node and render it as a printed variable. I followed the answer in this question here on Stack but it does not seem to work for me. if I do:

print '<pre>';
var_dump(get_defined_vars());
print '</pre>';

I see I have this as part of the data available to me for field_video_file_col

["field_video_file_col"]=>
          array(1) {
            ["und"]=>
            array(1) {
              [0]=>
              array(12) {
                ["fid"]=>
                string(3) "888"

So it looks to me that the FID is 888 in this case and I want to render that in my template. My node preprocess function is as such:

function MYTHEME_preprocess_node(&$vars, $hook) {

    $entity_type = 'field_collection_item';
    $bundle_name = 'field_field_video_collection'; // Field name the collection is attached to
    $field_name = 'field_video_file_col'; // Field name within the field collection
    $video_file_fid = field_info_instance($entity_type, $field_name, $bundle_name);
    if ($video_file_fid) {
      $my_fid = $video_file_fid['fid'];
    }
}

The end result needed is that I need to render the variable in my field-collection-item--field_video_collection.tpl.php template as:

<?php print $video_file_fid; ?>

... but this does not seem to work.  I've searched all over and tried many different incarnations of this code and combinations but still no joy.

I use Entity API when work with Field Collection Items. See: Programmatically create and update field collection with Entity API

To work with field collections can do smth like this:

// Wrap node with Entity API
$node_wrapper = entity_metadata_wrapper('node', $node);
// Get the first item from the muli-value field collection
$raw_collection = $node_wrapper->field_video_collection[0]->value();
// Wrap it with Entity API
$collection = entity_metadata_wrapper('field_collection_item', $raw_collection);
//dsm the old value
debug($collection->field_video_file_col->value());

If you already know your field_collection id you can just do:

$collection = entity_metadata_wrapper('field_collection_item', $fid);
//dsm the old value
debug($collection->field_video_file_col->value());

UPDATE:

use the code above in MYTHEME_preprocess_node

UPDATE 2:

So in your case it will be:

function MYTHEME_preprocess_node(&$vars, $hook) {
  if (empty($vars['nid'])) {
    return;
  }
  // Wrap node with Entity API
  $node_wrapper = entity_metadata_wrapper('node', $vars['nid']);
  // Get the first item from the muli-value field collection
  $raw_collection = $node_wrapper->field_video_collection[0]->value();
  // Wrap field collection with Entity API
  $collection = entity_metadata_wrapper('field_collection_item', $raw_collection);
  // print value
  $fid = $collection->field_video_file_col->value();
  debug($fid);
}

Also you can find answer at Understanding Field Collection Values

The code from dropbucket might be helpful to get and prepare all the field collection's data into an array:

$fieldname = 'field_lorem_slides';

// Get the items
$slides = array();
foreach($vars[$fieldname] as $delta => $item_id){
    $data = field_collection_item_load($item_id['value']);
    if ($data)){
                $l = isset($data->language) ? $data->language : LANGUAGE_NONE;
        $slides[$delta] = array();

                // Get the field collection's data prepared in an array
                // Alternatively, you could do $slides[$delta] = $data; in order to get the full objects in the array
        $slides[$delta]['lorem_image'] = '<img src="'.file_create_url($data->field_image[$l][0]['uri']).'">';
        $slides[$delta]['lorem_data'] = isset($data->field_heading[$l]) ? $data->field_heading[$l][0]['safe_value'] : null;
    }
}

// Send the information to the template file
// $vars['slides'] = $slides;


Migrate d2d picture migration destination path incorrect I'm in the process of building a migration module for a d6 to d7 migration using the d2d module.

I'm almost there, but one thing that's holding me back is the DrupalPicture6Migration. After trial and error, this is what I have (using the d2d documentation):

/* Register the picture migration */

$picture_arguments = $common_arguments + array(
  'machine_name' => 'abcdPicture',
  'description' => t('Import Drupal 6 picture files'),
  'default_uid' => 1,
  'source_dir' => '/',
  'destination_dir' => 'public://pictures',
);
Migration::registerMigration('DrupalPicture6Migration', $picture_arguments['machine_name'], $picture_arguments);
}

source_dir points to the correct location: /sites/default/files/userPictures.

I'd expect the migration to go like this:

'sites/default/files/userPictures/picture-1589309970.jpg  -> public://pictures/picture-1589309970.jpg.

But when I perform the migration, the path gets migrated over instead of the pictures. So I end up recieving this error:

'The specified file sites/default/files/userPictures/picture-1589309970.jpg could not be copied to public://pictures/sites/default/files/userPictures/picture-1589309970.jpg.

The entire path sites/default/files/userPictures/picture-xx.jpg is copied into the public://pictures directory.

I am reading up on using destination_file but am failing to make the connection on how I'd code this.

Thanks!

You may try to specify the destination_dir in the __construct() instead of passing the arguments e.g.

class FooUserPictureMigration extends DrupalPicture6Migration {

  public function __construct(array $args) {
    parent::__construct($args);

    // Add simple field mappings
    $this->addFieldMapping('source_dir', FALSE)
         ->defaultValue(MIGRATE_D6_USERPIC_SRC_DIR);
     $this->addFieldMapping('destination_dir', FALSE)
         ->defaultValue(MIGRATE_D6_USERPIC_DST_DIR);

Where MIGRATE_D6_USERPIC_SRC_DIR is your source dir and MIGRATE_D6_USERPIC_DST_DIR is your destination dir (e.g. public://pictures).

Alternatively you can fix the user avatars by the following one-time query:

UPDATE users u
SET picture = (SELECT fid FROM file_managed fm WHERE filename = (SELECT SUBSTRING_INDEX(picture, '/', -1) as filename FROM DRUPAL6_DB.users as d6u WHERE name = u.name AND picture <> '' AND fm.filename = SUBSTRING_INDEX(picture, '/', -1)))
  WHERE u.name <> ''
    AND u.name IN (SELECT name FROM DRUPAL6_DB.users WHERE picture <> '')

WHERE DRUPAL6_DB is your database name for Drupal 6.

i guess you need to use:

 'destination_dir' => 'public://userPictures/pictures',

have you test this ?


How to hide published content to anonymous user programmatically? I have created a new content type programmatically and I would like to set permission so that anonymous users do not see this content when it is published.

How can I do this?

By default, Drupals permission system does not support specific view permissions by content types. You will need a module for that. Have a look at Controlling Access to Content Overview. In Drupal 6 projects I have used Taxonomy access control lite quite offen.

You could use a custom module that:

add a permission for every content type
modify permissions to node/nid with hook_menu_alter

Obviously you can create a permission only for your custom content type.

Here is an example:

<?php
/**
 * Implements hook_permission.
 */
function mymodule_permission() {
  $permissions = array();
  foreach (node_type_get_types() as $type) {
    $permissions['view ' . $type->name . ' contents'] = array (
      'title' => t('View published contents for ' . $type->name . ' nodes'),
      'description' => t('Let users to see nodes of type ' . $type->name),
    );
  }
  return $permissions;
}

/**
 * Implements hook_menu_alter.
 */
function mymodule_menu_alter(&$items) {
  $items['node/%node']['access arguments'] = array(1);
  $items['node/%node']['access callback'] = 'mymodule_check_permission';
}

/**
 * Check permission
 */
function mymodule_check_permission() {
  global $user;
  if ($node->status == 1) {
    if (user_access('view ' . $node->type . ' contents', $user) || user_access('administer nodes', $user))) {
      return TRUE;
    }
  else {
    return user_access('access content', $user);
  }
}
?>


Styling Menu Mini panels I'm having an issue with styling my menu mini panel hover.

Here's the site with the megamenu I'm working on:
http://drupal.scienceworld.ca

As I'm rather new to JS, I was wondering what the best way to center the foldout menu in the browser would be?

This isn't exactly a Drupal question but if you add the following to your CSS this will accomplish I think what you want.

div.qtip {
  top: 170px !important;
  left: 370px !important;
}

Adjust the values to suite your needs.

Edit: You may want to qualify that block of CSS further by prepending with it's wrapper or something, just to give it context and not break these qtip menus in other places


How to create many workbench moderation flows / scenarios I want to manage many content types with the workbench moderation module. Every content type should have its own states and transitions. I tried Workbench Moderation Profile module, but it has many bugs (it's in alpha) that causes many problems for me so I'm looking for any alternatives.

I don't mind developing a custom module, but I don't know how this could be achieved. Are there other solutions here?

I think what you need is Workbench Moderation Types


How can I install modules using the FTP method? I got a error when trying to install modules. What should I set up for the FTP? I just learned Drupal. Who knows what happen? I am using Drupal 7.7.

As kalabro said:

Make sure the folder /sites/default is OWNED by the user that executes the drupal scripts.

On most Ubuntu installations, this is the user Apache user www-data.

chown www-data sites/default

In case, if you've access to /sites/all/modules directory then you can also prefer directly uploading the module-name.tar.gz:

extract the zip  copy the directory to /sites/all/modules/
In web-site, navigate through admin-bar -> modules
check the module in the list
Save configuration

This should install the new module.


Allow html tags in Form submit button in block plugin I'm using a block plugin to render a user specified form. I'm retrieving the form like so:

public function blockSubmit($form, FormStateInterface $form_state) {

    $this->configuration['template'] = $form_state->getValue('template');
    $selected_entity_type_bundle     = $form_state->getValue('entity_type');
    $values                          = explode('.', $selected_entity_type_bundle);

    $this->configuration['entity_type']             = $values[0];
    $this->configuration['bundle']                  = $values[1];
    $this->configuration['entity_type_submit_text'] = $form_state->getValue('entity_type_submit_text');

}

private function buildEntityForm() {
    $values = array();
    // Specify selected bundle if the entity has bundles.
    if (\Drupal::entityManager()->getDefinition($this->configuration['entity_type'])->hasKey('bundle')) {
        $bundle_key = \Drupal::entityManager()->getDefinition($this->configuration['entity_type'])->getKey('bundle');
        $values     = array($bundle_key => $this->configuration['bundle']);
    }
    $entity = \Drupal::entityManager()
        ->getStorage($this->configuration['entity_type'])
        ->create($values);

    if ($entity instanceof EntityOwnerInterface) {
        $entity->setOwnerId(\Drupal::currentUser()->id());
    }

    $form = \Drupal::entityManager()
        ->getFormObject($this->configuration['entity_type'], 'default')
        ->setEntity($entity);

    return \Drupal::formBuilder()->getForm($form);
}

This grabs the form just fine, and I render it using

public function build() {

    if ($this->configuration['entity_type'] != '') {
        $entityForm                                = $this->buildEntityForm();
        $entityForm['actions']['submit']['#value'] = t($this->configuration['entity_type_submit_text']);// Editable submit button value.
        if ($this->configuration['template'] == 'learnmore') {
            $entityForm['actions']['submit']['#value'] = ''.$entityForm['actions']['submit']['#value'];
        }
    } else {
        $entityForm = '';
    }
    $entityForm['actions']['preview'] = '';

    $content = [
        'template'     => [
            '#type'       => 'container',
            '#attributes' => [
                'class'      => [$this->configuration['template']],
            ],
            'header'  => [
                '#type'  => 'html_tag',
                '#tag'   => 'h5',
                '#value' => $this->configuration['label'],
            ],
            'form' => $entityForm,
        ],
    ];

    return $content;
}

Which renders the form. But I'm setting the submit button text as specified by the user like so

$entityForm['actions']['submit']['#value'] = t($this->configuration['entity_type_submit_text']);

And I want to add an icon inside the button before the text like so

$entityForm['actions']['submit']['#value'] = ''.$entityForm['actions']['submit']['#value'];

The issue is when it renders the button it includes the html tags so the actual submit button text is

  Submit Button Text

It displays the html tags instead of rendering the actual icon.
Is there a way to allow html tags inside of a submit button on a form?

Use a formattable markup:

use Drupal\Component\Render\FormattableMarkup;

  $value = new FormattableMarkup('<i class="fa fa-mail"></i>@text', [
    '@text' => $value,
  ]);

The formattable string will not be escaped. The variable in the placeholder @text will be escaped and that is important, because it contains user input.

I don't believe this is possible since it's inserting the html into the value attributes of a submit type input tag rather than in the content within a button tag. To resolve this I appended a button element like so.

    $content = [
        'template'     => [
            '#type'       => 'container',
            '#attributes' => [
                'class'      => [$this->configuration['template']],
            ],
            'header'  => [
                '#type'  => 'html_tag',
                '#tag'   => 'h5',
                '#value' => $this->configuration['label'],
            ],
            'form' => $entityForm,
        ],
    ];
    if ($this->configuration['template'] == 'learnmore') {
        $content['template'][] = [
            'test'           => [
                '#type'         => 'html_tag',
                '#tag'          => 'button',
                '#value'        => '<i class="fa fa-envelope-o"></i> '.$entityForm['actions']['submit']['#value'],
                '#allowed_tags' => 'i',
                '#attributes'   => [
                    'type'         => 'submit',
                    'form'         => 'contact-message-learn-more-form',
                ],
            ],
        ];

    }

    return $content;


How to create an image gallery in Drupal 7 I would like to create image galleries in my Drupal 7 site. Ideally the gallery should be easy to create and themable. What is the best way to do this?

It seems like Taxonomy, Colorbox, Views, and the Image field in D7 would be the best way to do it.

Create a taxonomy for gallery
Create a content type for image
Create a View to display the gallery taxonomy
Create a View to display the images in the gallery taxonomy term

I say that is the best approach because it gives you the most flexibility, and will only take you about 30 minutes to set up. Anything else for a gallery (in my experience) tends to be overkill unless you're an actual photo sharing website.

The Views Galleriffic module is fantastic.

This is a views integration for the Galleriffic JQuery plugin.
It allows you to make Views with image fields to create a galleries. These galleries can be attached to nodes themselves or act as stand-alone galleries. Because it uses Views this module is extremely flexible.


How to delete all nodes referencing a given one? I'm working on a catalog based on Drupal Commerce. I have a product display content type referencing product entities. I'm thinking about the ways to make life of a content manager easier.

I made a rule which fires when product is created and creates a corresponding Product display. But I can't figure out the best way to delete a product display nodes when the product is deleted.

Till now I've tried VBO, but seems in Drupal 7 rules2 lacks the ability to run VBO actions.

I guess a quick and dirty solution is to write a module for this task, but I'm looking for something more elegant. Any ideas?

I think a "quick and dirty" module would be the more elegant way. I did something similar recently in drupal 6 with ubercart. I have a content type that sometimes needs to be associated with a product and sometimes doesn't. When one of the custom nodes is deleted, if it has a product associated with it, that needs to be removed as well:

your_module_nodeapi(&$node, $op) {
  if($op == 'delete') {
    $product_nid = db_result(db_query('SELECT nid FROM {content_type_product} WHERE field_product_list = %d', $node->nid));
    if(!empty($product_nid)) {
      node_delete($product_nid);
    }
  }
}

In this case, field_product_list was a node reference field added to the product. I'm sure something similar would work in your case.

The following has been borrowed from here.

Insert the following into your custom module.

/**
 * Implements hook_node_delete().
 */
function mymodule_node_delete($node) {
  if ($node->type == 'mynodetype'){
    $nids = db_query('SELECT entity_id FROM {field_data_field_review_reference} WHERE field_review_reference_nid = :nid', array(':nid' => $node->nid))->fetchCol();
    node_delete_multiple($nids);
  }
}


Drupal 7. Replacing core links with their aliases in theme templates I want to check all templates before rendering and replace links
node/1 node/3 ect to their aliases

For example, i have main landing page template
page--front.tpl.php
and there are some links in this template:
Contact
I want drupal to dynamically change such links to their aliases:
Contact
So, if i change alias for specific page, all urls will remain correct

Is it possible?

Not sure if this is what you're after, but
in your tpl.php file you can change

Contact

to

<a href="<?php print url('node/1');?>">Contact

It sounds as though you have links hard coded into the template, which is probably a mistake. Can you replace the links with a menu or a block so they are easier to maintain?

However, to answer the question, you can use drupal_get_path_alias('node/1') to obtain the alias. Be sure to prefix with a / as '/contact' may be different from 'contact' in different locations on the site.

You could also use the l() function to make the links: l('Contact', 'node/1').

I would really recommend trying to turn these links into a menu if you can and then putting that into the right template region using 'Blocks'. Your future self will thank you.


Multiple forms on single page? Is it possible to put multiple forms on a single page?

I am trying to make a coupon offer page. I wanted to have two forms for two different offers on each side of a page. Each form has a text field for the coupon code and its own submit button. The first form works okay; however the second form's hidden values seem to be overridden by the first form's.

I'm using hook_alter to alter the second form to make it different, but it still has the same form_id as the first. Is this what's causing my problems, or do I need to look/think somewhere else?

The two forms have the same values for "form_id" and "form_token," but different values for "form_build_id."

If you want to add the same form multiple times, you need to implement hook_forms(). See node_forms() for an example.

This allows to use different form_id's, which all point to the same form builder function. For example, you can use yourmodule_some_form_$i and then use hook_forms() to point these to yourmodule_some_form.

See http://www.mohitsharma.net/content/how-show-same-form-multiple-time-page for an example

You can have more than one form in the same page; see what done by node_admin_content(), which uses the following code:

function node_admin_content($form_state) {
  if (isset($form_state['values']['operation']) && $form_state['values']['operation'] == 'delete') {
    return node_multiple_delete_confirm($form_state, array_filter($form_state['values']['nodes']));
  }
  $form = node_filter_form();

  $form['#theme'] = 'node_filter_form';
  $form['admin']  = node_admin_nodes();

  return $form;
}

Leaving out the first IF-statement, the function is adding two different forms that have their own submission handlers.

The problem is with the form fields that are repeated twice. The following array structure would create problems when the form array is flattened, as there would be two "coupon" fields.

$form['first form']['coupon'] = array(
  '#type' => 'textfield',
  '#title' => t('Coupon'),
  '#default_value' => variable_get('mymodule_coupon'),
  '#size' => 60,
  '#maxlength' => 128,
  '#required' => TRUE,
);

$form['second form']['coupon'] = array(
  '#type' => 'textfield',
  '#title' => t('Coupon'),
  '#default_value' => variable_get('mymodule_coupon'),
  '#size' => 60,
  '#maxlength' => 128,
  '#required' => TRUE,
);

Without to see the code being used, I could think that using a page callback that calls drupal_get_form() is probably the easier way, in your case.

$output = drupal_get_form("form identifier") . drupal_get_form("form identifier");

I tried using the following code in Drupal 6.

module_load_include('inc', 'path', 'path.admin');
$output = drupal_get_form('path_admin_form') . drupal_get_form('path_admin_form');

The content of $output for the two form was the following one (I removed the output for the single form fields).

<form action="/dr61/devel/php"  accept-charset="UTF-8" method="post" id="path-admin-form-1">

<input type="submit" name="op" id="edit-submit" value="Create new alias"  class="form-submit" />
<input type="hidden" name="form_build_id" id="form-4eb9304baac34f292901ca23d925ff03" value="form-4eb9304baac34f292901ca23d925ff03"  />
<input type="hidden" name="form_token" id="edit-path-admin-form-form-token" value="cd429a06b84e381eb82ef04cd5033eeb"  />
<input type="hidden" name="form_id" id="edit-path-admin-form" value="path_admin_form"  />

<form action="/dr61/devel/php"  accept-charset="UTF-8" method="post" id="path-admin-form-1">

<input type="submit" name="op" id="edit-submit-1" value="Create new alias"  class="form-submit" />
<input type="hidden" name="form_build_id" id="form-fb363c7ca6d88f71d98e86f8a69b0379" value="form-fb363c7ca6d88f71d98e86f8a69b0379"  />
<input type="hidden" name="form_token" id="edit-path-admin-form-form-token-1" value="cd429a06b84e381eb82ef04cd5033eeb"  />
<input type="hidden" name="form_id" id="edit-path-admin-form-1" value="path_admin_form"  />

There is not a conflict between the HTML ID assigned to the same form field, and the value for "form_build_id" (or "form_token") is different in the two forms.

The implementation of hook_form_alter() used to alter the form should be able to understand in which case to alter the form, or both the forms would show the same fields.

From the point of view of the user experience, I am not sure that showing two different forms with their own submission buttons is the best way to do what you are trying to achieve.
I would think that using a form that shows different fields basing on the values set for other fields would be better. For example, the form could have a selector for the type of the coupon, and would shown different form fields basing on the coupon type selected.


How do I print a username of current profile? I am making a profile page for users on my site, and would like to print out their username. If I do print $user->name it will just print out the username of the currently logged in user, I want the username of the profile I am looking at.
Thanks.

It depends on how you build the profile page (which modules you use), but usually you will get the user info on profile templates by accessing $account, while $user is the logged in user.

So, in short, $account->name should be what you are after. Again, this depends on how you create the profile page. For a profile page built with Views, this would not help, but you could add the name in the View itself.

I guess it should be simple enough with the use of user_load(), and using the loaded object to print the name.


Why does Drupal not register Menus Nor Links? One of the website that I manage the menu system is not working. I have installed many modules (including the commerce modules) and are not being displayed on the menu. However, all modules links (and commerce) works, if I type it on the URL.

After troubleshooting a little bit more I figure out that this is not only for commerce. I created a new content type and is not been display on the node/add page  or in the admin_menu. And once again I'm able to go to the page if I type the URL.

I click on rebuild menu, I flush all caches and still not been register. I do not see any Drupal logs errors.

How can I address this problem ? I cannot expect the sysadmin to know all the URL.

Update 3/27/2015

I'm now using the latest Drupal (v7.35) and I noticed this at first on 7.34.

Like I mentioned before it is not only on the menu. So I do not think the admin_menu is the problem. I remove the module admin_menu and use the toolbar module. But there are missing links on the pages that are been created for the latest module that I have installed. So any module that I enable from now on it would not register the pages.

Update 4/3/2015

I'm now using the latest Drupal (v7.36) and I noticed this at first on 7.34.

I disable/uninstall and enable drupal core menu module and still not fix this issue. Someone from the Google + community suggested that this issue may be cause by the jquery updated I try to used different jQuery version and still have issues. In addition, I try to follow this How to completely wipe and rebuild drupal menus? and to rebuild all my menu and did not work.

I strongly believe is need to be something with the hook_menu not working on my Drupal website.

Update 4/4/2015

I notice that if I add a new content type it would not appear the links on the node/add nor under the content menu. However, it appear in the page admin/structure/types and in the menu under structure -- > Content Type.

Some more updates to address one of the suggested answers to try to get my issue reolved:

This is single site installation.
I do not think is because of the memory_limit. Because I have managed bigger sites that does not have this issue. I did try it out and it did not help. I.e in my setting.php I set it up to 300M and on my php.ini as well. After that I cleared caches, run cron, restart the webserver. And still nothing.

It would be interesting to see if your problems could be related to the "memory limit", which might not be high enough (anymore), especially since in the OP it says "I have many modules enabled".

I'm assuming that this is NOT a multi site. So therefor consider editing your /sites/default/settings.php, and change the line to set the memory limit. If it is a multi site, then edit the settings.php file related to the site where you are experiencing the problem.

That line in settings.php should look similar to this:

ini_set('memory_limit', '100M');

The '100M' in it might be some other number. Whatever the number is, try to increase it with like 50%, or maybe even double it to see what happens after you do so (of course do not forget to save the file after increasing that number).

Curious to hear if that helps somehow ...

Here are a few other thoughts that might ring a bell in the right direction (if you haven't tried them yet):

temporary turn of all caching, to see what the impact is of doing so. Of course that cannot be the real solution in most cases, but at least it might give some indication like "it seems to be caching related".
what about compression of JavaScripts and/or CSS? If you have turned them on, what happens if you (temporary) disable them?

I think this is problem with admin menu caching.
Go to admin/config/administration/admin_menu
Under performance vertical tab uncheck the option to cache menu in client-side browser.
See if it works, otherwise try uninstalling admin_menu module completely and clearing drupal's cache and browser's cache. Also try it opening in another browser.


How to keep track of days online? I'd like to display the total number of days that users were online in a View on their profile pages.

How can I do this?

You can use Visitors module.
It will give you the following reports:

View pages that have recently been visited.
View pages that have been hit frequently.
View pages count per month.
View pages count per day of month.
View pages count per day of week.
View pages count per hour.
View pages count per host.
View access log.
View user activity report (hits, nodes, comments).
View referer list.

and many more things.
Maybe for your requirement you need some customization.

You can take a clue form User Stats module if it doesn't support your requirement and implement your own custom solutions to track user logged in days...

  Provides commonly requested user statistics for themers, IP address
  tracking and Views integration. Statistics are:

  days registered; join date; days since last login; days since last
  post; post count; login count; user online/offline; IP address;


Wich template to override for user account form I am building a theme for my Drupal 8 site and I want to create a custom profile page with user information like this: http://bootsnipp.com/snippets/featured/profile-card but I can't find the correct template to override where I can have access to all the information needed like username, name, picture and for example his address. Also I can't find where is the user-edit form to change the HTML so I can display it as I want.

I am new to Drupal 8 theming and that's why my question may look kind of no sense.
Thank you

EDIT (add more information)

So, I want to make my user's profile edit page to a two column layout where I can have the user base information like name and picture on left and on the right having the form to change the rest of the information like user and password.
What is the best way to achieve that?

use the native interface to add fields and change display

/admin/config/people/accounts/fields

/admin/config/people/accounts/display/full

if the html structure need to be changed , the template

  user.html.twig

can be override in the theme child templates folder.

As an exmaple for custom added individual fields, with fundation classes :

  {% if content %}

        {{ content.field_user_photo }}

        {{ content.field_user_name }}
        {{ content.field_user_status }}
        {{ content.field_user_email }}
        {{ content.field_user_phone }}

  {% endif %}

Enable Twig in services.yml.
No you can see the active template in the html-code


How to ask anonymous to confirm their flag by email? I need to add Flags to one of my content types. Two kinds, actually:

I'll take care of it
Solved

Second flag should be available only to node author, and only if first one was already raised. But that's simple part. First kind of flag is trivial for logged in users, too.

The point is - I need to make first kind of flag available for anonymous users, too. And I need to make sure I have their valid email addresses. Standard confirmation link in mail would be OK - so how do I do that?

I know I can develop custom module from scratch, and I will if needed, but I was sure there is already a out-of-the-box solution, and I simply can't find it now.

Just to make some things clear:

Flag module works for anonymous users if you install Session API. No problem here.
I planned to keep emails in Email Field attached to flag itself. For logged in users it defaults to their email, and if they decide to change it, so be it, I have a way to reach them anyway. For anonymous, I want it verified by link in email, and if it is not verified in time, I want to delete flag. Deletion will be easy with CRON and Rules or simple helper module, it's verification that's complicated (and I hope solved already).

I would use hook_flag_link_type_info() to provide a link type like the 'confirm' link type provided by the flag module. Copy their approach, but on the 'confirm' form you ask for the users e-mail address (if the user is anonymous). You save the value to the email field you added to your flag and the Rules module should be able to do the rest for you. It requires a bit of custom code (not too much I would guess), but the major part of the functionality (flagging, unflagging, rules integration, ...) still comes from the Flag module.

[EDIT] For the verification part: Add a boolean field to your flag ('Verified') which you change with the verification link you send by mail. The "Solved" flag can be hidden/shown with hook_flag_access().

As far as I know, there is only one anonymous user, whose account is shared by all anonymous users. If you want to track the email address of anonymous users, then can't the be given their own accounts?

The only way I can think of storing information for anonymous users, is to set a cookie, which is stored on their computer. But there would be an issue of different anonymous users shared a computer, or the anon user used two different devices.


How do I add the noscript tag? I've a drupal 8 website, where in every page, I would like to add a noscript tag for every script tag. In drupal 8, in html.html.twig, I saw the scripts variable in missing. So how do I do that in Drupal 8?

You can do it in a custom module (MYMODULE.module):

use Drupal\Core\Render\Markup;

function MYMODULE_page_attachments(array &$page) {
  $fallback = '<link href="fallback.css" rel="stylesheet" />';
  $noscript = array(
    '#tag' => 'noscript',
    '#value' => Markup::create($fallback),
  );
  $page['#attached']['html_head'][] = [$noscript, 'mymodule'];
}

I wound up just putting the <noscript> tag into my html.html.twig template. There is a NoScript Tag module, but I didn't feel like adding a module to my site for this purpose.


Which method has better performance I want to update some term id on some node (let suppose 1000 node),My changes is convert all news node with category(term_id) = 3040 to category(term_id)=5).

I know I can do it with several methods( use views bulk operation, write batch running etc, .... ) but my question is about performance of below approaches

Approach based on old method ( node_save)

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
        ->entityCondition('bundle', 'news')
        ->propertyCondition('status', 1)
        ->fieldCondition('field_category', 'tid', array('3040'));
$result = $query->execute();
$nids= array_keys($result['node']);
//ym($nids);

$nodes= node_load_multiple($nids);
foreach ($nodes as $node){
    foreach($node->field_category['und'] as $i=>$item){
       if($item['tid']==3040){
            $node->field_category['und'][$i]['tid']=5;
            node_save($node);
        }
    }

}

Approach based on entity wrapper method

    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'node')
            ->entityCondition('bundle', 'news')
            ->propertyCondition('status', 1)
            ->fieldCondition('field_category', 'tid', array('3040'));
    $result = $query->execute();
foreach($result['node'] as $nid => $stub_node) {
  // Load the full node and wrap it with entity_metadata_wrapper().
  $node = node_load($nid);
  $wrapped_node = entity_metadata_wrapper("node", $node);
  if ($wrapped_node->field_category->value()->tid == 3040) {
    $wrapped_node->field_category->tid->set(5);
    $wrapped_node->save();
  }

in first approach we have one node_load and one node_save but in second approach we have one node_load one creating entity metawrapper creation and one entity wrapper save.
I want to know which method has better performance?
let suppose we have the same situation for both 2 method, I just want somebody tell me ( take a benchmark on one node and  in bulk ( multi node) mode and tell me the performance of both that which one of this method is faster in the same situation.
please provide your answer with facts or benchmark testing result

This is essentially impossible to answer.  You have one part of your question, wrong

Your first method uses a single node_load_multiple() with multiple node_save
Your second answer uses multiple node_load() with multiple Entity API calls

My gut tells me the first will be quicker, as a single node_load_multiple() is typically more performant than multiple node_load() calls, given the same set of nodes.  You also aren't creating the the metadata wrapper objects.

However, you need to do the benchmarking on your system.  There may be a difference, but it may be small enough to not make a real imapact.  Some things that make cross-system benchmarks unreliable

entitycache can have a tremendous impact on a system, especially if you use a non-SQL backend for it
the number of fields on your node can effect how long the wrapper creation process takes, and also how long the node_save() takes
APC and/or OpCache usage and configuration
PHP version
MySQL configuration (or whatever database backend you are using), including some of the Drupal-specific tricks that can improve performance
The number of hook_node_update() instances that fire for each save

After some research and some benchmark  I get below results

In equal and regular situation using Entity Meta Wrapper for change the node fileds has better performance.

  Loading the entity object just for passing into EMW. Unless you
  already have the pre-populated entity, it's more efficient to just
  pass the entity id to entity_metadata_wrapper(); EMW will lazy load
  the field and property data that it needs, hoorah! So much magic.

(if we have $node it is better use it but if we don't have it Don't use node_load to load it before pass it to entity_metadata_wrapper and just pass nid to it has better performance rather first load node then pass it to EMW

// Unnecessary node load... $node = node_load($nid);
$wrapper = entity_metadata_wrapper('node', $node); // More efficient
(if the object isn't handed to you)...
$wrapper = entity_metadata_wrapper('node', $nid)

Saving the entity with node_save(), taxonomy_term_save(), etc. instead of the EMW save() method. Fun fact: both EMW and standard entity controllers include save() methods, so you can call e.g. $node->save() on properly instantiated entity objects and wrappers.

// If you don't already have the node object, don't bother loading it just to save...
$wrapper->field_foobar = 'new value';
$node = $wrapper->value();
node_save($node); // Easier and prettier...
$wrapper->field_foobar = 'new value';
$wrapper->save();

Reference: Death to Field Arrays


Twitter Card Preview is failing with twitter:image I'm trying to add Twitter Cards to my site so that tweets referencing my blog posts will be expandable and show extra info. I've installed the metatag module, enabled the Metatag: Twitter Cards sub-module as well as patched the Twitter Cards sub-module to fix a problem with it generating <link /> tags instead of <meta /> tags.

When I include a twitter:image tag, the Twitter Card fails, but when I remove it, it works just fine. What am I doing wrong?

<meta property="twitter:url" content="http://liberalgeek.com/content/why-do-atheists-celebrate-christmas" />
<meta property="twitter:card" content="summary" />
<meta property="twitter:description" content="I can&#039;t speak for all atheists, I can only speak for myself, so please leave a comment below and explain why you celebrate Christmas! When I hear someone ask, &quot;Why do atheists celebrate Christmas?&quot; my first thought often is: Better Question: Why do Christians celebrate Christmas?" />
<meta property="twitter:creator" content="@kennywyland" />
<meta property="twitter:title" content="Why do Atheists celebrate Christmas?" />

<!-- the following line causes the problem -->
<meta property="twitter:image" content="http://liberalgeek.com/sites/default/files/styles/large/public/Christmas%20Tree.jpg" />

I have tried <meta property= as well as <meta name= and they behave the same way.

The image is publicly visible, it's large enough without being too large... what is wrong?

To be clearer, by "failing" I mean that Twitter refuses to acknowledge there is a Twitter Card for that URL, so the preview is not shown along with the tweet. When I test this on the twitter card preview page, this is the result I get:

However, when I remove the twitter:image tag and generate the preview again it works just fine and looks like this:

During further testing I found the STRANGEST thing. If I change the domain from liberalgeek.com to www.liberalgeek.com, the Twitter Card successfully generates, although the thumbnail image is a broken image. (That may just be due to high twitter volume, but I'm not sure.)

I want the Twitter card to work, even if they don't include the unnecessary www.

Notice that:

The .htaccess file is the standard one installed with Drupal
I don't think I'm using gzip compression
Apache isn't sending back the wrong headers
The error log doesn't shown any error
The access log shows entries with a return code equal to 200, and a correct content length value, when Twitter tries to access the image

I found a site on my server which twitter handles just fine:

<meta property="twitter:image" content="http://www.geekqi.com/images/StylizedYinYangRedLucida.png" />

But I'm not sure what the difference is between this and all of my other sites.

I made a test with this values

<meta name="twitter:url" content="http://liberalgeek.com/content/why-do-atheists-celebrate-christmas" />
<meta name="twitter:card" content="summary" />
<meta name="twitter:creator" content="@kennywyland" />
<meta property="twitter:description" content="I can&#039;t speak for all atheists, I can only speak for myself, so please leave a comment below and explain why you celebrate Christmas! When I hear someone ask, &quot;Why do atheists celebrate Christmas?&quot; my first thought often is: Better Question: Why do Christians celebrate Christmas?" />

<meta name="twitter:title" content="Why do Atheists celebrate Christmas?" />

<!-- the following line causes the problem -->
<meta name="twitter:image" content="http://graphics8.nytimes.com/images/2012/02/19/us/19whitney-span/19whitney-span-articleLarge.jpg">

Changing the image, the card works normally in the preview tool.
I would try to check if you have some restriction on the file.
Have a look at the crawling section of the API docs

  Twitter's crawler will respect robots.txt when scanning URLs. If a
  page with card markup is blocked, no card will be shown. If an image
  URL is blocked, no thumbnail or photo will be shown.

UPDATE
As suggested by the author of the question, changing robot.txt could not be enough. Since Twitter could have cached your file, you need to wait at least 24 hours to let it expires.
I add that the same problem could be found not just on robot.txt file, but also on images. Indeed, wrong Twitter cache could lead to a 404 error and a broken preview image.

Try this: <meta name="twitter:image:src" content="http://liberalgeek.com/sites/default/files/styles/large/public/Christmas%20Tree.jpg" />


How can I embed a view in an email sent by Rules without resorting to the PHP filter? I want to embed a view in an email sent by the Rules module using the standard "Send mail" action.  I have the Mime Mail and Mail System modules installed, and I can send HTML email when it is included in the body of a rule.

Based on this question, I tried the Insert View module, but that only allows views to be inserted into node content, not rules (which are entities, but Insert View does not support generic entities).  I tried adding [view:view_name=display_name] to the message body of my rule, but the view did not appear.  To make sure it wasn't working, I added another rule with the "show a message" action and tried to embed the view there, which also didn't work.  However, I can place the exact same code inside a node body and the view DOES appear, so it appears that Insert View does not work with Rules.

Entity Views Attachment does support generic entities, but this "attaches" the view, whereas what I am trying to do is embed the view in a rule's email message body like this:

  MY TEXT - HEADER

  EMBEDDED VIEW

  MY TEXT - FOOTER

I also only need to do this for one email, so if possible, I would like to add something like a custom token for Rules to embed the view, but I'm not sure how to go about that.

Using Insert View, Mime Mail and Mail System module, you can send views in emails.
After installing and enabling the above modules, you will need to configure Mail System settings and Text Format settings.

In the Mail System settings,
Change all settings to use MimeMailSystem class to send mails.
Note: Site-wide default MailSystemInterface class should be MimeMailSystem.
In the text formats settings,
Enable Insert View Filter in each text format you require.

The problem for you isn't with the rules. It should be the Mail System settings.
I hope this would work.

Use views_embed_view function. Its pretty simple to embed views


Create a footer menu from primary links and should be able to control what should appear I have a menu at the top on hover it expands. I want a menu at bottom of page with same links, but i may choose what should appear here. Is there any module available for it.

For this functionality, try Footer Sitemap

It allows you to choose which menus and/or menu items will be included in the footer sitemap.

You can then customize the template included to manipulate the markup if you need to.

You can achieve this with Menu Clone module.


how to use EntityFieldQuery by language? global $language;

$query = new EntityFieldQuery();
$result = $query->entityCondition('entity_type', 'node')
->propertyCondition('type', 'events')
->propertyCondition('language', $language->language)
->propertyCondition('tnid', $output)
->execute();

I tried using this code and it is showing me empty page, any help on using EntityFieldQuery?

$language variable  is better to be in the function as:

 function getListNode(){
   global $language;
   $query = new EntityFieldQuery();
   $query->entityCondition('entity_type', 'node', '=')
         ->entityCondition('bundle', 'content_type', '=')
         ->propertyCondition('language', $language->language, '=');
   $nids = $query->execute();
   return entity_load('node', array_keys($nids['node']));
 }

it works for me
good luck

The propertyCondition method needs a 3 parameter for the matching to work

propertyCondition('language', $language->language, '=')


How can I float a specific field to the right of another field For example, I have one field in my content type that is a boolean value of "Is this employee certified" next to this field I'd like a Pop-up Date that shows the expiration field. I've created both fields for my content type but I have not seen anything in the CSS that allows my to float or align fields. Any help would be greatly appreciated.

Can I do this with Views? Or with CSS? Thank you

You can just use CSS for this. You will need to find the specific element ID or class for the containing element (div for example) for each of the fields (you can find this out using Firebug with Firefox), then create a CSS rule for each of those elements such as:

#field1 {
  float:left;
  width:150px;
}

#field2 {
  float:left;
  width:150px;
}

You will probably need to then use the CSS rule clear:left; for the field or element that follows after them.

You can use Token Field Or computed Field but the easier way it's to use token field.

You should create a token field then use replacement patterns (each field of your content type has a replacement pattern to print it's value) for example:

I have integer field (field_int), it's replacement pattern should be [node:field_int].

With that you can print the fields between each other.


display the multiple value in single field in drupal 7 view display the related multiple value in single field to avoid duplication in drupal 7 view

Guys help me to solve this issue.

Now it's like this.

Name -----------------------------Organization

sam --------------------------------Ministry of public Health

sam ---------------------------------It solution company

I want to display like below

Name------------------------------Organization

sam----------------------------------Ministry of public Health, It solution company

You can do this by "Rewrite results" follow the following steps.

1) Edit the first field and exclude it from display.

2) Edit the second field and click on the "Rewrite results"

3) check "Rewrite the output of this field" checkbox.

4) find your fields in the "replacement Patterns" and put it in the textarea like this [field1],[field2]

You can use views_php module. This module adds a field to your module that its content is php code. The rows and results of other fields are also available in the php code.


How to disable the first option of select form element I created a custom module that contains a form with select element
I tried to disable the first option like this, but failed to get it work

'#options' => $terms,
                '#empty_option' => '- Select category -',
                '#empty_value' => 'none',
                '#disabled_values' => array('none'),

How could this be achieved without removing the option?

Drupal by default doesn't allow for this, so you'll need to do two things:

Override theme_select()
Create your own callback the create the options
Change the way you define your select options in your form definition

Overriding theme_select():

function THEME_select($variables) {
  $element = $variables['element'];
  element_set_attributes($element, array('id', 'name', 'size'));
  _form_set_class($element, array('form-select'));

  return '<select' . drupal_attributes($element['#attributes']) . '>' . custom_form_select_options($element) . '</select>';
}

Create your own callback the create the options:

function custom_form_select_options($element, $choices = NULL) {
  if (!isset($choices)) {
    $choices = $element['#options'];
  }
  // array_key_exists() accommodates the rare event where $element['#value'] is NULL.
  // isset() fails in this situation.
  $value_valid = isset($element['#value']) || array_key_exists('#value', $element);
  $value_is_array = $value_valid && is_array($element['#value']);
  $options = '';
  foreach ($choices as $key => $choice) {
    if (is_array($choice) && !isset($choice['data'])) {
      $options .= '<optgroup label="' . check_plain($key) . '">';
      $options .= form_select_options($element, $choice);
      $options .= '</optgroup>';
    }
    elseif (is_object($choice)) {
      $options .= form_select_options($element, $choice->option);
    }
    else {
      $key = (string) $key;
      if ($value_valid && (!$value_is_array && (string) $element['#value'] === $key || ($value_is_array && in_array($key, $element['#value'])))) {
        $selected = ' selected="selected"';
      }
      else {
        $selected = '';
      }
      $options .= '<option value="' . check_plain($key) . '"' . $selected;
      if(is_array($choice) && isset($choice['disabled']) && $choice['disabled'])
      {
          $options .= ' disabled';
      }
      $choice = is_array($choice) && isset($choice['data']) ? $choice['data'] : $choice;
      $options .= '>' . check_plain($choice) . '</option>';
    }
  }
  return $options;
}

Change the way you define your select options in your form definition. Turn the option into an array with two keys:

data: The display value of the element
disabled: A boolean indicating whether to disable the element

Example:

$form['select'] = array(
  '#title' => t('Pick something'),
  '#type' => 'select',
  '#options' => array(
    'yes' => array('data' => t('Yes'), 'disabled' => TRUE),
    'no' => t('No'),
  ),
);

If you just set an empty array as value the option will be disabled.

['#options']['my disabled option'] = [];

this option will get the name, 'my disabled option' and will be disabled.


How do I get the current path alias or path? How can I get the current alias and/or path in Drupal 8?

In Drupal 7 I did this with drupal_get_path_alias(). What is the equivalent code I should use in Drupal 8?

Some of the other answers were only correct during previous alpha/beta versions of Drupal 8, or seemed to be incomplete. As of beta7 (and hopefully permanently), the following rules should apply:

For the current raw path (the un-aliased Drupal path):

$current_path = \Drupal::service('path.current')->getPath();

For the current URI, which is pretty-much a direct representation of the request (it may even include a query string):

$current_uri = \Drupal::request()->getRequestUri();

There is of course no guarantee that this $current_uri value will give you an alias, even if one is available for the request, as it only represents what the user has requested. So to strictly do what you are asking about (get alias if available, and path if not) I think you could do:

$current_path = \Drupal::service('path.current')->getPath();
$result = \Drupal::service('path.alias_manager')->getAliasByPath($current_path);

Of course depending on the type of processing you are doing it may be best to be working with routes instead of paths, but I suppose that's a whole other topic.

Get the current route name:
$current_route = \Drupal::routeMatch()->getRouteName();

Get current query parameters (upscaled):
$current_parameters = \Drupal::routeMatch()->getParameters();

Get current URL as an object of type Drupal\Core\Url, which requires the query parameters to be an array of values rather than upscaled objects
use Drupal\Core\Url;

$url = Url::fromRoute(\Drupal::routeMatch()->getRouteName(), \Drupal::routeMatch()->getRawParameters()->all());


Allow users to annotate content in Drupal 7 Is there any way to allow users to add some private annotations when reading a book page for example ?

It seems that the annotate module is not anymore supported.

The book Pro Drupal Development is probably the most popular book for learning how to build Drupal modules. In the 3rd edition, which covers Drupal 7, the author uses the Annotate module as an example of how to build a module from scratch.

If you read the first chapters of the book you could easily write the module yourself, or even better, try to port the module you mention to 7.x. By the way, remember to check Errata of the book first.

You can check this article on annotations it may help you - http://wearepropeople.com/blog/annotations-in-drupal-8