Access an id of a user in a table from a controller - zend-framework

PHP, Zend Framework, Apache, MySql.
I want to edit a user in a list by clicking its corresponding edit button.
when i click the edit button, the corresponding users id should be send to the controller from where it should be accessed.
But I cant seem to get the user id in the controller.
After getting the id , i want to populate the fields in edit.phtml with the data retrieved view model.
Since i cant access the id, i cant populate the fields.
The url is like /Sample/user/edit/2 where 2 is id of a user.
UserController.php
<?php
class UserController extends Zend_Controller_Action
{
protected $_user;
public function init()
{
/* Initialize action controller here */
$this->_user = new Application_Model_User();
}
public function indexAction()
{
// action body
}
public function listAllAction()
{
// action body
$this->view->users = $this->_user->listUsers();
}
public function registerAction()
{
// action body
if($this->getRequest()->isPost())
{
$data = array(
'user_uname' => $this->_request->getParam('uname'),
'user_pwd' => $this->_request->getParam('paswd'),
'user_address' => $this->_request->getParam('address')
);
$this->_user->insert($data);
}
}
public function editAction()
{
// action body
**$u_id = $this->_request->getParam('user_id');**
// print_R("Hi ".$u_id);
// exit;
if($this->_request->isPost())
{
$u_id = $this->_request->getPost('user_id');
//print_R("Hi ".$u_id);
//exit;
}
else
{
**$this->view->user = $this->_user->getUser($u_id);**
}
}
}
Model class
<?php
class Application_Model_User extends Zend_Db_Table_Abstract
{
protected $_name="tbl_user";
public function listUsers()
{
// action body
$sql = "select * from tbl_user";
$result = $this->_db->query($sql);
return $result->fetchAll();
}
public function getUser($id)
{
$query = "select * from tbl_user where user_id = ?";
return $this->_db->fetchRow($query,array($id));
}
}
ListUser.phtml
<html>
<head></head>
<body>
<b><center>List of Users</center></b>
<form name="list_users" method="post" action="">
<table>
<tr><th>ID</th>
<th>Name</th>
<th>Password</th>
<th>Address</th>
<th>Action</th>
</tr>
<?php foreach ($this->users as $usr): ?>
<tr>
<td><?php echo $usr['user_id'] ?></td>
<td><?php echo $usr['user_uname'] ?></td>
<td><?php echo $usr['user_pwd'] ?></td>
<td><?php echo $usr['user_address'] ?></td>
<td>Edit</td>
<td>Delete</td>
</tr>
<?php endforeach; ?>
<tr>
<td colspan=2>Add More Users</td>
</tr>
</table>
</form>
</body>
</html>
edit.phtml
<html>
<head></head>
<body>
<form name="user_edit" method="post" action="<?php print $this->baseUrl(); ?>/user/edit">
<b><center>Edit Profile</center></b>
<table>
<tr>
<td>Username</td>
<td><input type="text" name="uname" id="uname1" value="<?php print $this->user['user_uname'] ?>"/></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="paswd" id="paswd1"/></td>
</tr>
<tr>
<td>Address</td>
<td><textarea type="text" name="address" id="address1"></textarea></td>
</tr>
<tr>
<td></td>
<td><input type='submit' name='edit_user' value='Update User'/></td>
</tr>
<tr>
<td colspan=2>See All Users</td>
</tr>
</table>
</body>
</html>
Thank you in advance..
I got the answer.
In usercontroller's editaction change the code $u_id = $this->_request->getParam('user_id'); to $u_id = $this->getRequest()->getParam('id');

Small change needed: change the following line:
<td>Edit</td>
to
<td>Edit</td>

Related

Clear the filled data of form in Phalcon Framework

I am new to phalcon and trying to learn this framework. I have created a simple form. Now, When I fill up the form, I am able to store the data in database. After submitting the form I want to be on the same page. Now the issue is, form is still have the filled data it is not clearing up. I have googled and found the clear() method to clear the form data but it seems that its not working. What to do?
Here is my code
//Controller
use Phalcon\Mvc\Controller;
class ProfileController extends Controller
{
public function indexAction()
{
// Add some local CSS resources
$this->assets->addCss("css/styles.css");
$this->assets->addCss("css/bootstrap.min.css");
// And some local JavaScript resources
$this->assets->addJs("js/jquery.js");
$this->assets->addJs("js/bootstrap.min.js");
}
public function createAction(){
//create object of model class
$profile = new Tbl_profile();
$profile->fname= $this->request->getPost('firstname');
$profile->lname= $this->request->getPost('lastname');
$profile->email= $this->request->getPost('email');
$success=$profile->save();
if($success) {
$this->flash->success("Profile created!");
//redirect to same page.
$this->dispatcher->forward(['action' => 'index']);
}else {
}
}
}
//views
<html>
<head>
<title>Title</title>
<?php $this->assets->outputCss(); ?>
</head>
<body>
<h4 class="ml-5 mt-2"> Create Profile</h4>
<?php echo $this->getContent(); ?>
<?php echo $this->tag->form("profile/create") ?>
<table class="table">
<tbody>
<tr scope="row">
<td>First Name</td>
<td><?php echo $this->tag->textField("firstname"); ?></td>
</tr>
<tr scope="row">
<td>Last Name</td>
<td><?php echo $this->tag->textField("lastname"); ?></td>
</tr>
<tr scope="row">
<td>Email</td>
<td><?php echo $this->tag->textField("email"); ?></td>
</tr>
<tr scope="row">
<td></td>
<td><?php echo $this->tag->submitButton("Create");?></td>
</tr>
</tbody>
</table>
</form>
</body>
</html>
Once you save the data to database, redirect to the controller instead of forwarding the request because forwarding the request won't reload the page.
$this->request->redirect('profile/index');
Read this what's the difference between redirect and dispatch in phalcon? for more information
You must create form class to have ability using $form->clear() method.
See the doc https://docs.phalconphp.com/cs/3.4/forms

Footable table timeout when row count is over 1000

I have tried to implement footable pluglin on an MVC application and it currently has 3000+ users which fail to load and the browser page times out. For the User Admin section I have created the following View:
#model IEnumerable<MyBudgetWeb.Models.ApplicationUser>
#{
ViewBag.Title = "Index";
}
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script type="text/javascript">
$(function () {
$('.footable').footable();
});
</script>
<br /><br />
<h2>Bill Pay Users</h2>
<input id="filter" type="text" placeholder="Filter" />
<br /><br />
#if (Model.Count() > 0)
{
<table class="table" data-filter="#filter" data-page-size="50">
<thead>
<tr>
<th data-type="numeric">Customer Number</th>
<th data-type="numeric">Account Name</th>
<th data-type="numeric" data-hide="phone">Go Live Date</th>
<th data-type="numeric" data-hide="phone">Online Live Date</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>#item.CustomerNumber</td>
<td>#item.AccountName</td>
<td>#item.GoLiveDate</td>
<td>#item.OnlineCreationTimestamp</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
#Html.ActionLink("Details", "Details", new { id = item.Id }) |
#*#Html.ActionLink("Delete", "Delete", new { id = item.Id })*#
</td>
</tr>
}
</tbody>
<tfoot class="hide-if-no-paging">
<tr>
<td colspan="12" class="text-center">
<ul class="pagination"></ul>
</td>
</tr>
</tfoot>
</table>
}
else
{
<h2>You are still awaiting users to be added. All users will be displayed here.</h2>
}
My controller looks as follows:
public async Task<ActionResult> Index()
{
return View(await UserManager.Users.ToListAsync());
}
Is there any way workarounds to prevent this?
there are 2 option to solve:
1. PHP Side script, by setting the time limit of execution. Use this code on top your PHP script:
set_time_limit(0);
Use Footable AJAX what describe here:
http://fooplugins.github.io/FooTable/

How to add an add button in in my custom module

I have a module which is used to add banner images through admin panel. I have created the module successfully. My module edit page has two tabs. One for adding general informations of banner and second one for adding images. The general information tab is working fine now.
I need to have a button 'add banner image' in my second tab initially. When clicked on it, it should load an file type button.We can use this button for loading the image. We can use 'add banner image' in any number of times for loading the image. This is just similar to the add custom option for a product. I need that exact same functionality here.
I have searched a lot. But couldnt find how to add 'add banner image' button to my second tab. Please help me to solve this issue. Give me an idea of how can impliment this functionality. Sorry for my bad english.Thanks
I have created a similar functionality where I can add postcode ranges in my custom module using below code.
In my Module_name/Block/Adminhtml/Regions/Edit/Tab/Form.php I have added.
$fieldset->addField('postcodes', 'text', array(
'name'=>'postcodes',
'class'=>'requried-entry'
));
$form->getElement('postcodes')->setRenderer(
$this->getLayout()->createBlock('zones/adminhtml_regions_edit_tab_postcodes')
);
This will add postcodes field in my tab with renderer adminhtml_regions_edit_tab_postcodes
In my Module_name/Block/Adminhtml/Regions/Edit/Tab/Postcodes.php I have added the button with the code.
class Ripples_Zones_Block_Adminhtml_Regions_Edit_Tab_Postcodes
extends Mage_Adminhtml_Block_Catalog_Product_Edit_Tab_Price_Group_Abstract
{
public function __construct()
{
$this->setTemplate('zones/postcodes.phtml');
}
protected function _prepareLayout()
{
$button = $this->getLayout()->createBlock('adminhtml/widget_button')
->setData(array(
'label' => Mage::helper('zones')->__('Add Postcode Range'),
'onclick' => 'return addPostCodeRange.addItem()',
'class' => 'add'
));
$button->setName('add_postcode_range_button');
$this->setChild('add_button', $button);
return parent::_prepareLayout();
}
}
This will add a button on my tab with the onclick function addPostCodeRange.addItem().
After this I have added a phtml file in design/adminhtml/default/default/template/zones/postcodes.phtml
<?php $_htmlId = $this->getElement()->getHtmlId() ?>
<?php $_htmlName = 'postcodes';?>
<tr>
<td class="label">Postcode Range</td>
<td colspan="10" class="grid">
<table cellspacing="0" class="data border" id="postcodes_table">
<col width="50" />
<col width="50" />
<col width="1" />
<thead>
<tr class="headings">
<th><?php echo Mage::helper('zones')->__('From') ?></th>
<th><?php echo Mage::helper('zones')->__('To') ?></th>
<th class="last"><?php echo Mage::helper('catalog')->__('Action') ?></th>
</tr>
</thead>
<tbody id="<?php echo $_htmlId ?>_container"></tbody>
<tfoot>
<tr>
<td colspan="3" class="a-right"><?php echo $this->getAddButtonHtml() ?></td>
</tr>
</tfoot>
</table>
<script type="text/javascript">
//<![CDATA[
var tierPriceRowTemplate = '<tr>'
+ '<td><input type="text" value="{{from}}" class="custgroup required-entry" name="<?php echo $_htmlName ?>[{{index}}][from]" id="postcodes_row_{{index}}_from" />'
+ '</td>'
+ '<td><input type="text" value="{{to}}" class="custgroup required-entry" name="<?php echo $_htmlName ?>[{{index}}][to]" id="postcodes_row_{{index}}_to" />'
+ '</td>'
+ '<td class="last"><input type="hidden" name="<?php echo $_htmlName ?>[{{index}}][delete]" class="delete" value="" id="postcodes_row_{{index}}_delete" />'
+ '<button title="<?php echo Mage::helper('zones')->__("Delete Range") ?>" type="button" class="scalable delete icon-btn delete-product-option" id="postcodes_row_{{index}}_delete_button" onclick="return addPostCodeRange.deleteItem(event);">'
+ '<span><span><span><?php echo Mage::helper('zones')->__("Delete") ?></span></span></span></button></td>'
+ '</tr>';
var addPostCodeRange = {
template: new Template(tierPriceRowTemplate, new RegExp('(^|.|\\r|\\n)({{\\s*(\\w+)\\s*}})', "")),
itemsCount: 0,
addItem : function () {
var data = {
from: '',
to: '',
readOnly: false,
index: this.itemsCount++
};
if(arguments.length >= 2) {
data.from = arguments[0];
data.to = arguments[1];
}
if (arguments.length == 3) {
data.readOnly = arguments[2];
}
Element.insert($('<?php echo $_htmlId ?>_container'), {
bottom : this.template.evaluate(data)
});
$('postcodes_row_' + data.index + '_from').value = data.from;
$('postcodes_row_' + data.index + '_to').value = data.to;
if (data.readOnly == '1') {
['from', 'to', 'delete'].each(function(idx){
$('postcodes_row_'+data.index+'_'+idx).disabled = true;
});
$('postcodes_row_'+data.index+'_delete_button').hide();
}
},
disableElement: function(el) {
el.disabled = true;
el.addClassName('disabled');
},
deleteItem: function(event) {
var tr = Event.findElement(event, 'tr');
if (tr) {
Element.select(tr, '.delete').each(function(elem){elem.value='1'});
Element.hide(tr);
Element.addClassName(tr, 'no-display template');
}
return false;
}
};
<?php $collection = Mage::getModel('zones/regions')->getCollection()->addFieldToFilter('regions_id',array('eq' => $this->getRequest()->getParam('id'))); ?>
<?php foreach ($collection as $_item): ?>
<?php $postcodes = unserialize($_item['postcodes']); ?>
<?php foreach ($postcodes as $postcode): ?>
addPostCodeRange.addItem( '<?php echo $postcode['from'] ?>', '<?php echo $postcode['to'] ?>');
<?php endforeach; ?>
<?php endforeach; ?>
//]]>
</script>
</td></tr>
This file contains the function. I have added two textboxes on function call. You can add file field in this function.
Hope this helps.

Button redirecting to the grid page

I have a custom module 'banner' and in which I have added a button in its second tab(only two tabs for the module). when click on that button, it is submitting my banner automatically and then go to the grid page(i e it acts as just another save button). But the function of this button is to add an uploading image field.ie whenever the button is clicked, it should add an image form field to my tab file. This is my tab file.
<?php
class Karaokeshop_Banner_Block_Adminhtml_Banner_Edit_Tab_Image extends Mage_Adminhtml_Block_Widget_Form
{
protected function _prepareForm()
{
$form = new Varien_Data_Form();
$this->setForm($form);
$fieldset = $form->addFieldset('banner_image', array('legend'=>Mage::helper('banner')->__('Banner Image')));
//declaring a new custom form field and adding
$fieldset->addType('add_button', 'Karaokeshop_Banner_Block_Adminhtml_Banner_Edit_Tab_Field_Custom');
$fieldset->addField('banner_img_add_button', 'add_button', array(
'title' => Mage::helper('banner')->__('Add Banner Image'),
'id' => 'add_banner_img_button',
'class' => 'scalable save',
'style' => '',
'onclick' => 'banner.add(this)',
'type' => 'button',
));
return parent::_prepareForm();
}
}
this is my button defining file
<?php
class Karaokeshop_Banner_Block_Adminhtml_Banner_Edit_Tab_Field_Custom extends Varien_Data_Form_Element_Abstract
{
public function __construct($attributes=array())
{
parent::__construct($attributes);
}
public function getElementHtml()
{
$value = $this->getTitle();
$onclick=$this->getOnclick();
$class=$this->getClass();
$id=$this->getId();
$style=$this->getStyle();
$type=$this->getType();
$html='<button id="'.$id.'" class="'.$class.'" style="'.$style.'" onclick="'.$onclick.'" type="'.$type.'" title="'.$value.'">'.$value.' </button>';
$html .= '<p id="' . $this->getHtmlId() . '"'. $this->serialize($this->getHtmlAttributes()) .'>
<script type="text/javascript">
//<![CDATA[
var banner =
{
add : function(obj)
{
},
};
//]]>
</script>
</p>';
return $html;
}
}
what should i do to change my button to an add button? what should I do to avoid this submitting functionality of the button. Please help me. Thanks in advance
First you need to call your phtml from block like this :
class My_Moudles_Block_Adminhtml_Image_Edit_Tab_Form extends Mage_Adminhtml_Block_Widget_Form
{
public function __construct()
{
parent::__construct();
$this->setTemplate('modules/imageupload.phtml');
$this->setFormAction(Mage::getUrl('*/*/imageupload'));
}
then create file in adminhtml/default/default/template/yourmodule/imageupload.phtml and put this code there.
<div class="entry-edit">
<div class="entry-edit-head">
<h4 class="icon-head head-edit-form fieldset-legend"><?php echo $this->__('General')?></h4>
<div class="form-buttons"></div>
</div>
<form id="imageform" method="post" action="<? echo $this->getFormAction(); ?>">
<div id="rules_form" class="fieldset ">
<div class="hor-scroll">
<table cellspacing="0" class="form-list">
<tbody>
<tr>
<td class="label"><?php echo $this->__('Add Image')?></td>
<td class="grid tier" colspan="10">
<table cellspacing="0" id="chain_tiers" class="chain border" style=" width:465px; ">
<thead>
<tr class="headings">
<th><?php echo $this->__('Image')?></th>
<th class="last"><?php echo $this->__('Action')?></th>
</tr>
<tr class="template no-display" id="email_chain_add_template">
<td class="nobr">
<input type="file" id="chain_Image" value="0" name="imageg" class="requried-entry input-text">
</td>
<td class="last"><input type="hidden" value="" disabled="no-template" class="delete" name="email_chain[__index__][delete]"><button onclick="emailsControl.deleteItem(event);return false" class="scalable delete icon-btn delete-product-option" title="Delete Image"><span><?php echo $this->__('Delete')?></span></button></td>
</tr>
</thead>
<tfoot>
<tr>
<td></td>
<td class="a-right" colspan="6">
<button style="" onclick="emailsControl.addItem()" class="scalable add" type="button" title="Add email" id="id"><span><span><span><?php echo $this->__('Add Image')?></span></span></span></button></td>
</tr>
</tfoot>
<tbody id="email_chain_container">
<tr>
<td class="nobr">
<input type="file" id="chain_Image" value="" name="Image[]" class="input-text">
</td>
<td class="last"><input type="hidden" value="" class="delete" name="email_chain[delete][]"><button onclick="emailsControl.deleteItem(event);return false" class="scalable delete icon-btn delete-product-option" title="Delete Image"><span><?php echo $this->__('Delete')?></span></button></td>
</tr>
</tbody>
</table>
<script type="text/javascript">
//<![Cchain[
var emailsControl = {
itemsCount : 0,
deleteButton : false,
addItem : function () {
var chain = {};
chain.TEMPLATE_ID = 0;
chain.index = this.itemsCount++;
if (arguments.length == 1) {
chain.TEMPLATE_ID = arguments[0];
}
var s = '<tr>' + $('email_chain_add_template').innerHTML.replace(/__index__/g, '#{index}').replace(/\sdisabled="?no-template"?/g, ' ').replace(/disabled/g, ' ').replace(/="'([^']*)'"/g, '="$1"') + '</tr>';
var template = new Template(s);
Element.insert($('email_chain_container'), {'bottom': template.evaluate(chain)});
$('chain_row_'+chain.index+'_TEMPLATE').value = chain.TEMPLATE_ID;
maxItemsCount++;
},
deleteItem : function(event) {
var tr = Event.findElement(event, 'tr');
if (tr) {
jQuery(tr).remove();
}
}
}
var maxItemsCount = 2;
//]]>
</script>
</td>
</tr>
</tbody>
</table>
</div></form>
</div>
</div>
Hopes this will solve your issue.
For edit you can do it like this :
<tbody id="email_chain_container">
<?php foreach($images as $row){ ?><tr>
<td class="nobr">
your image code
</td></tr>

Symfony forms post

I read about Symfony forms and i have simple question :
i Make 2 templates "test" and test1 . I want to post forms values of
test to test1 and after to show them with echo.
In test i put:
form action="<?php echo url_for('maraton/test') ?>" method="POST" />
<table>
<tr>
<?php echo $form?>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="submit" />
</td>
</tr>
</table>
</form>
my action is :
public function executeTest(sfWebRequest $request)
{
$this->form = new AthletesForm();
}
public function executeTest1(sfWebRequest $request)
{
$this->form = new AthletesForm();
if ($request->isMethod('post'))
{
$values = $this->form->getValues();
}
When creating a form you create it using an action :
public function executeContact($request)
{
$this->form = new sfForm();
}
Then to display that form you use a template
<?php echo $form->renderFormTag('foo/contact') ?> // this route "foo/contact" points to the action that will process the submit
<table>
<?php echo $form ?>
<tr>
<td colspan="2">
<input type="submit" />
</td>
</tr>
</table>
</form>
Then to process the form submit you use either the same action as above or a seperate action :
if ($request->isMethod('post'))
// this if statement would be added if you used the same action to
// create / process the submit of the form
{
$this->form = new sfForm(); // create an empty form object
$this->form->bind($request->getParameter('contact'));
// merges (binds) the post data with the form
if ($this->form->isValid()) // if the data is valid
{
// Handle the form submission
$contact = $this->form->getValues();
$name = $contact['name'];
// Or to get a specific value
$name = $this->form->getValue('name');
// Do stuff
// persist to database / save to file etc
$this->redirect('foo/bar');
}