Getting form element attribute values in cakephp 2 - cakephp

I came from a symfony background. In symfony to get any form element attributes that symfony generates I would do something like form.username.vars.id , form.username.vars.full_name to get id, name attribute for that field.
I was wondering how I would do this in cakephp2. For example in cakephp:
echo $this->Form->input('username');
would generate:
<input type="text" required="required" id="UserUsername" value="admin" maxlength="50" name="data[User][username]">
I only want to get the id, name generated by cakephp so that I could use in javascript . How can I do this ? Are there any helpers to do so?

The convention is consistent for naming these attributes.
Name will always be data[ModelName][field]
ID will always be ModelNameField
You can also choose the ID when you echo out the element:
echo $this->Form->input('username', array('id' => 'username'));
You can also change the name (you guess it, 'name' => 'name'), however that could definitely mess with form processing in CakePHP.

Related

Creating form arrays with Laravel 4

In Laravel 4 I can create text inputs with code like:
{{ Form::text('title', '', ['placeholder' => 'Ex. title', 'id' => 'title']) }}
This is very useful, because if other fields of my form fail validation, I can just do...
return Redirect::back()->withErrors($validator)->withInput(Input::all());
And when the form is shown again, the field title will conserve the value that was submitted before.
Good stuff.
Now here is my problem: What about input arrays?
I added the following input fields to my form:
<input type="text" name="option[]" />
<input type="text" name="option[]" />
<input type="text" name="option[]" />
<input type="text" name="option[]" />
And I submitted the form, knowing that would fail, to see if when the form appears again, the values on these fields still remained. Instead Laravel threw an exception.
ErrorException
htmlentities() expects parameter 1 to be string, array given
Even if I have just 1 option, it still gives me the same error:
{{ Form::text('option[]') }}
Now, I know that I could handle the filling of the array option manually, maybe like this:
$options = Input::get('option');
return Redirect::back()
->withErrors($validator)
->withInput(Input::except('option'))
->with('options', $options);
and then just looping through the $option array on the blade template.
Yes, that would probably work. But that is kinda hacky, and it still misses the powerful workflow of Laravel to autofill fields after failed submission, like I did back with title. So my question is:
Is there any built-in way in Laravel 4 to handle Input Arrays under these situations?
If you add an index to each input like:
{{ Form::text('option[1]') }} {{ Form::text('option[2]') }} it will work.
You can see how this works in vendor\laravel\framework\src\Illuminate\Html\FormBuilder.php in the function that creates the input

Issue with saving HABTM data in CakePHP

I’m having an issue saving HABTM data in a controller.
I have an Article model, which is associated to an Event model, as articles may be about specific events in my application. I’ve read the CakePHP cookbook entry on saving HABTM data so understand how it works on the controller level, but having difficulties understanding how it should look on the view side of things.
What I have in my form are inputs for the article data (title, excerpt, content etc). I then want checkboxes for each event in my database then I can then check to associate an article with the corresponding event(s).
Normally, I would have a checkbox like this:
<input type="checkbox" name="event[]" value="1" />
Where 1 is the ID of a venue, and do a checkbox like this for every event in my database, but this doesn’t seem to work in CakePHP.
What should I put for my field name when creating checkboxes with $this->Form->input()? What’s the “CakePHP” way?
Assuming you've set the events in the controller as described in the Cook Book:
$this->set('events', $this->Event->find('list'));
then your input should look like this, basically like the example in the Cook Book, with the addition of the multiple option with an value of checkbox:
$this->Form->input('Event', array('multiple' => 'checkbox'));
This should give you a correctly formatted list of checkboxes with the events displayField as labels.
Your next problem might be validation, so also have a look at CakePHP HABTM data not saving to database
I suppose that you save your data from the ArticlesController::add().
So your view, you should have something like the following
add.ctp
<?php
echo $this->Form->create('Article');
echo $this->Form->input('Article.title', array('type' => 'text'));
echo $this->Form->input('Article.excerpt', array('type' => 'textarea'));
echo $this->Form->input('Article.title', array('type' => 'textarea'));
/** Generate multiple checkboxes, assumung that your array of events is $events **/
foreach($events as $index => $evt) {
echo $this->Form->input('Event'.$index.'.id', array('type' => 'checkbox', 'value' => $evt['Event']['id']));
}
echo $this->Form->submit('save');
?>
The foreach loop will create a set of checkboxes which looks like this
<input type="checkbox" name="data[Event][0][id] value="1">
<input type="checkbox" name="data[Event][1][id] value="2">
<input type="checkbox" name="data[Event][2][id] value="3">
...
The respected data sent to the controller can be accessed via the $this->request->data['Event'] array. If you have setup the relations correclty then the data saving
is been done automatically for you.
I hope this helps.

cakephp form input with no name attribute

I am using CakePHP 2.2.4.
I am using the Form Helper to create a form. I need to have a form input with no name attribute.
Is this possible with the formhelper or should I just use HTML for creating this form?
eg in HTML:
<input type="text" maxlength="20" autocomplete="off" class="card-number stripe-sensitive required" />
Basically Am I able to do the above using the formhelper in CakePHP ?
Thanks.
You can overrule any property in the $options array, which is the second argument to the input() method. So technically you could do:
echo $this->Form->input('Model.field', array(
'label' => false,
'div' => false,
'name' => false,
'maxlength' => 20,
'autocomplete' => 'off',
'class' => 'card-number stripe-sensitive'
));
But please be aware the dropping the name attribute makes the entire field useless if you want to do anything with it's data in your controller/model, as the $this->data array gets it's names from the name attribute of your input fields.
CakePHP needs the name attribute to be able to know what is being submitted by the form. I'm not sure I follow why you would want there to be no name attribute.
If you are concerned that a named input will be passing something to a save method you could always use unset in your controller to remove it from $this->request->data before saving/validation.
Otherwise, you can manually add the markup to your view, but again not sure why you would want an unnamed input element.

Custom Input HTML with CakePHP's FormHelper

I'm trying to use CakePHP's form helper to generate some input elements.
The HTML I am trying to generate is:
<div class="formRow">
<label>LabelText:</label>
<div class="formRight">
<input name="data[User][email_address]" type="text" value="">
</div>
<div class="clear"></div>
</div>
Ive had a look through the Cake documentation (Using 2.1) and I can't find enough information on how to do this.
It looks like I need to use the format option on the input method, but can't figure out how to get it right. Especially concerned about the div surrounding the input field with a class name on it..
E.g. Ive tried something like this:
echo $this->Form->input('email_address', array(
"input" => array('attributes' => array('wrap' => 'div','class' => 'formRight'))));
But this doesnt change any of the markup and just throws this error:
Notice (8): Array to string conversion [CORE\Cake\View\Helper.php, line 459]
So my question is how can I get this form helper to create that markup?
Any help much appreciated
You're over-thinking it. (No worries, we all do). Just remember, CakePHP is all about making things easier for you (among other things) - if you're struggling with trying to force Cake to do something for you, just remember, you can fall back to the basics - it's just PHP/HTML after-all.
<div class="formRow">
<label>LabelText:</label>
<div class="formRight">
<?php echo $this->Form->input('email_address', array(
'div'=>false, 'label'=>false)); ?>
</div>
<div class="clear"></div>
</div>
You should use the Form helper for your forms when possible, but you don't have to use all of it's presets like surrounding divs & labels. In the case above, just tell it you don't want the div, and wrap it with a div yourself.
If you don't want <div>s or <label>s around any inputs, you can also set the form's inputDefaults:
$this->Form->create('Whatever', array(
'inputDefaults' => array('label'=>false, 'div'=>false)
));
If you have a lot of fields, you can use Jquery.
php:
echo $this->Form->input('email_address', array('class' => 'formRow'));
Jquery:
$(".formRow").each(function() {
$(this).wrapInner( "<div class='formRight'></div>");
$(this).find("label").prependTo(this);
$(this).append('<div class="clear"></div>');
});

How to pass an array as a hidden field?

I am implementing an auto complete box using the Ajax.autocompleter method of the scriptaculous.js framework.
This is the auto complete box and the div where the auto suggested entries are populated.
<?php echo $form->create('Share', array('url' => '/forms/share')); ?>
<label for="shareWith">Share Form with</label>
<input type="text" id="autocomplete" name="autocomplete_parameter"/>
<div id="autocomplete_choices" class="autocomplete"></div>
<input type="hidden" id="sharedUserId" name="sharedUserId"/>
<?php echo $form->end('Share');?>
This is the JQuery function to get the auto-suggested list and to get the id of the selected entry which is stored in the hidden field of the form.
new Ajax.Autocompleter("autocomplete", "autocomplete_choices",
"http://localhost/FormBuilder/forms/autoComplete",
{
tokens: ',',
afterUpdateElement : getSelectedId
}
);
function getSelectedId(text, li) {
$("#sharedUserId").val(li.id);
}
Suppose if I select multiple entries,how to send those values?
Can I have an array as a hidden field, so that I can have an array of the selected elements and save that array as a hidden field?
Simply create a new hidden input field for every selected ID, and make sure that for each you have name="sharedUserId[]". This doesn't follow the CakePHP form element naming convention, but it will make sure that the POSTed value of sharedUserId is an array.
serialize with json and parse it in the server back. PHP 5.2 can parse json natively.
Not related to your question though..
http://docs.jquery.com/Plugins/Autocomplete
jQuery Auto complete you

Resources