Dependencies for custom forms in Drupal 7 - forms

I have several forms for a single content type in Drupal 7. The purpose of this is to initiate different workflows when the user submits the form, depending on the type of information included, and defined by the /url for each. These forms are on different pages and the fields shown on each are defined in a custom module. For example:
.../form1 initiates workflow 1 and displays fields a, b, e, f, g
.../form2 initiates workflow 2 and displays fields a, b, c, e, h
.../form3 initiates workflow 3 and displays fields a, b, f, x, y
In this module it looks something like this:
function my_custom_module_custom_form() {
// Build Form
$form = getForm('content_type');
switch (strtolower($form['#action'])):
case('/form1'):
$form['field_some_field']['#access'] = FALSE;
switch (strtolower($form['#action'])):
case('/form2'):
$form['field_other_field']['#access'] = FALSE;
I would like to have a page template for each form, so I can specify what goes into each, rather than showing/hiding every field for each within the module, which is cumbersome, given the number of fields.
Can I create a page template for each form and link the submit button to trigger a particular action in the module?
Note: adding dependencies or using separate content types is not applicable to our use cases. If there are errors in the code above, it is only that i've given a quick example here, the actual module works.
Thanks for the help!

I have created the theme suggestions for a particular node form:
Change the function name to THEMENAME_preprocess_node
Change initial value of template_filename to 'node'
Account for dashes in aliases by adding this line below the second if statement: $alias = str_replace('-', '_', $alias);
So here's what it looks like now:
function THEMENAME_preprocess_node(&$variables, $hook) {
// Node template suggestions based off URL alias
if (module_exists('path')) {
$alias = drupal_get_path_alias(str_replace('/edit','',$_GET['q']));
if ($alias != $_GET['q']) {
$alias = str_replace('-', '_', $alias);
$template_filename = 'node';
foreach (explode('/', $alias) as $path_part) {
$template_filename = $template_filename . '__' . $path_part;
$variables['theme_hook_suggestions'][] = $template_filename;
}
}
}
}
Please let me know if you need any more details.

Related

How do i poulate a field with a parameter from previous page in a multipage form in gravityforms?

I want to build a multipage from.
The first page asks for first name and last name.
I want to greet the user with his first name in the second page.
The best way to do this is to use Live Merge Tags with Populate Anything:
https://gravitywiz.com/documentation/gravity-forms-populate-anything/#live-merge-tags
If you collected the user's first name in a Name field on page 1, you could great him in the field label for a field on page 2 like so:
Hello, #{Name (First):1.3}
(In this example, the field ID for the Name field is 1. The 3 refers to the first name input of a Name field and will always be 3).
If avoiding another plugin (as useful as that one is), you can use either the pre_submission_filter or pre_submission hooks to do this.
If their name was field 1 and lets say the field you'd like to show is field 2...
// THESE FOUR FILTERS WORK TOGETHER TO PRE-POPULATE ALL SORTS OF STUFF, AND YOU CAN ADD TO THIS AS NECESSARY. MINE IS ABOUT 1500 LINES LONG AND IS USED BY SEVERAL FORMS.
add_filter('gform_pre_render', 'populate_forms');
add_filter('gform_pre_validation', 'populate_forms');
add_filter('gform_pre_submission_filter', 'populate_forms', 10);
add_filter('gform_admin_pre_render', 'populate_forms');
function populate_forms($form) {
$form_id = $form['id'];
$current_form = 2; // pretending the form id you are working on is 2.
$future_form = 10; // imaginary form you'll create later for another purpose.
switch($form_id) {
case $current_form:
$first_name = !empty(rgpost('input_1_3')) ? rgpost('input_1_3') : null; // gets the value they entered into the first-name box of field 1.
foreach ($form['fields'] as &$field) {
if ($field->id === '2') { // Make as many of these as necessary.
if ($first_name) { // make sure there's actually a value provided from field 1.
$field->placeholder = $first_name; // not necessary, just habit since sometimes you'd need to have a placeholder to reliably populate some fields.
$field->defaultValue = $first_name; // this is the piece that will actually fill in the value like you'd expect to see in your question.
}
}
}
break;
//case $future_form: do more stuff.
//break;
}
return $form;
}
That should be a decent start for your functionality plugin where you can populate the current and future forms without much hassle. This can also be done with the gform_field_value hook; I've always found the language a bit clumsy with that one, personally.
The plugin mentioned earlier is definitely neat, but I found myself wanting to rely on that stuff less and less.

How to use a helper

I am creating a module that allows a user to input details into a form and save their details to allow relevant information to be forwarded to them at specified times.
To retrieve the details from the form and add them to the database I followed a tutorial and produced this code
public function saveAction()
{
$title = $this->getRequest()->getPost('title');
$f_name = $this->getRequest()->getPost('f_name');
$l_name = $this->getRequest()->getPost('l_name');
if ( isset($title) && ($title != '') && isset($f_name) && ($f_name != '') && isset($l_name) && ($l_name != '') ) {
$contact = Mage::getModel('prefcentre/prefcentre');
$contact->setData('title', $title);
$contact->setData('f_name', $f_name);
$contact->setData('l_name', $l_name);
$contact->save();
$this->_redirect('prefcentre/index/emailPreferences');
} else {
$this->_redirect('prefcentre/index/signUp');
}
}
The tutorial says to put it into the controller in a saveAction, and that works fine. However from my very limited understanding it would go in to a helper and i'd call the helper from the controller
I placed the above code in my helper and called it from within the saveAction using the following
Mage::helper('module/helpername');//returned blank screen and did not save
I also tried
Mage::helper('module/helpername_function');//returned error
My config has
<helpers>
<prefcentre>
<class>Ps_Prefcentre_Helper</class>
</prefcentre>
</helpers>
1 . Should this code go in a helper, if not where should it go?
2 . How do I call the helper(or the location the code need to go) to utilise the code?
1 . Should this code go in a helper, if not where should it go?
The actual code you posted imo is predestinated to be used within a controller action because it realizes a very specific process flow: Get user data for a specific case -> save if applicable -> redirect.
Secondly, a helper imo never should control route dispatching. It's a helper, not a controller.
I fail to see any use case where putting the method into a helper would give any advantages.
2 . How do I call the helper(or the location the code need to go) to
utilise the code?
Your definition uses <prefcentre> as alias, so if you did setup the helper the Magento standard way and using the file app/code/local/Ps/Prefcentre/Helper/Data.php, than your helper methods are callable like this:
Mage::helper('prefcentre')->myMethodName();

Zend Form - two select menus in "sync"

I have been trying to find out an answer for some time and still nothing.
There are two select menus, they have the same amount of options and values. Say
Select A
"one"=>1
"two"=>2
"three"=>3
Select B
"one"=>One
"two"=>Two
"three"=>Three
Is there a way with Zend Form and validate to make them "synced".
So If I select SelectB=>Three, it automatically selects SelectA=>3 and vice-versa.
Or only with a custom validator?
The JavaScript solution works like this:
Modify your form.php
$A->setOptions(array('onchange'=>'mapIt(this.id)'));
$B->setOptions(array('onchange'=>'mapIt(this.id)'));
and
Add below JavaScript function to your view
function mapIt(id){
if(id == 'A'){
document.getElementById('B').value = document.getElementById(id).value;
}else{
document.getElementById('A').value = document.getElementById(id).value;
}
}

Zend_Form_Element from Zend_Config_Ini

Currently I am loading form element definitions from an ini file that looks like this as an example:
[tickets] ; tablename
ticket_number.name = "ticket_number"
ticket_number.type = "text"
ticket_number.label = "Ticket ID: "
ticket_number.options.validators.alnum.validator = "alnum"
ticket_number.options.validators.strlen.validator = "StringLength"
ticket_number.options.validators.strlen.options.min = "6"
ticket_number.options.validators.strlen.options.max = "20"
assigned_date.name = "assigned_date"
assigned_date.type = "text"
assigned_date.label = "Entered Date: "
Now lets say I have a form element (select / dropdown box), and I want to load the options from a database (lookup table), is there a way to automatically configure that within the form elements ini config, or does that have to be done within the form class upon creation of the element?
Well, there are ways to do this, the question is whether you actually want to do this.
Possible ways to do it:
Create your own smart select element, which has the ability to build a multiOptions list based on some option values which you provide in your ini file.
or, before creating the form instance, inject the multiOptions values into the Zend_Config file.
or, after you've created the form instance, set the multiOptions using $form->getElement('name')->setMultiOptions(array(..))

CodeIgniter: URIs and Forms

I'm implementing a search box using CodeIgniter, but I'm not sure about how I should pass the search parameters through. I have three parameters: the search string; product category; and the sort order. They're all optional. Currently, I'm sending the parameters through $_POST to a temporary method, which forwards the parameters to the regular URI form. This works fine. I'm using a weird URI format though:
http://site.com/products/search=computer,sort=price,cat=laptop
Does anyone have a better/cleaner format of passing stuff through?
I was thinking of passing it into the products method as arguments, but since the parameters are optional things would get messy. Should I suck it up, and just turn $_GET methods on? Thanks in advance!
Query Strings
You can enable query strings in CodeIgniter to allow a more standard search function.
Config.php
$config['enable_query_strings'] = FALSE;
Once enabled, you can accept the following in your app:
http://site.com/products/search?term=computer&sort=price&cat=laptop
The benefit here is that the user will find it easy to edit the URL to make a quick change to their search, and your search uses common search functionality.
The down side of this approach is that you are going against one of the design decisions of the CodeIgniter development team. However, my personal opinion is that this is OK provided that query strings are not used for the bulk of your content, only for special cases such as search queries.
A much better approach, and the method the CI developers intended, is to add all your search parameters to the URI instead of a query string like so:
http://site.com/products/search/term/computer/sort/price/cat/laptop
You would then parse all the URI segments from the 3rd segment ("term") forward into an array of key => value pairs with the uri_to_assoc($segment) function from the URI Class.
Class Products extends Controller {
...
// From your code I assume you are calling a search method.
function search()
{
// Get search parameters from URI.
// URI Class is initialized by the system automatically.
$data->search_params = $this->uri->uri_to_assoc(3);
...
}
...
}
This would give you easy access to all the search parameters and they could be in any order in the URI, just like a traditional query string.
$data->search_params would now contain an array of your URI segments:
Array
(
[term] => computer
[sort] => price
[cat] => laptop
)
Read more about the URI Class here: http://codeigniter.com/user_guide/libraries/uri.html
If you're using a fixed number of parameters, you can assign a default value to them and send it instead of not sending the parameter at all. For instance
http://site.com/products/search/all/somevalue/all
Next, in the controller you can ignore the parameter if (parameter == 'all'.)
Class Products extends Controller {
...
// From your code I assume that this your structure.
function index ($search = 'all', $sort = 'price', $cat = 'all')
{
if ('all' == $search)
{
// don't use this parameter
}
// or
if ('all' != $cat)
{
// use this parameter
}
...
}
...
}