How to add Gravity Forms fields in gform_pre_render() - gravity-forms-plugin

I have a multi page Gravity Form that presents a series of questions by way of a radio button.
Which of the following would you choose?
o Choice #1
o Choice #2
+----------+ +----------+
| BACK | | NEXT |
+----------+ +----------+
Each question and choice set is configured using custom fields (Advanced Custom Fields). I'm able to iterate through all of these questions and choices just fine from within the gform_pre_render filter and now I want to create the needed Gravity Form fields on the fly.
Specifically, there will be a page field and radio button field for every question.
I really have tried just about every search criteria I can think of on Google and scoured through documentation on Gravity Help, but I just don't see an example of adding fields dynamically.
Can someone shine a light for me? :P

You can create a field with GFFields::create(). Here's a rough example (assumes you are within the gform_pre_render filter.
$props = array(
'id' => 123,
'label' => 'My Field Label',
'type' => 'text'
);
$field = GF_Fields::create( $props );
array_push( $form['fields'], $field );
There are probably more properties you will need to specify to get the field working. I would recommend using print_r() on an existing field to get an idea of all the properties available. You will also want to make sure your field IDs are unique.
Lastly, in order for data to be captured from these existing fields, you will probably want to also add your dynamic fields via the gform_pre_validation filter as well.

Related

How to access backpack fields on custom (non-CRUD) page?

I've made a custom page in backpack admin panel. This page is non-CRUD (not related to any model). There are several forms on it, with date pickers, select inputs, etc. So I'am trying to find a way to use backpack fields to create these date pickers and select inputs. Because it seems to be awkward to embed custom js-controls into the project, as Backpack already has appropriate fields.
The only solution I came up with, is to create a crud controller for random model, disable all operations except create, use create operation view as custom page (backpack fields are available this way), and finally override store() method - to prevent creating new model entry in DB.
So, is there a proper way to access backpack fields on custom (non-CRUD) page?
Backpack 4.x fields aren't meant to be used outside CRUDs, but you can do that.
Option A
At their core, Backpack fields are just Blade views, so you can load them using the Blade helper #include(). Just make sure to pass along all variables that the blade file needs. I believe in 99% of the fields that will be a $field and a $crud variable, so this will work:
#php
// set the CRUD model to something (anything)
// but ideally it'd be the model of the entity that has the form
$crud = app()->make('crud');
$crud->setModel(\App\Models\Monster::class);
#endphp
#include('crud::fields.number', [
'crud' => $crud,
'field' => [
'name' => 'price',
'label' => 'Price',
'prefix' => '$'
]
])
This way, you only load the bits you actually want (the inputs), without the overhead of a CrudController. You can point the form to your custom controller and do the saving yourself. What you need to pass for a $field above is a Backpack field definition in array form.
This way is super-simple, but it has a big downside if you ask me. The field definition has to be 100% correct and complete, you lose all the magic and assumption logic that Backpack usually does to make your life easier when you add field using addField(). That's why in most cases I think it's more convenient to go with Option B.
Option B
Instead of manually loading all each field Blade view, add them using addField(), then load all of them just like Backpack does it in the Create or Update operation:
#php
$crud = app()->make('crud');
$crud->setModel(\App\Models\Monster::class);
$crud->addField([
'name' => 'price',
'label' => 'Price',
'prefix' => '$'
]);
#endphp
<form method="post">
#include('crud::form_content', [ 'fields' => $crud->fields(), 'action' => 'create' ])
</form>
The above will produce an output like this:
The benefit of this second option is that you can "forget" to mention stuff in the field definition and Backpack will assume it, you can use the fluent syntax, you can use most Backpack features, really...

Drupal 7 Views add list of authors as exposed filter

I have a view with a number of exposed filters that I want to add an exposed filter for the author, so that the user can limit a list of nodes by the creator of the node (in addition to a number of other filters).
What I've done so far:
I've added an exposed filter of the author and set the operator to "contains any word" (so the usernames could just be a + separated list)
This is by default a text field, but I would like it to appear as a list of checkboxes (similar to taxonomy)
Using hook_form_alter I've added the following code to change it to a list of checkboxes (harcoded for now but I'll fix shortly)
$form['name']['#type'] = "select";
$form['name']['#size'] = "3";
$form['name']['#multiple'] = TRUE;
$form['name']['#options'] = array(
'admin' => 'admin',
'tyler' => 'tyler',
'test' => 'test'
);
$form['name']['#theme'] = "select_as_checkboxes";
When this form is submitted it changes the url to &name[]=tyler&name[]=admin, what I would like to do is combine these with a foreach so that url would look like &name=tyler+admin, but I'm really not sure how exactly to achieve this in the API.
I tried adding a function to $form['#submit'], and changing the value of the field in there, but that still didn't change the output.
Any advice?
Quick Edit
For the time being I have switched this to use radios instead of checkboxes, which solves the issue that I was having.
To break down the issue I was having a bit further, the names of the checkboxes where getting set to name[]= instead of name= because of the multiple inputs. The name filter in Views does not know how to handle multiple values for the name field.
For now I will see if this flies with the client, but if anybody has an answer for the original question of adding checkboxes for all authors to an exposed filter that would be awesome!
Use Better Exposed Filters module.

Zend Form Select, managing it using the array notation

I've a form in Zend that I use to manage the privileges of a series of resources (we're talking about dynamic ACLs stored in a db). So, for each of them I want to decide, through a select element (dropdown) who has the access. The controller will receive the request and handle it. My question is: how can I do to add elements to the form for having the possibility to store all the choices in one single array composed by many elements as the number of select element of form? Can I ask you a short real example? Thank you!
$myArray = array( ''=>'Select',
'Father'=>'Father',
'Mother'=>'Mother',
'Brother'=>'Brother',
'Sister'=>'Sister',
'Daughter'=>'Daughter',
'Son'=>'Son',
'Other'=>'Other',
);
'relationship' => array(
'type'=>'select',
'options'=>
array(
'label'=>'Relation',
'multiOptions' => $myArray,
)
),
OR
check this

How do I get a regular Checkbox in a Zend Form?

I have a form in Zend_Form that needs some checkboxes and I'd like them to be regular old checkboxes. You know, you give em a name and a value. If they are checked your post data contains name=>value.
Zend_Form is generating two inputs fields. One, the checkbox with a value=1 and the second a hidden input with a value=2. Both have the same name. I understand in theory how Zend expects the checkbox to work, but that's not how I expect it to work and it's not how I want it to work. How do I get my old fashion HTML checkbox back?
I have tried using $this->createElement, $this->addElement and creating a Zend_Form_Element_Checkbox manually. None allow me to set the checkbox's value and all generate the hidden input.
The final and REALLY correct answer is to add an option to the element :
$this->addElement('checkbox', 'my_element', array(
'label' => 'My Element Label',
'name' => 'my_element_name',
'disableHidden' => true
));
Zend_Form_Element_MultiCheckbox is what you're looking for.
The standard Checkbox element is meant to represent "yes/no" scenarios.
You could extend Zend library and add your own custom form element to render it just like you expect it. I did it for having a date field and it worked just fine.
I wonder why that does not work for you. You can set the values to anything you want (setCheckedValue() and setUncheckedValue()). So the only difference to normal checkbox is
if (null == $this->_getParam('checkbox', null)) {
//vs.
if ($unchecked == $this->_getParam('checkbox')) {
What exactly are you trying to do?

Why does the '#weight' property sometimes not have any effect in Drupal forms?

I'm trying to create a node form for a custom type. I have organic groups and taxonomy both enabled, but want their elements to come out in a non-standard order. So I've implemented hook_form_alter and set the #weight property of the og_nodeapi subarray to -1000, but it still goes after taxonomy and menu. I even tried changing the subarray to a fieldset (to force it to actually be rendered), but no dice. I also tried setting
$form['taxonomy']['#weight'] = 1000
(I have two vocabs so it's already being rendered as a fieldset) but that didn't work either.
I set the weight of my module very high and confirmed in the system table that it is indeed the highest module on the site - so I'm all out of ideas. Any suggestions?
Update:
While I'm not exactly sure how, I did manage to get the taxonomy fieldset to sink below everything else, but now I have a related problem that's hopefully more manageable to understand. Within the taxonomy fieldset, I have two items (a tags and a multi-select), and I wanted to add some instructions in hook_form_alter as follows:
$form['taxonomy']['instructions'] = array(
'#value' => "These are the instructions",
'#weight' => -1,
);
You guessed it, this appears after the terms inserted by the taxonomy module. However, if I change this to a fieldset:
$form['taxonomy']['instructions'] = array(
'#type' => 'fieldset', // <-- here
'#title' => 'Instructions', // <-- and here for good measure
'#value' => "These are the instructions",
'#weight' => -1,
);
then it magically floats to the top as I'd intended. I also tried textarea (this also worked) and explicitly saying markup (this did not).
So basically, changing the type from "markup" (the default IIRC) to "fieldset" has the effect of no longer ignoring its weight.
This sounds pretty strange because the manipulation of the form elements' #weight parameter always works reliably for me as advertised. One thing to note, though, is that the weights only affect the order relative to the elements siblings, so if the element you want to move around is on a level below that of the other elements, you'd have to change the weight of the parent element that is on the same level as the ones you want to move against.
To clarify, if you have a hierarchy like so,
$element['foo'];
$element['bar'];
$element['bar']['baz']
you can not move 'baz' relative to 'foo' by setting the weight of 'baz'. You'd have to either set the weight on 'bar' (moving it also), or pull out 'baz' and bring it to the same level as 'foo'.
Another possible reason could be CCK: If you have CCK installed, it allows you to set the order of its own as well as other fields under admin/content/node-type/<yourNodeType>/fields. It changes the order by registering the pre-render callback content_alter_extra_weights(), so this would run after your changes in hook_form_alter.
Edit: Update to answer the question update
The markup field type has a special behavior when used inside fieldsets, which is hinted on in the forms api documentation:
Note: if you use markup, if your content is not wrapped in tags (generally <p> or <div>), your content will fall outside of collapsed fieldsets.
It looks like if it does not only fall outside of collapsed fieldsets, but also refuses to respect the weight in those cases. Wrapping the content of the markup field in <p> tags makes it respect the weight on my machine:
$form['taxonomy']['instructions'] = array(
'#value' => "<p>These are the instructions</p>",
'#weight' => -1,
);
Sometimes (or always, when weighting CCK elements) the line that works in your hook_form_alter or $form['#after_build'] callback is this one:
$form['#content_extra_fields']['taxonomy']['weight'] = 5;
Wanted to insert a <div> I could use in JS. This didn't work for me:
$form['you_as_reviewer']['ui_container'] = array(
'#type' => 'markup',
'#value' => '<div id="le_reviewer_tags_ui"/>',
'#weight' => 5,
);
Weight was ignored.
This worked:
$form['you_as_reviewer']['ui_container'] = array(
'#type' => 'markup',
'#prefix' => '<div>',
'#value' => '<div id="le_reviewer_tags_ui"/>',
'#suffix' => '</div>',
'#weight' => 5,
);
Added prefix and suffix.
I do not quite understand what it is you want to achieve. Could you maybe clarify? Do you want to change the position of the taxonomy's drop-down on the page?
In the mean time you could install the Drupal Devel module (if you haven't done so yet). Then enable "Display form element keys and weights" from Admin > Devel Settings.
This should help you to debug your problem.
Edit after feedback:
I looked into it some more. The taxonomy weight is set in taxonomy.module on line 556 (Drupal 6.12):
$form['taxonomy']['#weight'] = -3;
To test I also implemented hook_form_alter for my module like this:
function mymodule_form_alter(&$form, $form_state, $form_id) {
...
$form['taxonomy']['#weight'] = -9;
...
}
This works for me i.e. it moves the taxonomy drop-down to the top of the page. I can change the weight and it moves accordingly on the rendered page.
Since you said you tried setting $form['taxonomy']['#weight'] in your original post I can currently think of only two possible checks:
Make sure the cache is cleared before testing. (you can use the Devel module for this)
Check to see if your hook_form_alter is called after taxonomy_form_alter
I you post the code you currently have we could look at it in more detail.
Please note: the weights displayed by the Devel module are not very useful for this situation. The weights of the elements on the "sub-forms" are displayed and not the weight of the "sub-form" itself. E.g. when I set $form['taxonomy']['#weight'] = -9; the -9 is not displayed by the Devel module but rather the weights of the elements inside $form['taxonomy'].
Have you specified the weight of another field and now your node form is not organized properly? The form api is kinda touchy and altering the form can result in things getting mixed up. I sometimes have to reassign a weight to my submit/preview buttons to get them back at the bottom of the form where they belong.
Just to cover all bases, make sure that you are clearing your cache as necessary. Drupal stores forms in it's cache by default, if you have the caching module enabled.
This is working for me
$form['forgot_password']['#markup'] = '<div class="text-align-right"><a class="text-primary" href="/user/password" target="_blank" title="Forgot Password?">Forgot Password?</a></div>';
$form['forgot_password']['#weight'] = 3;