Alvaro
Alvaro

Reputation: 41595

postLink generates invalid code at CakePHP 2.3

I am using CakePHP 2.3

I have two environments where I have my web application. At the testing environment with the exact same version of the application (all files are the same) I am having a problem with the Form->postLink method.

It shows this error on the Javascript console:

Uncaught TypeError: Object # has no method 'submit' users:119 onclick

Comparing the resulting HTML from both environments I can notice that the attributes name and id generated by this method are repeated more than once in the same page (which shouldn't be like that).

This is the code use to generate those post links:

foreach($users as $user){   
    $delete = $this->Form->postLink(__('Delete'), array('action' => 'delete', $user['user_id']), __('Are you sure you want to delete %s?', $user['user_id']));
}

This is the problematic generated HTML with repeated values for id and name as you can see:

<!-- link 1 -->
<form action="delete/1/" name="post_51e8019d095f1" id="post_51e8019d095f1" style="display:none;" method="post">
    <input type="hidden" name="_method" value="POST"/>
</form>

<a href="#" onclick="if (confirm(&#039;Are you sure you want to delete blabla?&#039;)) { document.post_51e8019d095f1.submit(); } event.returnValue = false; return false;">Delete</a>



<!-- link 2 -->
<form action="delete/2/" name="post_51e8019d095f1" id="post_51e8019d095f1" style="display:none;" method="post">
    <input type="hidden" name="_method" value="POST"/>
</form>

<a href="#" onclick="if (confirm(&#039;Are you sure you want to delete blabla22?&#039;)) { document.post_51e8019d095f1.submit(); } event.returnValue = false; return false;">Delete</a>

Why is this happening? Could it be related with the configuration of the web server somehow? I don't see another explanation for it...

Thanks.

Upvotes: 0

Views: 1634

Answers (1)

Alvaro
Alvaro

Reputation: 41595

The problem was caused by a bug in IIS 7.0.6000.16386 and the PHP function uniqid as pointed out here.

I am using a slightly different version in both environments ( IIS 7.0.6000.16386 vs IIS 7.5.7600.16385) and that was the cause of the problem.

In order to solve it I modified the file lib/Cake/View/Helper/FormHelper.php chaning the line $formName = uniqid('post_'); inside the postLink function to:

$formName = uniqid('post_', true);

That adds more entropy and as the documentation says:

If set to TRUE, uniqid() will add additional entropy (using the combined linear congruential generator) at the end of the return value, which increases the likelihood that the result will be unique.

Update

Ended up having to add one more change due to problems with javascript in forms. I added one more line after $formName = uniqid('post_', true); so it looks like:

$formName = uniqid('post_', true);
$formName = str_replace('.', '', $formName);

Upvotes: 1

Related Questions