Levano
Levano

Reputation: 319

CakePHP, jQuery - Add data attribute to anchor

I'm looking for a way to insert a data attribute to my table anchors in CakePHP. It automatically generates the following code, but I have no clue on how to alter this in a way where I make it a data-target attribute.

The reason I want to achieve this is because I'm linking to different div's on the same page and want to prevent the page from reloading. Do I have to insert a preventDefault() from jQuery? And if so, how to do so?

This is my current code:

<?php foreach ($servers as $server): ?>
  <tr>
     <td><?= $this->Number->format($server->id) ?></td>
     <td><?= h($server->url) ?></td>
     <td><?= h($server->description) ?></td>
     <td><?= h($server->Timestamp) ?></td>
     <td class="actions">
         <?= $this->Html->link('View', array('#' => 'admin-view-' . $server->id)) ?>
         <?= $this->Html->link('Edit', array('#' => 'admin-edit-' . $server->id)) ?>
     </td>
   </tr>
<?php endforeach; ?>

Here's the result I'm looking for; it has to be done using the CakePHP conventions (don't mind the list item):

<a data-target="admin-edit">Edit</a>
<a data-target="admin-view">View</a>

Upvotes: 4

Views: 1076

Answers (2)

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72299

Did you tried this:-

<?= $this->Html->link('View',array('#' => 'admin-view-' . $server->id,'data-target'=>"admin-view");?>
<?= $this->Html->link('Edit',array('#' => 'admin-view-' . $server->id,'data-target'=>"admin-edit");?>

To prevent from page reload, create a link with href="javascript:void(0);" like below:-

<?= $this->Html->link('View','javascript:void(0);',array('#' => 'admin-view-' . $server->id,'data-target'=>"admin-view");?>
<?= $this->Html->link('Edit','javascript:void(0);',array('#' => 'admin-view-' . $server->id,'data-target'=>"admin-edit");?>

If you want to prevent through jQuery (not with the above code) then:-

$('link').click(function(e){
   e.preventDefault();
   //rest your code
});

Note:- Make sure that jQuery library is added before this code and this code must be at the bottom of the page.

Upvotes: 3

Sumon Sarker
Sumon Sarker

Reputation: 2795

Here is the details about CakePHP HtmlHelper link method

CakePHP link methods takes 3 arguments as its parameters.

  • Title [String]
  • Url   [String or Array]
  • Options/Attributes [Array]

Syntax :

 $this->Html->link($title, $url = null, array $options = []);

Example :

echo $this->Html->link(
   'Title',
   '/path/to/url', #OR ['controller'=>'','action'=>'','others']
   [
     'class' => 'button',
     'target' => '_blank',
     'data-url'=>'#',
     'data-path'=>'',
     /*Other attributes*/
   ]
);

Here is the details about Creating Links in CakePHP

For your problem, If no need href='' in <a> tag, Then you can use button or other tags instead of <a> tag.

Upvotes: 2

Related Questions