Should a module file look like this? I've been having problems with one of my Drupal sites and have narrowed the problem down to the Views module. In my Apache error log, I see this:

  [Tue Oct 18 09:57:08 2011] [warn] mod_fcgid: stderr: PHP Parse error:  syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting ']' in /home/lakedistrict-holidayideas/public_html/sites/all/modules/contrib/views/handlers/views_handler_filter_in_operator.inc on line 206

Looking at the views_handler_filter_in_operator.inc file, I see this on line 206:

 $form['value']['#dep

Does that appear to be a normal line of code? To my untrained eyes, it looks incomplete.

I've reinstalled the module, but the problem remains.

If it appears to be that there's a problem with the module, I'll make a post on the Views issue queue on Drupal.org.

Since you're using Views module version 2.12, I looked up that file in the repository viewer:
http://drupalcode.org/project/views.git/blob/42fe4029ca7d7410f15933032a17e979bb0957c4:/handlers/views_handler_filter_in_operator.inc

Looks like line 206 should be:

$form['value']['#dependency'] = array($source => $this->operator_values(1));

I'd try re-downloading the entire Views module. Maybe your copy got corrupted along the way.


How do you programatically render a views exposed filter form block in a tpl in Drupal 6? I am trying to setup my views exposed filter form block in a custom tpl. How do I do this programatically? Note: My views setup display type is a page with a separate exposed filter form block.

views_embed_view displays the whole views block. Therefore in your template you put:

print views_embed_view('most_read_today', 'block_1');

If you are needing to pass arguments to your 'exposed filter', add a 3rd argument.


Open Outreach distribution image not displayed & unable to upload new image I installed Open Outreach via Acquia Dev Desktop on my Win 7 machine.

I am using Firefox, but the problem is also present in IE.

I deleted the second sample blog entry that came with the distribution. When I click the remaining blog (Welcome to our new website) the image that shows on the home page does not show on the blog page. Furthermore, when I attempt to upload a new image (after deleting the old one) I get a "Destination *" message, but no box to type in next to it. When I click Next I get "An illegal choice has been detected. Please contact the site administrator.".

In the message log I see the following.

Illegal choice public in Destination element.

http://openoutreach-7-x-1-19.dd:8083/media/browser?render=media-popup&types%5B%5D=image&activePlugins=&enabledPlugins=&schemes%5B%5D=public&schemes%5B%5D=private&file_directory=&file_extensions=png+gif+jpg+jpeg&max_filesize=&uri_scheme=public&min_resolution=&max_resolution=1000x1000&plugins=undefined

I am a newbie. Can you give me simple instructions as to how to fix this?

Thanks!

It appears that, by looking at the code that causes that "Illegal choice public in Destination element" error you got, "Public" is not an acceptable choice in the element with name "Destination". Not sure if this rings any bell, but maybe it helps somehow.

After you find the solution (reason) for this problem, you probably also solved the remaining error as you mentioned about ' ... "Destination *" message ...'


Enable/ Disable elements under 'edit' depending on role I want some users to have access to certain items under the 'edit' tab but hide others...

I know you can allow a role to 'edit' or not 'edit' a published node content type but that enables and disables the whole of the edit tab!

As I understand your question, you need the Field Permissions module. From the project page:

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

This will allow you to grant permission for editing certain fields to a specific user role.


Node's teaser view mode has extra "panels-default" markup/wrapper/classes I'm using bootstrap 3 as basetheme and Physics as main.
On content types view mode (teaser) I've created a Horizontal tabs group and added 3 Horizontal tab containers under it.

The problem is that content inside Horizontal tab is wrapped with Bootstrap panel markup which creates unnecessary borders and shadows. I can't find that where this is defined.

And since Horizontal tabs and Horizontal tab aren't part of either themes or supporting modules it seems weird that content is wrapped in any bootstrap markup.

Result

View mode/containers setup

UPDATE

The question is that why are these fields wrapped with a bootstrap panel markup?

Copy bootstrap-panel.tpl.php from base to main and configure it per requirements.


Update field data added in user form using a hook? I've added three fields in user form.

User code
User name
User ID.

I want to add this field data into the database. My question is, in which hook, i should write the logic of manipulating and saving data.

Hook implementation depends on when you want to manipulate the user account data.

Before creation of a new user account, hook_user_insert().
Before updating any user account, hook_user_update().

If you need to update existing users with new data you need your own custom function that makes user of user_load() (to load a user object) & user_save() (to save your manipulated user object with new data).


Custom PHP code before a site is loaded I need to execute a few lines of PHP code before a page is rendered.
Basically what I need to do is to store in a database the user's original http_referer together with an anonymous visitID, and save this visitID in a session.
So the code i need to execute is something like this:

if(!isset($_SESSION['lock'])) { // we only want this to run when the user enters the site, not on subsequent pages
   $_SESSION['lock'] = true;
   save_http_referer_in_database();
   $_SESSION['visitID'] = mysql_insert_id(); // gets the id of the last inserted row
}

I've found a few solutions but not very convincing.
UPDATE 16th Oct: I'm making a short summary here as I've edited this post many many times.

First, I tried putting the required code at the top of html.tpl.php... it works, but stops running if i enable caching. Not good. I don't want to disable caching.
I tried putting the code in the settings.php and index.php, but drupal's session aren't initialized yet in there.
As suggested here, I've tried creating a custom module implementing hook_boot, but this solution has weird problems when caching is enabled.
What happens is that the save_http_referer_in_database() function correctly runs the first time, but when the user loads another page, it runs again! All the subsequent page loads don't trigger it again though.
This post has some more informations about it.
This bug report on Drupal.org shows some other bad things that happen with sessions and caching and hook_boot()
SOLUTION: Use cookies instead of sessions.

Regarding @znerol's answer:

I wouldn't have DB problems anyway because i save visitID and referer in another database, so i manually db_connect() to my database and manually run mysql_query(). Hopefully it's not a bad thing.
How could exposing the visitID to the user create problems? The visitID is a completely anonymous ID, generated by MySql as the Auto Increment column of the table containing the http_referers. I can't imagine how someone could use this ID to do something 'bad'.
The reason why I want to do it inside my application, is that I need the visitID to "connect" certain actions on my site to the http_referer (through the visit_id foreign key). So basically i have a structure like this:

VISITS (visitID, http_referer)
EVENTS (eventID, event_description, fk_visitID)

When an event is triggered, I add it to the database by fetching the fk_visitID from the cookie (or session)

I couldn't find a way to accomplish that through AWSTATS (which is installed) or Google Analytics or other similar software.

I didn't know Piwik but thanks to the API it might be fine for what I need, right?

hook_boot runs on every page, even on cached pages. Implement it in a custom module.

Generally it's better to not require code to run on cached pages, but that's the best option you have, as opposed to hacking index.php. The primary problem I see with depending on hook_boot, is that you open your self up to a very simple denial of service attack. Anyone with curl and a shell can potentially bring your site down with much less resources when caching isn't used well.

One option to consider it relying on javascript to make a call the site via ajax. That way you can save yourself quite a bit of load on the server.


How do I get the user's email in the user profile template? I am trying to customize the user-profile.tpl.php file.

I can access the all custom fields using $user_profile['field_fieldname'], and I can even access the user picture using $user_profile['user_picture'], but I don't know how to get the user email.

I solved this by following way.

$account = menu_get_object('user');
$mail = $account->mail;


How to set different languages for different domains, and display the language switcher accordingly? I have a website with different domains and I'd like to have some domains to have different languages.

I have a main site which is example.com, it's the main "group" site, it has multiple languages, in this case french, english, russian and spanish.

Then i have several other "sub" sites assigned to other domains and each have one or many assigned languages.
For example:
es.example.com is in spanish
ru.example.com is in russian

The problem is for a sub site that have more than one language.
for example:
ca.example.com would be in french and english.

How do you configure drupal to be able to achieve this, and how do you make the language switcher display only the languages available on the domain ?

I have domain access and i18n installed obviously.

Thanks in advance for your help.

A complete summary of the multilingual system for Drupal 7 can be found here: Drupal 7's new multilingual systems compilation. Specific to your question of "...some domains to have different languages", setting / detecting the language by domain can be setup in http://YOURSITE.com/#overlay=admin/config/regional/language/configure -> Detection and selection tab after the Locale module has been enabled. Details on the Detection and selection tab.

Notice that new to Druapl 7 this is now a weighted list that is processed to determine what method to use for the display language. The higher in the list the more likely that the method will be used.

In the case of you situation I suspect you'll have to write your own language selector to add to this list. I have to confess that the situation you describe sounds like it could better be solved in configuration that in code. Perhaps consider add the language into the domain in addition to the country - for example ca.example.com could be French: fr.ca.example.com and English: en.ca.example.com.


How to stop animation and turn off the delay time in superfish menu? I created a superfish menu block and set the animation speed at fast and delay time to 0. Still it taking time to open the child menus. I disabled the animation using this article but still it taking time to open the menu. I want to open the child menu just when user hover on the parent menu.

Adding custom js did the trick.

jQuery(document).ready(function() {
    jQuery('ul.sf-menu').superfish({
       delay: 0,
       autoArrows: false,
       speed: 'fast',
       disableHI: true
    });
});


Create a list like draggable menu I am using Drupal 7.
I would like to create a list of items in which all items can be arranged using Drag 'n' Drop. Just like Menu system in Drupal.

I found drupal_add_tabledrag() but it seems it is used in table display/output. I want to create a simple list with rows and it should be arranged, just like menu in Drupal7.

Though there is DragableView module, but I want that every logged in users can create a list and they can manage their own list.

Do you know Node Queue?
It could be useful for you:

  The Nodequeue module allows users to collect nodes in an arbitrarily
  ordered list. The order in the list can be used for a any purpose


Issue with Uploaded Images Alright, I've got an odd issue with what I am guessing to be is size. I have uploaded several images to a site, and while they upload correctly (meaning I can find the image in the appropriate folder without loss of quality), I can't see images larger than what I am guessing is from 400-500KB. As you can see, the two bottom images are 353KB or less in size, and I can see them. However, the upper three are 850KB or larger and cannot be seen, am I doing something wrong with this? Thanks.

I had a similar issue, I just reset and added to the PHP limits in my configuration. After that, worked like a charm.


How to put conditional multiple recipients in drupal 7 default contact us form I am working on a multilingual Drupal 7 site using a single contact us form. It has 4 languages. The contact us form is multilingual i.e labels of form fields changes, depending on the language you have selected. But it has a single recipient now.

Now I want it to have conditional recipients i.e if English is selected the contact us form should be emailed to a@gmail.com and if Danish is selected then to b@gmail.com and so on.

Any suggestions how to do it ?

website form : http://dev-salman.com/venuepoint/contact

With this module https://www.drupal.org/project/tcontact you can create different contact categories for each language so you can specific different recipients.


How can I ensure that fields from a Views query plugin work as tokens? I have a Drupal 7 Views query plugin module that pulls in data from a RESTful API for use in Views. I used this series of articles as a starting point to build it: https://www.lullabot.com/articles/building-views-query-plugins. I now need to port it to Drupal 8.

I have made a start on the porting process, with the help of this series of articles: https://www.lullabot.com/articles/building-views-query-plugins-dupal-8-part-1. The Drupal 8 module now successfully pulls in data for the fields that use the 'standard' handler.

I'm currently stuck on trying to get tokens representing one of those fields to work when rewriting results.

The field is called access-url and contains URLs. If I tick 'Override the output of this field with custom text' on that field, and enter the token form, {{ access-url }}, it just returns '0' for every record, whereas if I untick that box it returns the URLs correctly. Meanwhile, the token form of the id field works correctly.

(In real life I will want to use {{ access-url }} under 'Output this field as a custom link', but 'Override the output of this field with custom text' illustrates the problem better.)

How can I get the {{ access-url }} token to work correctly?

I expect it would be helpful if I posted some code, but I'm not sure what code would be most helpful, so please let me know.

Additional debugging info: as far as I can tell, all seems well until it gets to the line in PluginBase::viewsTokenReplace() that runs $this->getRenderer()->renderPlain($build). $build at that point has the value of access-url in it, but the renderer returns zero.

Eventually I realised that it was only tokens containing hyphens that weren't working, and sure enough, it turns out that hyphens are not allowed in Twig tokens. Or, to be more accurate, they are interpreted as minus signs (https://www.drupal.org/project/drupal/issues/2371633). That was why the {{ access-url }} token was returning zero: access minus url equals zero, apparently. So I just replaced all of the hyphens with underscores.


Sub pages result in 404 I'm running Drupal 7, and I've cleared the cache through drush many times (drush cc all). I'm trying to access any subsequent pages beyond the front page and it results in a "Object not found error" error.

Does anyone have any idea? I feel like it's most likely an Apache or site configuration issue but I can't figure out what it is.

Sounds like the problem is that clean URL's are enabled in Drupal but not supported by your Apache configuration (make sure that mod_rewrite is enabled and the folder/vhost has AllowOverrides enabled) or the .htaccess file is missing.

You can verify that this is the problem by accessing the non-clean version of the URL. For example, instead of example.org/something, try example.org/?q=something.

See http://drupal.org/getting-started/clean-urls for more information.


Drupal logo is displayed with out the dimensions like width and height My client raised an issue that when viewing the source the logo of my website does not have any attributes, but I saw many themes, and not all have those attributes.

How do I add these to the logo? Is it really required?

The width and height is not required when using the img tag, but you can add it by overriding the theme template for the page, aka page.tpl.php in the directory containing the theme for your site. Usually sites/.../themes/YOURTHEME


What is the relationship between regions and panels? From here, it is clear that regions contain blocks, but when working with Panels, are regions still relevant? If yes how? What is the relationship between regions and panels? Thanks.

Panels can be thought of as self contained themes you define within a specific Drupal Theme displaying the page.  Like Drupal themes, panels also contain regions, but you define them, rather than the default theme.

And to expand upon this a bit more:

Panels presents a way to display content similar to a theme, but in a more modular fashion.   This site gives an excellent example of how panels can be used. A mini-panel, for instance, is used similarly to a  block and can, in fact, be placed in a region of a theme just like blocks are.  The advantage is that a panel/mini-panel can contain its own layout regions further breaking down the layout.  For instance, the signature blocks in this Drupal Answers question layout contains the top line with how long ago the question was asked, the avatar, authors site name and reputation.  Using mini-panels this configuration could be defined as a single mini-panel and placed inside a larger panel that holds other mini-blocks laying out the arrows and other graphics at the left side, the actual question, the tags and the action links such as links, edit, etc.

This larger panel construct can also be placed within a theme region such as the 'content' area giving the site display you see for your question page. Other content such as a list of the answers to your question can also be added to the main content area. Other regions such as right sidebar can hold the related questions links.  In this way your panels are placed within the existing theme framework providing additional content layout flexibilities.

Panels can be laid out in prearranged formats or be user designed as custom layouts.  These panel layouts contain their own regions so you are in-essence adding regions within a theme regions.

Panels can also go one step further and totally replace the theme layout using the Panels Everywhere module.  This offers the user the ability to control the layout and styles directly.  While contributed themes can be very flexible and sophisticated, these very capabilities can also make them very complex and difficult to modify to meet individual project demands.  The more experienced you become in using Drupal, the more attractive this ability may become for you.

Panels also offer another advantage.  The panels module works very well with CTools Page Manager, joining graphic control with Page Manager's content control.  In this way you can intercept URL requests before Drupal responds and set rules and layouts to respond to various context conditions using 'Variants'.  IN this way you can vary the content depending upon the permission levels of a user, or the content type being requested.  If specific conditions are not met, then panels/page manager, returns display control back to Drupal.  In addition, panels can display views and even pass its context to the view to determine what the view will show.  All of this gives the designer the control necessary to duplicate the content and layout this site provides.


How to create a node in Drupal 7 with a custom nid I have to create a node in drupal 7 with a custom nid but the solution I've tried doesn't works (The created node not appears in the backend).
If I create the same node without the custom nid, it works.

Code:

$node = new stdClass();

$node->nid = intval($insert['id']);
$node->vid = intval($insert['id']);
$node->uid = 1;
$node->type = 'nodetype';

$node->title = $insert['name'];
$node->created = time();
$node->changed = $node->created;
$node->promote = 0;
$node->sticky = 0;
$node->format = 2;
$node->status = 1;
$node->language = 'en';

$node->field_custom_1 = array('und' => array(array( 'value' => $insert['foo'] )));
$node->field_custom_2 = array('und' => array(array('value' => $insert['hello'])));
$node->field_custom_3 = array('und' => array(array('value' => $insert['world'])));

if ($node = node_submit($node)) {
    node_save($node);
    drupal_set_message(t("Node ".$node->title." : ".$node->nid." added correctly"));
}
else {
    drupal_set_message(t("Node ".$node->title." added incorrectly"), "error");
}

What's wrong? Thanks

http://api.drupal.org/api/drupal/modules%21node%21node.module/function/node_save/7

I believe node_save() takes all the node edit form input and builds a new node with a node->id for you.

node_save() either tries to update an existing node, or give you a newly saved one. You want to set what NID it gives you back.

Assuming an SQL storage engine for Nodes. You'd have to pick a NID greater than the current SQL MAX(id) FROM {node} ...

You could then make a new node entity with entity_create( See Creating and Editing Entities Documentation ) just passing the bare parameters you want: NID, type, bundle.

Then you could do a node_load() and then a node_save() with your code above to actually build out the rest of the node ...

That's what I would try.


How to get users (entities) for a certain field value? I want to write a function that returns users which have entered a certain value to a custom user field.

Lets say there is a custom birthday field for every user. What would be the best way to get all users with a certain birthday?

I could create a DB query that searches the field_data_field_birthday table and returns the entity_id(s) (which in this case would be the users id(s)) for which the field_birthday_value matches a given value and then load the user(s).

This seems a little bit crude, are there generic functions for this use case available? In the entity API or the field API maybe?

Simple example for the use case I asked about:

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'user')
  ->fieldCondition('field_birthday', 'value', $birthday);

$result = $query->execute();
$users_ids = array_keys($result['user']);


Views Entity reference (user): how to show profile values of respective user only i have a rather complex view and have troubles with showing the correct values. im trying to focus on the main issue.

there is a node (team) with entity reference fields to multiple users. the node has for instance two referenced user (UID 80 with 56 points on his profile, UID 23 with 23 points). now, my problem is that i cant get the view to show the correct values (points) of the respective user only. i have installed the views distinct module, but i still cant get the correct values.

what i would need is something like this:

user / points

80 / 56

23 /23

what it does is now is that it shows the values of all users that are referenced (without the views distinct module). with the views distinct module enabled it shows sometimes the values of the first user, sometimes the values of the second - but it does not show the correct values.

i hope this makes some sense. if not, i can post the whole view, but its rather complex.

came up with a solution that works for me.
first, ive added to the view the username field for the referenced users. this outputs the (two) different usernames of the people who are referenced.

second, ive added a global field as a filter called "Global: Fields comparison" that compares the name of the team_member with the name of the referenced user. now this shows only one correct entry.

hope this helps someone.


Problems with Clean URLs I've got a problem with Clean URLs. I had a look around and my problem doesn't look like any thing else on this site or anywhere on the internet.

I have a .htaccess file. It's there and it's working. I know because I've set it to remove www. and it is.

I go to Configuration->Search and Meta->Clean URLs (some people don't pass the clean URLs test but I do, it doesn't even come up) I have the option to turn on Clean URLS:

I tick the box and click Save configuration. But this happens:

NO! I ticked you!

So if I go to a clean URL (/contact) it works. But in the menu it comes up as (/?q=contact).

I thought I'd hack the database and turn it on.

But it was on the whole time...
<hold flashlight under chin and look scary>

Does anyone know how to remedy this situation so it stays ticked and comes up clean in the menu?

Ok, alright. I'm not going to kill anyone.

Turns out there was a line in my settings.php file:

  $GLOBALS['conf']['clean_url'] = 0;

Commented it and everything worked just fine.

That was 2 hours of my life wasted...


How to Modify Views output on every 10th item? I have a drupal based project that uses views to output some images and markup in a loop. Each content chunk is similar so pretty standard set up. However I now have a request to uniquely modify every 10th ( or so ) content block that gets output to have a different style and markup.  I am not sure how to handle this in drupal views. Can somebody please point me in the right direction?

I don't know how many items in total would be output.

Views by default wraps each View in a div with a class based on the View's name, eg,

and each row in a div with a views-row-# class, eg,

So, quick and dirty, you could change the first 5 of these with css along the lines of

.view-NAME .views-row-10,
.view-NAME .views-row-20,
.view-NAME .views-row-30,
.view-NAME .views-row-40,
.view-NAME .views-row-50 {

   /* different CSS here */

}

You can cascade down from there if you need or want to change the CSS of any of the fields in the row as well.

If you want to get fancier, you can also add classes to each row based upon modulo arithmetic inside of the Views theme templates or via a pre_process hook and then base your css off that class.

ADDITION BASED ON COMMENTARY:

Can you do something like this with the first/last classes?  Immediately out of the box it sort of does what you want, eg:

creates output like this:

and where last-tenth in this quick and dirty copy and paste is every 10th row?


Block Module jQuery Slider for Homepage I have a simple jquery slider for the homepage of a website, which works in my static HTML/CSS layouts.

I want to incorporate this front-end mark-up into a block module that will allow an admin to add/edit/remove slides. Is there a good module that already does this that I could hack with to get this functionality. Or even better does anyone know a good tutorial (doesn't have to be for a slider), that shows developing a module where you can add/edit multiple items specific to that block module (separate to the main content); in my case it would be adding/editing slide items to the slider.

From reading your question, I take it you have zero integration with Drupal. You simply hardcode your entire slideshow in a block.

What I would suggest is that you start with creating a new content type, and then apply either Field slideshow or Views slideshow onto it.

  Provides a Slideshow formatter for Image fields, using JQuery Cycle plugin.

  Compared to Views slideshows, building the slideshow from multiple nodes, this module builds it from a single node, with a multi-valued Image/Media/Field Collection field.

  Views Slideshow can be used to create a slideshow of any content (not just images) that can appear in a View. Powered by jQuery, it is heavily customizable: you may choose slideshow settings for each View you create.


During checkout, why is the customer skipping the payment step? I have a situation during the checkout process where the customer is skipping the payment and moved directly to the fulfillment state.  I'm using the Commerce PayPal module.
Here's my checkout flow: /admin/commerce/config/checkout-flows/manage/default

What's odd is the PayPal buttons display when I'm logged in as Admin, but not when non-admin:

I haven't found an option that looks relevant on the permissions screen, nor have I found a configuration option anywhere.
The order type is configured to use the correct checkout flow (Default).

With Commerce Paypal, I ran into the same issue.
I believe the fix for me was to the move the Payment Information (currently disabled) into the Order Information section. Might also work if you move into Review or Payment section, not sure.
Also, since you're using Paypal, I think you need to disable payment process.
Here is my working setup. Note: I didn't want users to login nor register.


Redirect after user creation via form What would be the proper hook to redirect after the user registration form is submitted and is in valid state?

I'm trying to automatically create a certain content-type node when a user registers and I want to redirect the user to that node's edit form after the user creation form is submitted and validated.

I was thinking of doing this in a mymodule_user_form_submit hook, but not sure if a) this hook exists and b) the validation in place for user registration will still work as intended.

Can anyone share some pointers?

EDIT:

Would the mymodule_user_insert hook run after the validation and submission of the form? Can I redirect from there? AFAIK, I won't have a form_state variable to act on, right?

EDIT2:

While researching for a solution, I noticed I have another (probably bigger) problem: the content-type node I need to create must hold a reference to the user's ID, so I'm getting in a chicken-or-egg situation.

I actually need to create said node after the user is created (otherwise I'll have no user_id), but I need to redirect to the node's edit form after user creation, which means I can't redirect with $form_state.

I think I got everything right, but I would love to be wrong. :D

Can anyone help?

If you have created a custom user registration form my_module_user_register_form, then you can define one or more submit functions for it

function my_module_user_register_form($form, &$form_state) {
    $form['#submit'][] = 'my_module_user_register_form_submit';
    // and now add a second submit function if you like
    $form['#submit'][] = 'my_module_user_register_form_another_submit';
}

and then place the appropriate redirect at the end of the last submit function.

function my_module_user_register_form_another_submit($form, &$form_state) {
   // do other stuff here
   $form_state->setRedirect('node/123/edit');
}


Ubercart how to provide expiry option for a product if its not in auction? How to provide option for products to be automatically expired using ubercart.

I know one solution could be scheduler.

Is there any other solution which can be applicable only for add to cart  products alone instead of auction item which already has expiry dates.

Thanks in advance.

There is one for Drupal 6, but there does not appear to be a solution for Drupal 7.

The easiest way may be to use rules with an additional field in the products content type and set the product to be unpublished after the date (see https://groups.drupal.org/node/240678 for an example).

Another more complex way would be to make a module that runs on cron (hook_cron) loops through all the products (MySQL select * from uc_products for an example), add a new field to the products content type called expired, set it to a date (using the date module), upon looping through products get the entire node (including this field) and see if it is expired.

But scheduler can do what you want, you just need to add a new field to the content type for the expiration date and set it to expire on that.


Best place to add to Drupal.settings from a theme I am working on a theme for a client, and have run into an instance where I would like to add to Drupal.settings via drupal_add_js() from the theme.

In this particular case, it is really most appropriate to do it from the theme itself and not a module hook, as the setting is related to the theme itself.

Doing it from template_preprocess(), or one of its relatives, is too late because $vars["scripts"] has already been built.  I suppose I could do something like the following code, but this doesn't seem right.

$settings = array(
  "bar" => "bar",
);

drupal_add_js(array("foo" => $settings), "setting");

$vars["scripts"] = drupal_get_js();

Is doing it from hook_theme() really the only option, or is the above approach kosher?

I have seen that pattern multiple times before, and it seems to be a standard practice.


How can I target the first item in a view? I have a views page that shows all the latest articles that were posted. I want to show case the latest article in a different div on it's own, and then have my loop with all the other articles.
This is my code for the loop, which is in the node--view.html.twig file -

{{ node.label }}

        {% set text = content.body|render|striptags %}

{{ text|length > 100 ? text|slice(0, 120) ~ '...' : text }}

        Read More

and in my views-view-unformatted.html.twig file I have -

{{ view.getTitle() }}

  {% if title %}

{{ title }}

  {% endif %}

{% for row in rows %}
  {%
    set row_classes = [
      default_row_class,
    ]
  %}
    {{- row.content -}}
  {% endfor %}

One possible solution ist to create two views. One for your featured content (only 1 item or as much you want to feature) and the second one for the rest with an offset. You can set the offset under pager options (items to skip).


Core and modules upgrade I want to upgrade my site from Drupal 6 to the latest version of Drupal 7. Currently I have version Drupal 6.21 for my site and there are other releases available 6.22 - 6.29 so I need to upgrade first to 6.29 or I can directly upgrade to Drupal 6.37 which is the latest version in Drupal 6? Also after having latest Drupal 6 version can I then upgrade directly to 7.41 or I need to do it in steps like 1-4?

Is it necessary to update core and modules first to the latest version of Drupal 6, before upgrading to Drupal 7, or can I directly upgrade to Drupal 7? I read a few articles on this, but I didn't get it.

You can't skip versions when you upgrade. For instance you cant go from 6.0 to 6.2 in one step. You also can't upgrade directly from 6.0 or 6.1 to Drupal 7. You have to have your Drupal 6 installation at the latest level.


Exclude Latest Article From View? I'm working with Views 3, and I'm trying to figure out how to best accomplish the following scenario:

On my front page, I'd like to have my articles set up as follows:

On the left, a large thumbnail is shown for the latest article. This accounts for the Title, Author, Post date, and a short summary with a comment count.

To the side, I have a block created in Views that would show the previous three articles with smaller thumbnails, author information, post date, summary, and comment counts.

What I need to know is this: How can I set up both Article views so that:

-The view on the left only shows the absolute latest article.

-The view on the right always excludes the latest article from the listing.

You have to create a view with two displays of type block. Arrange some region or panel method to display them in side by side fashion.

Create view, select its type as node, choose fields and filters according to your requirement.

For View display having latest item:

Click Pager from your view settings and define Items per page as 1 and set sort order Date created/posted as descending.

For View display having next three items:

Click Pager settings and define Items per page as 3 and set Offset as 1 and define the same date order as for the previous view display.

Thumbnails settings:

While selecting your fields particularly selecting image field (must be part of your post's content type) as thumbnail for post, choose image style. The image style are thumbnail sizes and formats. See the interface on example.com/admin/config/media/image-styles to add your custom image forma-tors so that a proper thumbnail can appear on each view display.


Allot space to individual registered user I have a drupal site with many users.

How to add space to individual registered users in drupal site? Each user can be alloted a maximum space of 500MB for all his events, messages, videos and hotlist. How could this be done?

A disc quota is one thing but also checking user-content in the db could be tricky :-). Never done something like this but here's what I would try:

use file_save_upload() to validate the upload. Part of the validation should be
the use of file_validate_size() and
file_space_used() to check the used space.

But as I said that checks only stuff inside the files table. No other content (text inside fields, cached content, thumbnails...) will be handled.


How can I prevent certain roles from editing other roles? I have user roles User Role 1, 2, and 3. I want a simple module that will make User Role 1 only be able to edit and administer users in User Role 2, and not User Role 3. Does anybody know of any module or other easy method to do that? It seems like there must have been somebody else who did something about their moderators being able to delete their admin accounts?

Please note that I'm not asking for anything about restricting the permission changing ability of roles.


Reference current user when creating a content type I am creating a new content type and one of the fields I d like to add owner.

I ve chosen reference - user as the field type
Type of item to reference = user

How do I make the default value the name of the current user?

Many Thanks

You can set default values in a hook_ENTITY_TYPE_create:

/**
 * Implements hook_ENTITY_TYPE_create() for 'node'.
 */
function mymodule_node_create(\Drupal\node\NodeInterface $node) {
  if ($node->getType() == 'my_content_type') {
    $node->field_user->target_id = \Drupal::currentUser()->id();
  }
}


Show the pager on the top and in the bottom of the page (generated by Views) I created a view and set a pager for it.
I is shown in the bottom of the page. Is there any way to show it both in the bottom and in the top of the page?

Copy views-view.tpl.php template file from theme subdirectory of Views module to your theme folder, edit it and duplicate fragment of code responsible for printing the pager:

  <?php if ($pager): ?>
    <?php print $pager; ?>
  <?php endif; ?>

to where you want it.


Programmatically get the results of a view Using the group module in D8, I have the below view with machine name: group_members_per_group

Machine Name of:

(Member account) User: Full Name is: field_user_full_name
(Member account) User: Phone Number is: field_user_phone_number

The above view has the below results:

On cron run, and while Looping through all rows of the view results, I want to get for each row the field_user_phone_number value so I can use it with other code.

So I wrote:

function my_module_cron() {

// Get and loop through the View `group_members_per_group`
//$args = [$gid];
$view = \Drupal\views\Views::getView('group_members_per_group');
//$view->setArguments($args);
$view->setDisplay('default');
$view->execute();

// Get the results of the view.
$view_result = $view->result;

// Check if the view is not empty and return results.
if (!empty($view_result)) {

// If the view returns results...
foreach ($view->result as $row) {

// Get the full name value.
$name = $row->field_user_full_name;

// check the result output for testing only.
\Drupal::messenger()->addMessage(t($name));
  }
 }
}

However, on cron run, I am receiving the below error:

  Notice: Undefined property: Drupal\views\ResultRow::$field_user_full_name in my_module_cron() (line 103 of modules\custom\my_module\my_module.module).
      my_module_cron(Object)
      call_user_func('my_module_cron', Object) (Line: 316)
      Drupal\ultimate_cron\Entity\CronJob->invokeCallback() (Line: 459)
      Drupal\ultimate_cron\Entity\CronJob->run(Object) (Line: 24)
      Drupal\ultimate_cron\Controller\JobController->runCronJob(Object)
      call_user_func_array(Array, Array) (Line: 123)
      Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber{closure}() (Line: 582)
      …
      …

Line 103 in the error is:

$name = $row->field_user_full_name;

You can not get the value of field directly from row result.
You can get it by accessing to the entity like the following:
Option1

  foreach ($view->result as $id => $result) {
    $node = $result->_entity;
    // Get the full name value.
    $name = $node->get('field_user_full_name')->value;
    // check the result output for testing only.
    \Drupal::messenger()->addMessage(t($name));
  }

Or by loop through the fields like the following:
Option2:

foreach ($view->result as $id => $row) {
      foreach ($view->field as $fid => $field) {
        if ($fid == 'field_user_full_name') {
          //Get the full name value.
          $name = $field->getValue($row);
          // check the result output for testing only.
          \Drupal::messenger()->addMessage(t($name));
        }
      }
    }


Configuration form settings I would like to create a settings page for a user which allows them to save the options of a list which is to be used in a custom form. The list is called marketing source and it is added to a form which gets submitted with plain text values to an external API.

I know in field config for select lists you can do this but I want to do it on a custom config page for that specific list.

Foe example I would have a textfield in the config that had values like this

1|google
2|magazine

Then I need to convert that into a seralised array and store with variable set.

Is there a function that does that already for the field form?

Cheers Dan

This is how I achieved what I wanted, rather than use key value pairs I just used an empty textfield and used one line for each option and then when retrieving the textfield for the form I used the following.

$raw_marketing_options = explode(PHP_EOL, variable_get('marketing_sources_sources'));

I then just used the variable directly in the form.

$form['Marketing_source__c'] = array(
  '#type' => 'select',
  '#title' => 'Marketing source',
  '#options' => $raw_marketing_options,
);

There may be a safer way to do it as I am not sure how secure variable_set() is when storing plain text but only the administrator will see the textarea anyway.

Cheers


D7 to D8 users migration processes 0 items I am working on my first migration from D7 to D8. I am trying to keep it very simple and start with users. I have created a custom module migrate_custom, created my definition at config/install/migrate.migration.d7cafe_users.yml:

id: d7cafe_users
label: User accounts
migration_tags:
  - Drupal 7
source:
  plugin: d7cafe_users
destination:
  plugin: entity:user
process:
  uid: uid
  name: name
  pass: pass
  mail: mail
  created: created
  access: access
  login: login
  status: status
  timezone: timezone
  langcode: language
  init: init

Then I have my source plugin at src/plugin/migrate/source/User.php:

<?php
/**
 * @file
 * Contains \Drupal\migrate_custom\Plugin\migrate\source\User.
 */

namespace Drupal\migrate_custom\Plugin\migrate\source;

use Drupal\migrate\Plugin\migrate\source\SqlBase;

/**
 * Extract users from Drupal 7 database.
 *
 * @MigrateSource(
 *   id = "d7cafe_users"
 * )
 */
class User extends SqlBase {

  /**
   * {@inheritdoc}
   */
  public function query() {
    return $this->select('dcf_users', 'dcf_u')
      ->fields('dcf_u', ['uid', 'status', 'created','access', 'login',    'name',
        'pass', 'mail', 'init', 'language']);
  }

  /**
   * {@inheritdoc}
   */
  public function fields() {
    $fields = [
      'uid' => $this->t('Account ID'),
      'status' => $this->t('Blocked/Allowed'),
      'created' => $this->t('Registered date'),
      'access' => $this->t('Time of last access'),
      'login' => $this->t('Time of last login'),
      'name' => $this->t('Account name (for login)'),
      'pass' => $this->t('Account password (raw)'),
      'mail' => $this->t('Account email'),
      'init' => $this->t('init'),
      'language' => $this->t('language'),
    ];

    return $fields;
  }

  /**
   * {@inheritdoc}
   */
  public function getIds() {
    return [
      'uid' => [
        'type' => 'integer',
        'alias' => 'dcf_u',
      ],
    ];
  }

}
?>

And finally I have a manifest.yml file containing:

- d7cafe_users

I run the migration with:

drush migrate-manifest manifest.yml --legacy-db-url=mysql://root:root@localhost/d7cafe

But all I get on command line is:

Running d7cafe_users                                                                                [ok]
Processed 0 items (0 created, 0 updated, 0 failed, 0 ignored) - done with 'd7cafe_users'

I don't think I'm far off, as I could see running it and importing the 4 users from the legacy db, but did a bit of fiddling on the definition file and now I can't get it back to importing records. What is wrong with my code?

Ok I tried it on a new site install and the code works and migrates users perfectly. All I can think of is that db got corrupted after running migration and rolling back a number of times.


Random image with Cycle I'm using Drupal Cycle module and list field_images items. I check 'random' button, but it is not working. I want get random image every refresh page. How can do it? field_sort_items or anyway solution?

You can do this in lots and lots of ways. This is 1 way without Views.

I did this for a homepage. I made 5 variables that hold FIDs for files uploaded using FAPI file_managed fapi element in an admin settings form.

Then using hook_page_build if I'm on the homepage I created a render array that simply calls theme_image using a random file id by loading my 5 variables into an array and using PHP's array_rand() to extract 1 random array value.

Lastly, if you can get this far -- and you have page caching turned on ... you'll only get 1 image ever and it'll never be random. For the render array inserted using hook_page_build you have to set #cache => FALSE within the render array so Drupal will not cache your images and it will be random every pageload.


Overriding variables based on url At our university we have dev/test/live versions of our sites at urls like

dev.example.foo.edu
test.example.foo.edu
live.example.foo.edu (the real live url is example.foo.edu)

There are certain Drupal site variables (values in the variables table) that need to change depending on the environment (dev, test, live) where the site is running.

The first time the site is migrated to the live environment certain site variables need to magically change from their "dev" values to their "live" values.

After that initial migration we will periodically load the live database into the dev and test sites to update their content.  When this happens I want certain site variables to change to their "dev" values.

I don't want the site builder to have to do anything.  I want the variables to simply change to the correct values.

It's okay if the site admin wants to manually override these variables.  They shouldn't have to, but there could be a need for this...

I mainly need a Drupal 7 solution--bonus if it works with Drupal 6.

Possible solutions:

Does a module exist that will do this?

I haven't found one. I've looked at

http://drupal.org/project/tadaa (incomplete)
http://drupal.org/project/context_domain (provides a url "reaction" but  context can't provide the kind of variable condition I need.  Looked at http://drupal.org/project/context_var (provides a Reaction not a Condition)).
http://drupal.org/project/strongarm (can set variables...often used with Features...)

Use hook_update_N (http://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_update_N/7)

This doesn't meet the requirement that the site builder doesn't have to do anything. They would have to copy paste a update_71234() in some install file. They would also have to remember to run update.php in various situations.

Write a custom module?

This works:

/**
 * Implementation of hook_cron().
 */
function ucb_varenv_cron() {
    global $base_url;

    //if (variable_get('ucb_varenv', FALSE) === FALSE) {
        $parts = explode('.', $base_url);
        $vars = ucb_varenv_vars();
        $p1 = str_replace('http://', '', $parts[0]);
        while (list($k, $v) = each($vars[$p1])) {
            variable_set($k, $v);
        }
        //variable_set('ucb_varenv', TRUE);
    //}

}

function ucb_varenv_vars() {
    $vars = array(
      'dev' => array(
        'cas_server' => "TEST2.example.com",
    ),
       'live' => array(
         'cas_server' => "auth.example.edu",
    ),
    );
    return $vars;
}

Hook cron seems like a clumsy approach.  The commented ucb_varenv code was from and experiment where this would run one time only at hook_boot()--but that seemed like a bad idea.

The more I think about this, I wonder if there is some way to leverage strongarm to do what I need.

Assuming I've parsed this all out correctly, you should be able to achieve what you're looking for using Rules. You'll need to install core's PHP Formatter for its integration with Rules to call variable_set() as an action, though beyond that it's pretty straightforward:

Event: When cron maintenance tasks are performed
Condition: Data comparison (Parameter: Data to compare: [site:url], Data value: http://example.foo.edu/)
Action: Execute custom PHP code (Code: variable_set('cas_server', 'auth.example.edu');)

Mind the trailing slash in the condition URLs - it's the path to the home page, not the domain name, so the slash is required.

Of course, you could bind it to whatever event you feel is most appropriate, and duplicate the same rule for your dev and test instances with the appropriate CAS servers (going this route would also mean you could export this with Features). I've tested the above reaction rule, and it seems to work on my own D7 instance (with the URL condition set accordingly):

# After cron
[dmw@seraph aqueduct]$ drush vget cas
cas_server: "auth.example.edu"

It's been a while since I've used the old Rules, though I don't see why something similar can't work for D6.


How to put db_merge into a try catch? in my code i need to use db_merge , that works well, but I'm looking for a way to show message when db_merge do not insert a record (to avoid duplication) the message would be : "you can't add this record because it exists in the db".
The best way is try/catch, but it seems to work for db_selct,db_insert,db_update but not for db_merge.

A merge query does this:

Does a record with the provided keys already exist in the database?
If no, add it with the provided field values
If yes, update the existing record with the provided field values.

Finding a duplicate isn't considered an exceptional circumstance, because that's what the query is designed to do; so no exception will be thrown.

If your aim is to support this statement:

"you can't add this record because it exists in the db"

Then a merge query might not be the right tool. db_insert() in a try...catch might make more sense in that case.

If you just want to know whether a record was added or updated, check the return value from MergeQuery::execute():

$result = $query->execute();
switch ($result) {
  case MergeQuery::STATUS_INSERT:
    // New record was added
    break;
  case MergeQuery::STATUS_UPDATE:
    // Existing record was updated
    break;
}


Node field not sanitize on render I have a form for users who want to add new content on my Drupal 8 website.
I render node field on a twig template :

{{ node_field_title.value }}

But field are not sanitized by Drupal. Is it the normal behaviour ?

--> If the title is <script>alert('XSS problem!')</script> the script will be executed.

Drupal 8 documentation says : 'The Twig theme engine now auto escapes everything by default. That means that every string printed from a Twig template (e.g. anything between {{ }}) gets automatically sanitized if no filters are used.'

It seems that there is no autoescaping, at least for Drupal 8.7.3 which the version I tested.
For example:

{{ "
Is this escaped?
" }}
{{ " "}}

These lines are not escaped by default. However:

{{ "
Is this escaped?
"|escape }}
{{ ""|escape}}

These are escaped, so better be safe than sorry and use |escape for the input you're getting from your users.


conditional visible form field How can i make the second field visible depending on the value selected in the first field ?

i have tried this but it does not work :

 $form['call-to-actions-widget']['call-to-actions-widget_select'] = [
      '#type' => 'select',
      '#title' => $this->t('widget options'),
      '#description' => $this->t('choisir un widget'),
      '#options' => [
        'none'=>$this->t('none'),
        'year_navigation' => $this->t('exposed filter :year'),
        'row_max_unset' => $this->t('more publications ( block refresh )'),
        'internal_link' => $this->t('more publications ( internal link )'),
      ],
      '#default_value' => (!empty($config['call-to-actions-widget_select'])) ? $config['call-to-actions-widget_select'] : 'none'
    ];

    $form['call-to-actions-widget']['internal_link'] = [
      '#type' => 'textfield',
      '#title' => $this->t('internal link'),
      '#description' => $this->t('de type /node/56'),
      '#default_value' => (!empty($config['internal_link'])) ? $config['internal_link'] : ''
    ];

    $form['call-to-actions-widget']['internal_link']['#states'] = [
      'visible' => [
        [
          [':input[name="call-to-actions-widget_select"]' => ['value' => 'internal_link']]
        ],
      ],
    ];

Try this

$form['call-to-actions-widget']['internal_link']['#states'] = [
  'visible' => [
    ':input[name="call-to-actions-widget_select"]' => ['value' => 'internal_link'],
  ],
];

In case when it doesn't work use another selector

':input[name="call-to-actions-widget[call-to-actions-widget_select]"]'

Or check in the browser name of the needed field. See e.g. where the name is password[pass1]


How to handle blog tags in a contrib theme? In blog or blog-like sites, taxonomy is often used for tags and categories.

In Drupal 6, node.tpl.php files could use the $taxonomy variable if they needed access to an array of unrendered taxonomy links associated with the current node. This variable was often assumed by contrib themes to contain the post tags and\or categories, and it was rendered accordingly.

In Drupal 7, $taxonomy is no longer available.

What's the alternative? How should themers handle taxonomy? In particular, how should contrib themes do it, in order to maximally preserve visual compatibility with the 6.x version?

BTW, the bit about that in the "converting themes to Drupal 7" guide is probably incorrect.

To print the the default taxonomy field separate from the other content:

<?php

    hide($content['field_tags']);
    print render($content);

    print render($content['field_tags']);

?>

This will only handle the default "tags" taxonomy. To follow discussion of an easier way to accomplish this, see this issue.


Is there a way in D7 that allows for multiple links in an image in a slider? Is there a way in Drupal 7 that allows for multiple links in an image in a slider?

Views Slideshow

Views Slideshow can be used to create a slideshow of any content (not
just images) that can appear in a View. Powered by jQuery, it is
heavily customizable: you may choose slideshow settings for each View
you create

Then add a custom field to your view and put the links there.


Fuctioning of Views Relationship? I am trying to understand the Views relationship. As I am searching the tutorials, it all described, "When you want to include data which is not directly available Views relationship lets you include that data through the common connector(joint)." Now in theory it is very straight there is a some connector which does provide the data, but How to get visualize this thing in the Views User Interface.

Let me put this way for the ease of visualization and understanding, Lets say, there is A, C and B in the following image, where C is a connector, A is data available and B is the data which is not directly available. So how can I find the A, B and C looking at Views User Interface, Hence I can Put All this three on the paper and put the logic.

Why I am putting this way, because after observing too much, I realize that why people have difficulty in understanding the views Relationship is that, what comes from  where are not so clear, hence people gets confuse which content comes from  where and how they connect each other and which one is actually not accessible. If this gets clear, the understanding of Views Relationship will be much simpler.

First understand entities, attributes, bundles and fields:

Node and User are entities. Both have a unique identifier. For Node it is nid, for User it is uid. Entities have attributes associated with them. These are the fields that you will see in the Node or Users table in the database. For instance, Node has author, data published etc, and User has name, mail etc.

Between the attributes of entities there are links, for instance: Node has an author, which is just the uid key of the User entity. In other words via a SQL join you can get from the one to the other. This is what Views do when you add a user relationship on the node view to bring in the extra information of the user table.

Bundles have fields. A bundle is an entity type with additional fields attached. For instance, Article is a bundle of entity type node. Article has all the attributes of Node, and it also has an image field. If you look at the Node table there is no image field on it. The image field is created as its own table,   field_data_field_image. In this table there is a field entity_id which contains the nid of the node it belongs to.

When you add a field that is not part of the node entity (node table) but part of the bundle (ie Article) to Views, Views will do a SQL join to get that field
into the display. Therefore Views is bringing in a relationship for you, nl. the relationship between the entity and the field.

When you install Entity reference you can add a field to an entity that will reference another entity. For instance, you add an entity reference field to an Article that can reference Basic Pages.

In the database you have now added a new field as a separate table which points to the node, of type article, as its parent container, as well as to the node of type Basic Page as the referenced node. It looks like this:

To add it to Views you need to include the relationship manually as an Entity Reference. There will be two possibilities:

Entity Reference: Referenced Entity - A bridge to the Content entity
that is referenced via field_reference
Entity Reference: Referencing entity - A bridge to the Content entity
that is referencing Content via field_reference

which is just the direction of the relationship. If I have the article in my View and I want to include the Basic Page, then it will be Referenced Entity. If I have the Basic Page and I want the Article, then it will be Referencing entity.

Views will bring in this relationship via two joins, the first to bring in the field belonging to the Article, and the second to bring in the Basic Page node that is pointed to by the entity reference field (the order depending on the direction)

NOTE that you can bring in even more relationships in a chain-like fashion. You may have a node whose author user has an entity reference to a profile type node that has a Taxonomy Tag etc.


Get username in custom user twig template I have a twig template for the compact display of a user where I am able to output the defined content fields. Is there a way to output the username of that user?

The display name is not a field you can configure in {{ content }}. You can get it directly from the user entity:

{{ user.displayname }}

Reference for the php method: AccountInterface::getDisplayName


CCK nodereference is returning empty nid when no node is selected For testing purposes I've installed CCK module on vanila drupal,
created new node type and attached CCK nodereference to it.

After creating new node, I've notice in node.tpl.php the following structure:

    [field_my_node_reference] => Array
    (
        [0] => Array
            (
                [nid] =>
                [safe] => Array
                    (
                    )

                [view] =>
            )

    )

As you can probably notice, there is a key $node['field_my_node_reference][0]['nid'] that is null.

In order for me to fully understand CCK - why CCK gives empty keys when nothing is selected?

Any answer is appreciated !

You are looking at a node in CCK's post build_content() phase.  When you add a node reference field to a node, CCK adds the 'nid' portion to the database, and when you build or display the content, it creates the 'safe' and 'view' portions.  If you were doing this manually, you could do something like:

$foo=node_load(27);

and if $foo had a nodereference, $foo would contain

[field_my_node_reference] => Array
(
    [0] => Array
        (
           [nid] =>
        )
)

eg, you could print 'my nid is ' . $foo->field_my_node_reference[0]['nid'];'

and it would print out my nid is [blank] if unset, or my nid is 593 if set.  Now,
when CCK comes in and gets all fancy, it creates the safe and view pieces, and these are set up by those widgets you select in the display fields portion of CCK before getting to node.tpl.  (You can do this yourself by calling $foo=build_content($foo); in a module and looking at $foo again.)  Anyways, CCK works all of that up into the $content variable it aggregates things together into for your node.tpl as well as in the $node variable it has in there if you yourself want to get fancier, eg, print 'this is a link to my node: ' . $node->field_my_node_reference[0]['view'] would normally print out 'this is a link to my node:' followed by the title of the node linked to it.  All changeable via those display options/widgets.

But as to why it has empty keys, they are just part of the data structure created to ensure everything up and down the workflow works together as well as it does, eg, the safe and view portions are blanks where a link would probably go if the field was set, so that makes sense.  And a NULL is in nid since it hasn't been set.

But...just plop in some content and you will see everything fill up all nice :)


How do I modify default labels of the location module? How can I modify the field names of the location widget that I use to collect addresses and phone numbers. I am using Drupal 7 with the Location Module: https://drupal.org/project/location

Below a screenshot of the fields I would like to rename ('Street Location' to 'Address Line 1' as an example).

Thanks!

https://www.drupal.org/node/381458#comment-6699162 worked for me

/**
 * Implements hook_location_element_alter().
 */
function update_personal_info_location_element_alter(&$element) {
  $element['additional']['#title'] = "Address line 2";
}


How to see override functions and template files in use for any part of the drupal site? I remember there is a module for displaying which core or theme functions or template files are used in order to create any part of a drupal site. Has anyone know what is the name of this module?

I need this module in site building.
Thanks in advance.

gokhan

You are thinking about the Theme Developer module.  When you install and enable, it you can click on just about any properly rendered element and see

Preprocess and process function candidates
Theme function candidates
Template file suggestions

Just keep in mind that it can interfere with some themes, and doesn't work well in some versions of IE.


How can I add two 'add to cart' ubercart buttons in a product page I would like to have two 'add to cart' buttons on my ubercart drupal site.
I've set up two views, but only one button will show at a time.
Why is this?
You can see it on https://www.thepetwiki.com/mg-testsite.com/ubercart/painting/please
There should be an 'add to cart' button next to both 'BUY: $2,400'

I would recommend creating a view:block that displays the product's price and an add to cart button, you can then duplicate the view:block and have in the block admin page, add the two new view blocks to the regions you would like them displayed in.


Can Drupal 8-compatible Drush be installed in Windows? Has anyone had any luck upgrading from Drush 6 to 7 on a windows machine?  I feel like I'm beating my head against a wall trying to get this done.  I want/need to use Omega 4 and I need Drush 7 to do so.  Also, if I ever want to update my websites to Drupal 8, I will need Drush 7.  Any direction/advice would be great!

Edit by @othermachines: Drush 8 is now recommended for Drupal 8 development.

Although it's a year and a half since this question was posted, as we get closer to a production release of Drupal 8 I can see it getting a few hits. So here's my answer...
Yes, it certainly can!
Although as of this writing it appears Drush 8.x (in particular the latest dev on branch master) is the recommended version for Drupal 8 development.
See: Drush Installation/Upgrading instructions
I'm running WampServer 2.5 (PHP 5.6.13RC1, MySQL 5.6.17, Apache 2.4.9) on Windows 8.1 and use Git Bash shell from the Git for Windows installation. I have Composer 1.0-dev set up globally.
I was able to upgrade successfully1  following the first installation method on this page, Composer - One Drush for all Projects.
Steps

Install from the command line:
$ composer global require drush/drush:dev-master

Modify the path to Drush in your system environment variables (here's a helper). On my system, Drush was installed in c:\Users\Username\AppData\Roaming\Composer\vendor\drush\drush.

Reboot Windows

Troubleshooting: Check loaded php.ini
The only problem that cropped up post-install was that the PHP settings being loaded by the CLI (and accessed by Drush) are out of sync with those loaded by WampServer. I found I had to copy my PHP settings from phpForApache.ini to php.ini in the currently loaded PHP version folder in c:/wamp/bin.2
Is Drush telling you you don't have X extension enabled, when you know you do? Run drush core-status to check on the path to php.ini on your own system.
A note about the Windows zip package
I had previously used the Windows zip package to install version 6.x. As of this writing there is a package available for version 7 - scroll down to the bottom of the installation page - but not 8 (unsurprisingly since AFAIK it is heavily under development). I wonder if having previously gone through this process somehow eased this upgrade by setting up some necessary extras - probably not;  I just don't know. Maybe I just become a big, fat skeptic when things work too easily on Windows.3
See also:
Installing Drush on Windows (Drupal.org)
How to Upgrade Drush to work with Drupal 8 (Manjit Singh)

1 Because this is Windows, it should be noted that I've only installed in the last couple of days, and have so far only used it for basic tasks such as creating databases, installing a site, clearing the cache tables. No problems so far, but that doesn't mean they won't crop up.
2
I don't recall having to copy the PHP settings over before, and this is going to be a bit sticky when I alter these settings or switch between PHP versions, but so far I haven't found a way around this.
3 The author above (Manjit Singh) seemed to have a similarly pain-free upgrade, which makes me less skeptical. :)


Child menu items not displayed in drupal I've a sub-menu like this:

I'm trying to build a custom theme, I just copied which contains following code:

<?php if ($main_menu || $secondary_menu): ?>

    <?php print theme('links__system_main_menu', array('links' => $main_menu, 'attributes' => array('id' => 'main-menu', 'class' => array('links', 'inline', 'clearfix')), 'heading' => t('Main menu'))); ?>
    <?php print theme('links__system_secondary_menu', array('links' => $secondary_menu, 'attributes' => array('id' => 'secondary-menu', 'class' => array('links', 'inline', 'clearfix')), 'heading' => t('Secondary menu'))); ?>

<?php endif; ?>

This is how its being displayed: Note that not even the HTML for child menu items are generated.

Yes, I've Show as expanded option checked for "Publications".

PS:
Why does drupal make even such simple things difficult. No wonder, its losing ground to wordpress.

Try this:

<?php
$menu_name = variable_get('menu_main_links_source', 'main-menu');
$tree = menu_tree($menu_name);
print drupal_render($tree);
?>

Also Drupal doesn't make things hard, you just don't understand it yet.

It is just a tool suited to specific tasks. If you just want to make a blog then don't use Drupal, just use Wordpress.

If however you want a very powerful CMF (Content management framework, not system) to create complex systems with lots of inter-related entities then continue to learn Drupal - I think it's the best tool for the job.


Alternative Top Menu bar for logged in users only via their Role I want to have an alternative top menu bar for certain Roles when they are logged in. For example, 'Teachers' have one top menu bar, 'Students' have another type.

For now, I want to do this using Rules, is this a good approach or is there an easier way. Simple functionality is the key here so at this time I'm not looking to hack tpl.php files as I just want to get something working for demo purposes.

I'm using Bootstrap and happy to stay that way for the future.

Any suggestions & advice on the above, most welcome. Thanks in advance.

When you create a menu, a block should be created at the same time (https://drupal.org/taxonomy/term/32478). Go to Admin, Structures, Blocks and place one of those menus in the area you want it to appear - under Role restriction at the bottom of the block configuration, you can decide who has access to that specific menu. Repeat for each menu - this way, the menu appears in the same spot, but a different menu will appear for different roles.


Dependency injection in Drupal queueworker plugin I am creating a queueworker plugin, and would need the QueryFactory and EntityManagerInterface.
I set these as 'use' statements, and added them in my parameters in __construct(),
but i get following error:

  TypeError: Argument 1 passed to Drupal\custom_example\Plugin\QueueWorker\SalesQueueProcessor::__construct() must be an instance of Drupal\Core\Entity\Query\QueryFactory, array given

My QueueWorker plugin:

namespace Drupal\simplified_bookkeeping\Plugin\QueueWorker;

use Drupal\Core\Queue\QueueWorkerBase;
use Drupal\custom_example\Entity\BookingEntity;
use Drupal\Core\Entity\Query\QueryFactory;
use Drupal\Core\Entity\EntityManagerInterface;

/**
 * Processes Sales Tasks.
 *
 * @QueueWorker(
 *   id = "sales_queue_processor",
 *   title = @Translation("Generate sales from bank/cash statements in queue"),
 *   cron = {"time" = 10}
 * )
 */
class SalesQueueProcessor extends QueueWorkerBase {

  public function __construct(QueryFactory $entity_query, EntityManagerInterface $entityManager) {
    $this->entity_query = $entity_query;
    $this->entityManager = $entityManager;
  }

  /**
   * {@inheritdoc}
   */
  public function processItem($bid) {}
}

What am I doing wrong?

Long story short, your plugin needs to implement ContainerFactoryPluginInterface for services to be injected.

Something like this:

namespace Drupal\simplified_bookkeeping\Plugin\QueueWorker;

use Drupal\Core\Queue\QueueWorkerBase;
use Drupal\custom_example\Entity\BookingEntity;
use Drupal\Core\Entity\Query\QueryFactory;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Processes Sales Tasks.
 *
 * @QueueWorker(
 *   id = "sales_queue_processor",
 *   title = @Translation("Generate sales from bank/cash statements in queue"),
 *   cron = {"time" = 10}
 * )
 */
class SalesQueueProcessor extends QueueWorkerBase implements ContainerFactoryPluginInterface {

  public function __construct(array $configuration, $plugin_id, $plugin_definition, QueryFactory $entity_query, EntityTypeManagerInterface $entityTypeManager) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);

    $this->entity_query = $entity_query;
    $this->entityTypeManager = $entityTypeManager;
  }

  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('entity.query'),
      $container->get('entity_type.manager')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function processItem($bid) {}
}

As an aside, the entity manager service is deprecated; the entity type manager should be used instead. You also don't strictly need to inject the entity query service as you can get an instance from the manager, e.g.:

$query = $this->entityTypeManager->getStorage('node')->getQuery();


How to use entity autocomplete for "user" target_type with specific roles? I have created a form field with user autocomplete as below.

$form['user_list'] = [
      '#title' => ('Select User'),
      '#type' => 'entity_autocomplete',
      '#target_type' => 'user',
      '#required' => TRUE,
      '#selection_settings' => [
        'include_anonymous' => FALSE,
        'roles' => ['sales'],
      ],
    ];

I used "#selection_settings" with roles specific, but this is not working.
I want to filter user with "sales" only.

The selection settings array is passed to the plugin options,
 which in this case is Drupal\user\Plugin\EntityReferenceSelection\UserSelection.

In that class, you can see that the relevant array key is $options['filter']['role'], which is an array.

Therefore, the correct code here is:

$form['user_list'] = [
  '#title' => ('Select User'),
  '#type' => 'entity_autocomplete',
  '#target_type' => 'user',
  '#required' => TRUE,
  '#selection_settings' => [
    'include_anonymous' => FALSE,
    'filter' => [
      'role' => ['sales'],
    ],
  ],
];


Customizing tableheader.js Sticky table Header As I am having a custom "position:fixed" top navigation bar in my admin pages, the sticky table header are being hidden behind it when I scroll-up.

I went through tableheader.js and saw there is a Drupal.settings.tableHeaderOffset that helps change the "top" property, but I don't know where I should override it. Possible to do it in my template.php?

Also, I would like to change the position that triggers the sticky header to change visibility from hidden to visible...

  // Track horizontal positioning relative to the viewport and set visibility.
  var hScroll = document.documentElement.scrollLeft || document.body.scrollLeft;
  var vOffset = (document.documentElement.scrollTop || document.body.scrollTop) - this.vPosition;
  this.stickyVisible = vOffset > 0 && vOffset < this.vLength;
  this.stickyTable.css({ left: (-hScroll + this.hPosition) + 'px', visibility: this.stickyVisible ? 'visible' : 'hidden' });

You can override tableheader.js using hook_js_alter(&js) {}, just replace path of file, like in example (details here).

Also you can override Drupal.settings.tableHeaderOffset value.
Thus, in template.php place something like this:

drupal_add_js('themeTableHeaderOffset() { return 200; }', 'inline');
drupal_add_js(array('tableHeaderOffset' => 'themeTableHeaderOffset'), 'setting');


The Login block has vanished I haven't changed it in /admin/structure/blocks and it is still there.

All that I can think that I installed a few modules to try them out and then disabled them and maybe that caused it.

In any case, my users can't log in and I am in big trouble.

How to go about debugging the problem?  Thanks.

Update: I am not logged in (I see "Log in or register to post comments"). Even when I load /user/logout the login block is not there (not in the HTML)

The "recent log messages" shows nothing out of the way.

The modules you were experimenting with and then disabled, did you go through the uninstall process?
Also, flush you caches.

I hope that helps.


What is the maximum number of elements allowed in a form? I have googled and binged and yahooed this question but can't seem to find an answer. I was working on a form that included over 800 fields but the form's submit function would never execute.  After I pared the form down, the submit function ran.  So now I'm curious if there's an actual built in maximum number of elements.

I think, the issue is related to Server configuration, not with Drupal.

There is max_input_vars variable in php.ini which define the maximum number of variable form elements that can be submitted to a single page.

  The “max_input_vars” setting in the php.ini file is a relatively new
  option starting last year from PHP 5.3.9. It allows you to control the
  maximum number of form elements on a page. Some webpages have a large
  amount of forms/fields for administrative or page configuration
  purposes. In those cases, we need to increase the number of this value
  in order to properly view those pages.

There is also post_max_size variable in php.ini.

  post_max_size sets max size of post data allowed. This setting also affects file
  upload. To upload large files, this value must be larger than
  upload_max_filesize. If memory limit is enabled by your configure
  script, memory_limit also affects file uploading. Generally speaking,
  memory_limit should be larger than post_max_size. If the size of post data
  is greater than post_max_size, the $_POST and $_FILES superglobals are empty.

You can check the this for more details.


Post AJAX JSON with session id Using Drupal Services I am able to log in but each time I post a node it posts as anonymous. I get the session id and session name upon login but can´t pass it along with a POST no matter what i try.

I have tried including it in the json string, as a header and within the URL - without any result. I'm testing using the Chrome Postman as REST client.

What am I doing wrong?

Thank you for any help!

var session_id = $('#session_id').text();
$.ajax({
  type: "POST",
  url: 'http://www.website.com/active_services/node?sessid='+session_id,
  data: JSON.stringify(noden),
  headers : {
    "Authorization" : session_id,
    "sessid" : session_id,
    "sessionid" : session_id,
  },
  beforeSend: function (req){
    req.setRequestHeader("Authorization",session_id);
    req.setRequestHeader("sessid",session_id);
    req.setRequestHeader("sessionid",session_id);
    req.setRequestHeader("Content-Type", "application/json");
  },
  dataType: 'json',
  contentType: 'application/json',
  success: function(data){
    console.log(data);
 }

I am using POSTMAN to test my REST calls to server.

When i try http://mysite.com/api/endpoint/users/login.json

with parametes

Content-Type - application/json
username - A valid username on site
password - users password

I get a json looks like this

{
    "sessid": "6nRaPdlYfV4mDt0cgUHfGwNmWJZNvUfKM618DYY4unc",
    "session_name": "SESS4356595e5cb4b5df8f18058cfbd8d13a",
    "user": {
        "uid": "144",

From that i suspect you should pass sessid and session_name to get it work.

Try it and let me know whether its working if not we find some other solution which works :)


Code to take quiz again on the next day after user is failed In drupal 6, I had a requirement to enable the users to take the quiz on the next day if they failed and from somewhere I got the following code to make that work. They added one more variables, time_end and used strtotime('today')

But now I upgraded to Drupal 7 and code for the same a little bit changed and I couldn't make that work. I am looking forward to getting help to achieve it. I am using quiz quiz-7.x-4.0-rc1

Drupal 6 Original lines

// Check to see if this user is allowed to take the quiz again:
  if ($quiz->takes > 0) {
//   $query = "SELECT COUNT(*) AS takes FROM {quiz_node_results} WHERE uid = %d AND nid = %d";
//   $taken = db_result(db_query($query, $user->uid, $quiz->nid));

Drupal 6 Changed lines (only first two lines. after that code remains the same except drupal_set_message.)

     $query = "SELECT COUNT(*) AS takes FROM {quiz_node_results} WHERE uid = %d AND nid = %d AND time_end > %d";
        $taken = db_result(db_query($query, $user->uid, $quiz->nid, strtotime('today')));

    $allowed_times = format_plural($quiz->takes, '1 time', '@count times');
    $taken_times   = format_plural($taken, '1 time', '@count times');

Drupal 7 Original lines.

  // Check to see if this user is allowed to take the quiz again:
  if ($quiz->takes > 0) {
    $taken = db_query("SELECT COUNT(*) AS takes FROM {quiz_node_results} WHERE uid = :uid AND nid = :nid", array(':uid' => $user->uid, ':nid' => $quiz->nid))->fetchField();
    $allowed_times = format_plural($quiz->takes, '1 time', '@count times');
    $taken_times   = format_plural($taken, '1 time', '@count times');

Full drupal 7 code is available here DrupalContrib

I could find a solution. It's actually pretty simple. But I don't know whether this is the right way doing it.
Just change $taken like below. Then anybody can retake the test on the next day. Thanks to all for the support.

$taken = db_query("SELECT COUNT(*) AS takes FROM {quiz_node_results} WHERE uid = :uid AND nid = :nid AND time_end > :time_end", array(':uid' => $user->uid, ':nid' => $quiz->nid, ':time_end' => strtotime('today')))->fetchField();


Comment with email or social networks I am developing my personal site in drupal 7. Actually i am searching for a module which allows anonymous users commenting with their email or any social n/w like twitter,facebook or google+. Is there any good module available or is drupal 7 supports  anonymous users commenting with their email address ?

You can achieve that using the OpenID Selector module

This module integrates Javascript OpenID Selector with Drupal's OpenID client.
This module substitutes Drupal's default OpenID form with Javascript OpenID Selector widget, so users do not even need to know what OpenID URL is.


There is data for the field - On uninstalling module Given I have a module that defines a new field on an entity. How can I delete that data on uninstalling? There is a requirement:

  There is data for the field X on entity type Y

which means I cannot delete the data on the hook_uninstall since it cannot be called.

This is a known limitation to Drupals Core and this finally gets resolved for Drupal 8.5.x, see this issue:
https://www.drupal.org/project/drupal/issues/2282119

But for versions earlier there is an option to workaround this, by creating a form that handles the cleaning of added data to make the uninstall validation pass. This is a UI solution but you still need to add a not somewhere that users know how to find the form. See how the Flag module handled it:
https://www.drupal.org/node/2409673

There are other options like creating a drush command, but what you basically need to do is to clean the added data from the database to make the validation for uninstall pass and allow users to uninstall the module.


Can Drush 9 be used with this core version? I have a Drupal 7 site that was not built with Composer. I have been using Drush 7 with it, but about a week ago, drush wd-show --tail stopped working, I'm not getting any output. I installed Drush 9, but I'm having difficulty configuring it.

I created an XML file, per the example., Instructions say to put aliases in $PROJECT/drush/sites/self.site.yml but I don't have a project root with a composer.json – can I get this to work without using Composer to build my site? Or is Drush 9 depending on the Drupal site using Composer?

I'm running the local version of the site in MAMP on my Mac. I created sites/drush/sites/self.site.yml – it contains:

local:
  root: /Users/pglatz/dev/wdocs/wdocs-code/www
  uri: 'https://www.whiskerdocs-local-qa.pglatz.com/'

The command I'm using is:

$ drush9 @local --alias-path=/Users/pglatz/dev/wdocs/wdocs-code/www/sites/drush/sites --root=/Users/pglatz/dev/wdocs/wdocs-code/www

When I run it, I get the error:

  Command wd-show was not found. Pass --root or a @siteAlias in order to run Drupal-specific commands.

But I am passing --root and a site alias. Likely a dumb syntax error on my part, but I can't figure it out. What am I doing wrong? And how can I get Drush to be working properly again?

No. Drupal 7 requires Drush 8.

See https://www.drush.org/latest/install/#drupal-compatibility

Furthermore, Drush 9 can't be installed globally.

See https://www.drush.org/latest/install/


How an user set his own password while creating account When a user creates an account he is only asked for a username and email.

I also want him to set his own password when he creates an account. how can i manage that as admin?

Thank you!

Maybe this module is for you: User registration password


How to display the entity ID next to the title of an ECK entity I have an entity template that starts like this:

<div class="<?php print $classes; ?>">

<?php print $title; ?>

But now I want to display the entity ID and the UUID next to the title.
<?php print $entity_id; ?> or <?php print $entity_id; ?> display nothing.

Do I need to preprocess something?

$title is an available variable in that entity template. So, yes if you need to pass entity ID and UUID then you will have to pass them via preprocess hook.


Safe way to authentication users with REST I can authentication and login user with below code in Jquery

$.ajax({
    url : "http://domain.com/user/login",
    type : 'post',
    data : 'form_id=user_login_form&name=' + encodeURIComponent("user") + '&pass=' + encodeURIComponent("password"),
    dataType : 'json',
    error : function(data) {
            //error code
    },
    success : function(data) {
      console.log(data);
        //success code
    }
});

But is seems this is not safe mode, and I think maybe someone can attack  bruteforce to find users password.I want to know is this method safe(I don't think so) and what is solution for make this safe against brute-force login attack.

This Ajax request don't return any Json output,It seems try to login and if authorized  then get /user/uid

Note "User login REST format" is similar, but it's not duplicate, and it doesn't have an accepted answer.

Probably because you're a header, should be like this:

{
    "_links": {
        "type": {
            "href": "https://yoursite.com/rest/type/node/article"
    }
  },
  "title": [{"value": "test title"}],
  "body": [{"value": "test body"}]
}


In Views, what is the difference between "Show Fields" and "Show Content" under Format? In the Format section you have the option Show: Fields. That is the one I usually use. However, you also have Show:content. What is Show:content and how is it different? When would I want to use it instead of Show:fields?

Show: content will render the content as it is normally displayed if you access it at its URL.  For example, selecting Show: content for a view displaying users will display each user's full profile.  Selecting it for a view displaying nodes will render each node in its entirety.

Show: fields, by contrast, allows you to select (limit) which fields to display.


Add a class to all title text fields in all content add forms I'm using Twitter Bootstrap and I want to expand the length of all the title fields in the content forms by adding 'span6' to the class attribute for the title field's input element.

I've added the following function to my template.php file:

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

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

  // Render the items.
  $output .= '
';
  foreach ($variables['items'] as $delta => $item) {
    $classes = 'field-item ' . ($delta % 2 ? 'odd' : 'even');
    $output .= '
' . drupal_render($item) . '
';
  }
  $output .= '
';

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

  return $output;
}

Right now all I've done to it is change the name of the function according to the functions preceding comment.  I'm not sure what I need to do, because I need to add the class to the input element directly, and not its parent div element.

Using JavaScript (including jQuery) is not an option.

TL;DR

How does one add a class to a specific field's input element?

The content title is a property rather than a field, so overriding theme_field() isn't the way to do this.

Instead you might want to use a hook_form_FORM_ID_alter() (which can also be used in your theme's template.php file):

function ccom_form_node_form_alter(&$form, &$form_state, $form_id) {
  $form['title']['#attributes']['class'][] = 'span6';
}


The 'Drupal' way to query the database I'm using the method below to query the database within a custom module but it doesn't seem to be the 'Drupal' way of doing things. Is there a better way?

$sql = "SELECT field1, field2 FROM {tablename} WHERE field3 = $var1 AND field4 = $var2";
$result = db_query($sql);
$num = $result->rowCount();
if ($num != null) {
  foreach($result as $line) {
    // Do something
  }
}

welcome.

The only tweak needed I see is:

$sql = "SELECT field1, field2 FROM {tablename} WHERE field3 = :var1 AND field4 = :var2";
$result = db_query($sql, array(':var1' => $var1, ':var2' => $var2));

The method you've written your query allows for SQL-Injection -- using placeholders in the SQL helps to defend against this.

I invite you to read up on the Database API documentation, specifically queries:

Result Sets
Dynamic Queries
Static Queries


Including Google Maps in my custom module So, to set the stage, I'm working on a small database project that will handle a company's order handling.
So far, I have a fully working client part where users can get a full list of all the clients and can edit/delete/add clients at will.

The next think that I'm trying to implement, is that each client will also have it's own details page, where more details of the client will be displayed. It should display all the data in the database regarding the specific client, but it should also incorporate a Google Map based on the client's address.

I've looked around and found a dozen of Google Maps modules, but they only seem to work with article types that have fields that contain an address.

My current line of thinking was just to render the detail page with a render array after getting all the client's info from my database.

1) Is this the correct way of doing it? If not, how should I approach this?

2) If yes, how can I then implement a google map?

EDIT:

The thing is, I'm not exactly working with a content type at the moment. I'm using hook_menu for all my pages, and an example callback function for displaying a full list of all the clients is

function expoline_clients_overview() {
    // Table settings.
  $attributes['datatable_options'] = array(
    'bFilter'   => TRUE,
    'bInfo'     => TRUE,
  );
  // Define table columns
  $header = array(
    array(
      'data' => t('Column 1'),
      'datatable_options' => array(
        'bSortable' => TRUE,
        'bSearchable' => TRUE,
      ),
    ),
    array(
      'data' => t('Column 2'),
      'datatable_options' => array(
        'bSortable' => TRUE,
        'bSearchable' => TRUE,
      ),
    ),
    array(
      'data' => t('Column 2'),
      'datatable_options' => array(
        'bSortable' => TRUE,
        'bSearchable' => FALSE,
      ),
    ),
    array(
      'data' => t('Column 2'),
      'datatable_options' => array(
        'bSortable' => TRUE,
        'bSearchable' => TRUE,
      ),
    ),
    array(
      'data' => t('Column 2'),
      'datatable_options' => array(
        'bSortable' => TRUE,
        'bSearchable' => TRUE,
      ),
    ),
    array(
      'data' => t('Column 2'),
      'datatable_options' => array(
        'bSortable' => TRUE,
        'bSearchable' => TRUE,
      ),
    ),
    array(
      'data' => t('Column 2'),
      'datatable_options' => array(
        'bSortable' => TRUE,
        'bSearchable' => TRUE,
      ),
    ),
  );

  /*
   * Fetch all clients from the database and insert them into the array of rows
   * that will be rendered in the table
  */
  $query = db_query("SELECT * FROM {expoline_clients}");
  foreach ($query as $currentclient) {
    unset($client);
    $client[] = $currentclient->name;
    $client[] = $currentclient->street;
    $client[] = $currentclient->street_number;
    $client[] = $currentclient->postal_code;
    $client[] = $currentclient->city;
    $client[] = 'cid . '/edit"><button type="button">Edit</button>';
    $client[] = 'cid . '/delete"><button type="button">Delete</button>';
    $clients[] = $client;
  }
  $rows = $clients;

  // Render the Datatable
  $variables = array(
    'attributes' => $attributes,
    'header' => $header,
    'rows' => $rows,
  );
  $output = theme('datatable', $variables);

  return $output . '<button type="button">' . t('Klant toevoegen') . '</button>';
}

Thanks a bunch!

I didn't dig into the exact methods you are using, but if all you want to do is embed a very simple map graphic you could use something like this:

if (isset($currentclient->street_number) && isset($currentclient->street)) {
      $address_var = $currentclient->street_number . " " . $currentclient->street;
      if (isset($currentclient->city)) $address_var .= "+".$currentclient->city;
      if (isset($currentclient->state)) $address_var .= "+".$currentclient->state;
      if (isset($currentclient->postal_code)) $address_var .= "+".$currentclient->postal_code;
      $address_var = str_replace(' ', '+', $address_var);
      $output = "";
    }

Or, I suppose a render array would simply change the $output= line above to be something like this:

$output =  array(
    'map' => array(
      '#type' => 'markup',
      '#markup' => '',
    ),
);


How toView attached files from a og my first question here.
Drupal 7
OG 7.2

I'm trying to make a view to display a list of attached files to a group.
I've made a custom field for the attachments in the content type for posts and in there comments.

I've achieve to display the view, both for private files and public.
Ok ! I was very happy after hours of pain.

The problem is that the view is pulling all the files from all groups.
What I want it's to see the group files.
How do I get the relation between the file and the group ?
 Any help would be appreciated.

Bellow it's a image of the view, I hope you can understand it. (field_anexos_de_grupo) it's the media field.
Note: I'm new to drupal and I'm not a php expert.

Thanks

You need to also to add the relation between the file to the current viewed groups with the OG membership relationship. You can have a look how this done in a view called "OG content"


How to set an error message with Javascript? I was wondering how to set an error message from js to Drupal ?
something like

<?php
    drupal_set_message('mplampla);
?>

but in Drupal object in js

jQuery(document).ready (function(){
    Drupal.setErrorMessage('mplampla');
})

is this even possible?

The drupal_set_message() works by storing the messages into a session and displays when the page is reloaded.

If you want to show an error message through javascript, include js in your module (if working with some module).

You could simply append an error message on some event

    jQuery(document).ready (function(){
    jQuery(".error-message").append('
Error message to be displayed
');
});

It will simply display an error message. You can apply further Js code as desired output.