Drupal Views - How to return information about a view that is being rendered - drupal

I'm having trouble dealing with hooks for the Views module in Drupal. What I'm trying to do is determine which view is being rendered so that I can identify it and make changes to it. IOW, I don't know ahead of time which view I'm working on.
In the code below, I've replaced my actual module name with "MODULENAME".
In my .module file I have included a file MODULENAME.views.inc file with the following:
include_once ( dirname(__FILE__) . '/MODULENAME.views.inc');
In the .views.inc file, I have a MODULENAME_views_api function like this:
function MODULENAME_views_api() {
return array('api' => 2, 'path'=> drupal_get_path('module', 'MODULENAME'),
);
}
Those seem to work just fine. So, now I try to get down to business with an actual hook...
function MODULENAME_views_pre_render(&$view) {
$get_view_info = $view->name;
echo $get_view_info;
}
MODULENAME_views_pre_render();
The problem is this throws an error, "Missing argument 1 for MODULENAME_views_pre_render().
So, obviously it expects me to pass in an identifier of some sort to tell it which view I want. But that's the whole point of this function is to determine which view is being rendered. If I knew the answer to that, then I wouldn't need to call the function in the first place.
Am I missing something obvious? Is there a function call that I can use to return this identifier?

You hook into things by implementing hooks, so this part of your code is ok:
<?php
function MODULENAME_views_pre_render(&$view) {
$get_view_info = $view->name;
echo $get_view_info;
}
But this:
<?php
MODULENAME_views_pre_render();
Why? You're not generating a view, Views is. It's not your job to invoke the hook. You just implement it.
So, you need to make changes to the view? you do it right there:
<?php
function MODULENAME_views_pre_render(&$view) {
if ($view->name == 'TheViewIWantToModify') {
// Make some changes to the $view
}
}
And that's it.
Also, note that depending on the type of modifications you want to do, you might want to implement another hook instead of hook_views_pre_render(). Take a look at the docs/docs.php file that comes with Views (version 6.x-2.12 at least, I don't know which version you have, and BTW you should indicate this) and starting on like 538 you'll see a few hook_views_pre_ and hook_views_post_ type of hooks (that is, their descriptions, for you to know what each of them are good for), and then you can decide which one to implement in your module.

Related

Drupal 6 preprocess function for custom template

I have a custom template file I'm using for a page.
Say the page is www.mydomain.com/hello-world
The content of this page is taken from a template file called hello-world.tpl.php
Now I need to have a variable prepared in advance for that page, so I took a look at how core modules achieve this and tried to implement in the same way, only the variables are always null..
for hello-world.tpl.php I created in my module file a function called:
function template_preprocess_hello_world(&$variables) {
$variables['test'] = "test";
}
As I said $test doesn't get any value on www.mydomain.com/hello-world (I receive NULL when var dumping it)
I spent an hour or so double checking that I don't have any typos or anything like that.
Is what I'm doing worng??
Try renaming the function to mymodulename_preprocess_hello_world(&$variables). Don't forget to clear the cache as well.

how to change form action url for contact form 7?

I'm using Contact Form 7 in a wordpress site with multiple forms.
I need to direct one form to a different form action url than the others.
I found the reply below for a previous thread but I'm not sure how to go about it.
Can someone specify what exact code needs to be included in "additional settings"
and what the code in functions.php would look like?
Thanks for your help!
reply from diff. thread, which I don't completely understand...
*Yes, you have to change the "action" attribute in the form using this Filter Hook wpcf7_form_action_url. (what would be the code?) You could add the hook into your theme's functions.php and then just process the form data in your ASP page.(code?) *
Since you're not familiar with PHP code at all, I'll give you a bit of a crash course in coding within the Wordpress API.
First off, you need to know the difference between functions and variables. A variable is a single entity that is meant to represent an arbitrary value. The value can be anything. A number, somebody's name, or complex data.
A function is something that executes a series of actions to either send back - or return - a variable, or alter a given variable.
<?php
$a = 1; //Number
$b = 'b'; //String *note the quotes around it*
$c = my_function(); //Call to a function called my_function
echo $a; //1
echo $b; //b
echo $c; //oh, hello
function my_function()
{
return 'oh, hello';
}
?>
Wordpress utilizes its own action and filter system loosely based on the Event-Driven Programming style.
What this means is that Wordpress is "listening" for a certain event to happen, and when it does, it executes a function attached to that event (also known as a callback). These are the "Actions" and "Filters". So what's the difference?
Actions are functions that do stuff
Filters are functions that return stuff
So how does this all fit in to your problem?
Contact Form 7 has its own filter that returns the URL of where information is to be sent by its forms.
So lets look at the basics of a Filter Hook
add_filter('hook_name', 'your_filter');
add_filter is the function that tells Wordpress it needs to listen
for a particular event.
'hook_name' is the event Wordpress is listening for.
'your_filter' is the function - or callback - that is called when the 'hook_name' event is fired.
The link to the previous thread states that the hook name you need to be using is 'wpcf7_form_action_url'. That means that all you have to do is make a call to add_filter, set the 'hook_name' to 'wpcf7_form_action_url', and then set 'your_filter' to the name of the function you'll be setting up as your callback.
Once that's done, you just need to define a function with a name that matches whatever you put in place of 'your_filter', and just make sure that it returns a URL to modify the form action.
Now here comes the problem: This is going to alter ALL of your forms. But first thing's first: See if you can get some working code going on your own. Just write your code in functions.php and let us know how it turns out.
UPDATE:
The fact that you were able to get it so quickly is wonderful, and shows the amount of research effort you're putting into this.
Put all of this in functions.php
add_filter('wpcf7_form_action_url', 'wpcf7_custom_form_action_url');
function wpcf7_custom_form_action_url()
{
return 'wheretopost.asp';
}
As mentioned before, that will affect ALL of your forms. If this is only supposed to affect a form on a given page, you can do something like this:
add_filter('wpcf7_form_action_url', 'wpcf7_custom_form_action_url');
function wpcf7_custom_form_action_url($url)
{
global $post;
$id_to_change = 1;
if($post->ID === $id_to_change)
return 'wheretopost.asp';
else
return $url;
}
All you would need to do is change the value of $id_to_change to a number that represents the ID of the Post/Page you're trying to affect. So if - for example - you have an About Page that you would like to change the Action URL, you can find the ID number of your About Page in the Admin Dashboard (just go to the Page editor and look in your URL for the ID number) and change the 1 to whatever the ID number is.
Hope this helps you out, and best of luck to you.
Great answer #maiorano84 but I think you should check form ID instead of Post. Here is my version.
add_filter('wpcf7_form_action_url', 'wpcf7_custom_form_action_url');
function wpcf7_custom_form_action_url($url)
{
$wpcf7 = WPCF7_ContactForm::get_current();
$wpcf7_id = $wpcf7->id();
$form_id = 123;
return $wpcf7_id == $form_id? '/action.php' : $url;
}
Another thing you might need to disable WPCF7 AJAX. That can be disabled by placing the following code in your theme functions.php
apply_filters( 'wpcf7_load_js', '__return_false' );
You can add actions after a successful submission like the documentation says
Adding a filter will work in the sense that it will change the action on the form but unfortunately it will also break the functionality of the plugin. If you add the filter like other answers suggest the form will keep the spinner state after submission.
You can make the form do something else on submit by using advanced settings such as:
on_submit: "alert('submit');"
more details about advanced settings here.
According to #abbas-arif, his solution works great, but have a limitation. This solution change the form's action on all forms present in post with that ID.
A better solution should be to use directly the form's ID. To get it, whit wordpress >5.2, you can use:
add_filter('wpcf7_form_action_url', 'wpcf7_custom_form_action_url');
function wpcf7_custom_form_action_url($url)
{
$cf7forms = WPCF7_ContactForm::get_current();
$Form = $cf7forms -> id;
switch($Form){
case 1:
return 'destination like salesforce url 1...';
case 2:
return 'destination like salesforce url 2...';
case 3:
return 'destination like salesforce url 3...';
default:
return $url;
}
}

Set PHP Variables for Drupal 7 Theme Files

I want to set custom php variables that can be used throughout my drupal theme (html.tpl.php, page.tpl.php etc.) I need the variables set based on the $title of the node. I'm not an expert on how Drupal works, the moduling and hooks, and I just need to know the simplest/easiest way to accomplish this. I keep reading about implementing some sort of hook in the template.php file where you can set variables, but I've been unsuccesful with everything I've tried.
So, basically, how would you accomplish this:
Get $title of Node
Set variables that will be passed along into theme files (for example, to do basic things like: if($title == 'news_page') { $siteSection = "news"; } )
Have $siteSection be available to use in theme files
Any help would be great.. thanks!
Before Drupal builds the HTML for a page from a theme's template (.tpl.php file), it runs preprocess "hooks". Hooks are basically a naming convention for functions that let modules and themes override or "hook" onto Drupal core processes.
E.g., if you want to display a message to a user when they log in, you can use hook_user_login.
function MODULENAME_user_login(&$edit, $account) {
drupal_set_message("Welcome, ". $account->name);
}
When a user logs in, Drupal looks for all loaded functions that end in "_user_login" and it runs them. If this function is in an enabled module, it has been loaded, so it will get run as well.
If you want to make a variable named $site_section available in your page.tpl.php file, you can hook into template_preprocess_page. This is a theme hook, so the name is a little different, but it functions pretty much the same way. To call this hook from your theme, you need to create a file called template.php in your theme's directory. Inside template.php, we'll add:
<?php
function THEMENAME_preprocess_page(&$vars){
switch (drupal_strtolower($vars['node']->title)) {
case "about page":
$site_section = "about";
break;
case "news page":
case "news page1":
case "news page2":
$site_section = "news";
break;
default:
$site_section = "none";
break;
}
$vars['site_section'] = $site_section;
}
The <?php is used to tell the server the treat all of the proceeding code as PHP. We then declare our hook function with the intention of loading Drupal's array of page variables into a local variable called $vars. By adding the & before $vars, we'll be allowed to modify the values for use outside of this function.
The switch statement will let us efficiently test the page title for multiple values. The value of the node's title may contain uppercase letters, lowercase letters, and symbols, so to avoid a case-sensitive mismatch, we're going to convert the title to lowercase and only test that (symbols will still be in the title, though). After the switch statement, we set the value of our $site_section local value into the referenced $vars array for use in page.tpl.php.
However, if it's just your intention to break the site up into sections for theming purposes, there are other ways of accomplishing that. My answer to a similar situation a few months ago might be helpful.

wordpress plugins - handling variables

I wrote a simple twitter connect plugin which needs to display the 'logged in' user's name in the header after he logs in. The function is working properly but I am unable to display the $user variable in my header or anywhere outside the function even though it is assigned global.
Here is the end of the login function:
$user= $Twitter->get_accountVerify_credentials();
print_r($user);
// show screen name (not real name)
$twitter_user = $user->screen_name;
// show profile image url
$twitter_image = $user->profile_image_url;
I can see that it is successful because the $user gets printed, but when I call it in my header.php file the same way I can an error: Notice: Undefined variable: user
Any suggestions?
As opposed to getting wrapped up in the scope of the variables, I'd write a function to get this information. Something like:
function get_twitter_user_name(){
$user= $Twitter->get_accountVerify_credentials();
return $user->screen_name;
}
Then, in the header, where I want to display the name, I'd call the function like so:
<?php echo get_twitter_user_name(); ?>
Depending on the structure of your code, this may look a little different than what I have here, but hopefully this will give you another way of tackling this problem.

Drupal - Getting node id from view to customise link in block

How can I build a block in Drupal which is able to show the node ID of the view page the block is currently sitting on?
I'm using views to build a large chunk of my site, but I need to be able to make "intelligent" blocks in PHP mode which will have dynamic content depending on what the view is displaying.
How can I find the $nid which a view is currently displaying?
Here is a more-robust way of getting the node ID:
<?php
// Check that the current URL is for a specific node:
if(arg(0) == 'node' && is_numeric(arg(1))) {
return arg(1); // Return the NID
}
else { // Whatever it is we're looking at, it's not a node
return NULL; // Return an invalid NID
}
?>
This method works even if you have a custom path for your node with the path and/or pathauto modules.
Just for reference, if you don't turn on the path module, the default URLs that Drupal generates are called "system paths" in the documentation. If you do turn on the path module, you are able to set custom paths which are called "aliases" in the documentation.
Since I always have the path module turned on, one thing that confused me at first was whether it was ever possible for the arg function to return part of an alias rather than part of system path.
As it turns out, the arg function will always return a system path because the arg function is based on $_GET['q']... After a bit of research it seems that $_GET['q'] will always return a system path.
If you want to get the path from the actual page request, you need to use $_REQUEST['q']. If the path module is enabled, $_REQUEST['q'] may return either an alias or a system path.
For a solution, especially one that involves a view argument in the midst of a path like department/%/list, see the blog post Node ID as View Argument from SEO-friendly URL Path.
In the end this snippet did the job - it just stripped the clean URL and reported back the very last argument.
<?php
$refer= $_SERVER ['REQUEST_URI'];
$nid = explode("/", $refer);
$nid = $nid[3];
?>
Given the comment reply, the above was probably reduced to this, using the Drupal arg() function to get a part of the request path:
<?php
$nid = arg(3);
?>
You should considder the panels module. It is a very big module and requires some work before you really can tap into it's potential. So take that into considderation.
You can use it to setup a page containing several views/blocks that can be placed in different regions. It uses a concept called context which can be anything related to what you are viewing. You can use that context to determine which node is being viewed and not only change blocks but also layout. It is also a bit more clean since you can move the PHP code away from admin interface.
On a side note, it's also written by the views author.
There are a couple of ways to go about this:
You can make your blocks with Views and pass the nid in through an argument.
You can manually pass in the nid by accessing the $view object using the code below. It's an array at $view->result. Each row in the view is an object in that array, and the nid is in that object for each one. So you could run a foreach on that and get all of the nid of all rows in the view pretty easily.
The first option is a lot easier, so if that suits your needs I would go with that.
New about Drupal 7: The correct way to get the node id is using the function menu_get_object();
Example:
$node = menu_get_object();
$contentType = node_type_get_name($node);
Drupal 8 has another method. Check this out:
arg() is deprecated

Resources