I'm trying show on views (each row) my custom form. It works, but the form doesn't work proper. I need to give to each form different ids.
hook_forms should help me, but I cannot manage how to use it. If I put print $form into it, I still cannot see my forms.
I'm calling my form like this from the template file:
$form1 = drupal_get_form('votingform_create_decision_form_' . $node->nid, $node->nid);
print drupal_render($form1);
Now I got it working:
function hook_forms($form_id, $args) {
if ($args[0] == 'mymodule_form_') {
$forms['mymodule_form_' . $args[1]] = array(
'callback' => 'mymodule_form',
'callback arguments' => array($args[1]),
);
}
return $forms;
}
Related
I am trying to add a function to that strips the html from a field in drupal views. I found a function for sql server called "udf_StripHTML" that does that.
http://blog.sqlauthority.com/2007/06/16/sql-server-udf-user-defined-function-to-strip-html-parse-html-no-regular-expression/
I am using the following code:
/**
* Implements hook_views_query_alter().
*/
function cviews_views_query_alter(&$view, &$query) {
// Add a strip html tags from content.
$fields = array('field_data_body.body_value');
foreach ($query->where as $key1 => $value) {
foreach ($value['conditions'] as $key2 => $coditions) {
if (in_array($coditions['field'], $fields)) {
$query->where[$key1]['conditions'][$key2]['field'] = 'dbo.udf_StripHTML(' . $coditions['field'] . ')';
}
}
}
}
When views module converts the query object to a string the field become
from:
'dbo.udf_StripHTML(field_data_body.body_value)';
to:
[dbo].[udf_StripHTMLfield_data_body.body_value]
My question is, how can I add a function there?
Thank you,
You are going way too deep here friend. I'm going to assume that you're using Drupal 7, but for Drupal 8 this should be similar (since views is in core for both).
A few things about your approach:
That function is a user defined function which means that it needs to be defined at a much lower-level (in the SQL database) before you can use it in your query.
This is a red-herring approach, however, because you don't need to even touch the SQL to accomplish what you want (you can do this with PHP with strip_tags!)
You don't need a query alter hook here (we don't need to go to the database to do this). You could do this with one of the preprocess or field hooks from the field API or the views API using the function linked in my previous point.
Even better, you don't even have to touch the code to accomplish this. You can do it right in the Drupal UI.
Under the field settings for the view, select rewrite results and then Strip HTML tags. Presto, no more HTML tags in that field.
Image source: https://www.drupal.org/node/750172
Here is the solution that worked for me:
// Traverse through the 'where' part of the query.
foreach ($query->where as &$condition_group) {
foreach ($condition_group['conditions'] as &$condition) {
if (in_array($condition['field'], $fields)) {
$value = $condition['value'];
$field = $condition['field'];
$condition = array(
'value' => array(),
'field' => t('dbo.udf_StripHTML(!field) like \'#value\'', array(
'!field' => $field,
'#value' => $value)),
'operator' => 'formula',);
}
}
}
I manually set the CakePHP Pagination values in my Usergals Controller like so, so as to Paginate a related Model (TreasuresUsergal) on the view of Usergal. Here is a simplified snippet from the UsergalController:
public function view($id = null) {
$this->loadModel('TreasuresUsergal');
$options['joins'] = array(
array('table' => 'treasures',
'alias' => 'Treasure2',
'type' => 'LEFT',
'conditions' => array(
'Treasure2.id = TreasuresUsergal.treasure_id',
)
)
);
$options['conditions']=array('TreasuresUsergal.usergal_id'=>$id);
$options['fields']=array('Treasure2.*','TreasuresUsergal.ord','TreasuresUsergal.comments');
$options['order']=array('TreasuresUsergal.ord'=>'asc');
$options['limit']=$limit;
$this->Paginator->settings = $options;
$treasures=$this->Paginator->paginate('TreasuresUsergal');
$this->set('treasures',$treasures);
}
So in the above example, $id is the value passed to the view function from the URL. There is a live example of this here:
http://collections.centerofthewest.org/usergals/view/20
As you can see, it works just fine for a single page. However, today I tested the Paginator in the view and discovered the "next" button does not work. The Counter, sorting, and Page numbers all load correctly - but anytime the actual named parameter "page:n" is passed (when n is greater than 1) I get a Not Found page with the following error:
Not Found
Error: The requested address '/usergals/view/20/page:2?url=%2Fusergals%2Fview%2F20' was not found on this server.
I must be missing something simple - I have experimented with the routes a little, but haven't been able to figure it out. Or perhaps I am missing some Paginator options? Or does it think its OutOfBounds when its not?
UPDATE / WORKAROUND
After some messing around, I have devised this workaround. Not as nice as I'd like, but here is the basic idea (error handling, etc can be added)
First, I added a check in beforeFilter to see if page paramter was set. If so, I change it to 'p' parameter and redirect.
I did this here because otherwise I had problems with the Not Found exception (see notes at bottom). So, in beforeFilter:
if (isset($this->params['named']['page'])){
$newurl=$this->params['named'];
$pg=$newurl['page'];
unset($newurl['page']);
$newurl['p']=$pg;
$this->redirect(array('action' => 'view/'.$this->params['pass'][0])+$newurl);
}
Then, in the 'view' function of the same controller, I added this along with the other Paginator options:
if (isset($this->params['named']['p'])) $options['page']=$this->params['named']['p'];
With this, the standard Paginator behavior seems to work fine in the view. Prev, next, etc.
If anyone has a better suggestion, I would love to hear it. I don't like the idea of having to redirect, but it works for now.
It's worth noting that adding this code (even just to experiment) - caused all of my pagination counts to stop working. The query in debug was correct, but the displayed counts were wrong:
try {
$this->Paginator->paginate();
} catch (NotFoundException $e) {
}
When I've Search my listing i'm getting some results with pagination, but when i go for second page my search is
breaking as it was a get request where i'm getting the search results via post method.
Note: For getting search results I don't want to submit the form via get request (i.e. Query string params) and also don't want to store the form data in session
Is there any way to get the results which satisfy the above conditions ?
You want to implement the PRG Pattern.
Post/Redirect/Get (PRG) is a web development design pattern that
prevents some duplicate form submissions, creating a more intuitive
interface for user agents (users). PRG implements bookmarks and the
refresh button in a predictable way that does not create duplicate
form submissions.
The CakeDC Search plugin makes that pretty easy to do in CakePHP.
It would be very hard to do it using only "POST" calls. You'll need to transfor your POST into a GET call.
Check this post i made or clone it from github
Hope this helps
EDIT:
Using my git repo. If you want url querystrings instead of named parameters:
in this line, instead of the foreach build the querystring and pass it to the redirect
in this line, get the parameters from the query string ($GET)
and in this line add page, sort and direction to this->paginate
I haven't tested it, but it should be something like that
We can do it with a patch.
In Views :
create search form :
$this->Form->create('Search', array('url' => array('controller' => 'controller', 'action' => 'index', substr(time(), 2,rand(1, 7) ))) );
Note : A random number appended at the end of the form action. This will let us know when to clear session.
in Controller :
public function index( $search = null)
{
$conditions = array(1 => 1);
if( !empty($this->data['Search']['keyword']) && $search)
{
$conditions = array('Model.field like' => $this->data['Search']['keyword'] . '%');
// store search array in session
$this->Session->write('conditions', $this->data['Search']);
}
if ($search)
{
$this->request->data['Search'] = $this->Session->read('conditions');
$conditions = array('Model.field like' => $this->data['Search']['keyword'] . '%');
}
else
{
$conditions = array(1 => 1);
$this->Session->delete('conditions');
}
$this->paginate= array('limit'=> 10, 'conditions' => $conditions);
$lists = $this->Paginate('Model');
}
Hope you understand the logic behind.
I have a module, which includes multistep form. I decided to make one of these steps work like this: free times per employee are rendered as html elements, and when element is clicked, Javascript will apply the value to hidden input field.
So I found this tutorial: http://drupal.org/node/1092122 but it didn't work for me, maybe I made a error, maybe not.
My module name is reservation. My template file is named reservation_select_time_week_page.tpl.php and its in the reservation/theme folder.
I have these functions:
function reservation_theme() {
// basic things
$module_path = drupal_get_path('module', 'reservation');
$base = array(
'path' => "$module_path/theme",
);
// define themes
return array(
'reservation_select_time_form' => $base + array(
'render element' => 'form',
'template' => 'reservation_select_time_week_page',
),
);
}
function template_preprocess_reservation_select_time_week_page(&$variables) {
echo "this works!";
}
function template_preprocess_select_time_form(&$variables) {
echo "this works!";
}
I dont know which of those preprocess functions is right (should it be named based on template name or form id?
Anyhow, custom template is not applying.
I also have tried using the:
$form['start_time'] => array('#theme' => 'reservation_select_time_week_page');
I got it working, so that the static html is rendered in template file, but I dont know how I can render the form elements in template file. Using:
drupal_render($form)
caused the form to go infinite loop I think.
Is Drupal even able to handle complex forms and form layouts?
I am working on a book review application and I am using autoComplete to search for titles in when creating a review. The review model has an associated book_id field and the relationship is setup as the review hasOne book and a book hasMany reviews.
I am trying to pass the Book.id (into the book_id field), but I want to display Book.name for the user to select from. With the default setup (accomplished via CakePHP's tutorial), I can only pass Book.name. Is it possible to display the name and pass the id?
Also, I am passing it via the following code in the create() action of the review controller:
$this->data['Review']['book_id'] = $this->data['Book']['id'];
Is that the proper way to do it in CakePHP? I know in Ruby on Rails, it is automatic, but I can't seem to make it work automagically in CakePHP. Finally, I am not using the generator because it is not available in my shared hosting environment... so if this is the wrong way, what do I need other than associates in my models to make it happen automatically?
Thanks for the help and I promise this is my question for awhile...
UPDATE- I tried the following, but it is not working. Any ideas why?
function autoComplete() {
$this->set('books', $this->Book->find('all', array(
'conditions' => array(
'Book.name LIKE' => $this->data['Book']['name'].'%'
),
'fields' => array('id','name')
)));
$this->layout = 'ajax';
}
The problem is that when I use the code above in the controller, the form submits, but it doesn't save the record... No errors are also thrown, which is weird.
UPDATE2:
I have determine that the reason this isn't working is because the array types are different and you can't change the array type with the autoComplete helper. As a workaround, I tried the follow, but it isn't working. Can anyone offer guidance why?
function create() {
if($this->Review->create($this->data) && $this->Review->validates()) {
$this->data['Review']['user_id'] = $this->Session->read('Auth.User.id');
$this->Book->find('first', array('fields' => array('Book.id'), 'conditions' => array('Book.name' => $this->data['Book']['name'])));
$this->data['Review']['book_id'] = $this->Book->id;
$this->Review->save($this->data);
$this->redirect(array('action' => 'index'));
} else {
$errors = $this->Review->invalidFields();
}
}
FINAL UPDATE:
Ok, I found that the helper only takes the find(all) type or array and that the "id" field wasn't passing because it only applied to the autoComplete's LI list being generated. So, I used the observeField to obtain the information and then do a database lookup and tried to create a hidden field on the fly with the ID, but that didn't work. Finally, the observeField would only take the characters that I put in instead of what I clicked, due to an apparent Scriptaculous limitation. So, I ended up going to a dropdown box solution for now and may eventually look into something else. Thanks for all of the help anyway!
First of all, $this->data will only contain ['Book']['id'] if the field exists in the form (even if it's hidden).
To select something by name and return the id, use the list variant of the find method, viz:
$selectList = $this->Book->find('list', array(
'fields' => array(
'id',
'name'
)));
$this->set('selectList', $selectList);
In the view, you can now use $selectList for the options in the select element:
echo $form->input('Book.id', array('type' => 'hidden'));
echo $form->input('template_id', array(
'options' => $selectList,
'type' => 'select'
));