Onclick Action in Yii - php

I'm totally new to Yii and I need help please even if it looks trivial. I have a page where I generate a table from my database, I added a search option and I need to generate the result as a table also.
The problem is that when I click the button nothing happens.
I also tried using submit but it didn't work.
This is my code:
...views/supermarkets/index.php:
<?php
use yii\helpers\Html;
use yii\widgets\LinkPager;
use app\views\supermarkets\search;
?>
<h1>Supermarkets</h1>
<ul>
<p>
Search by Name
</p>
<INPUT TYPE = "Text" VALUE ="" NAME = "searchname">
<button onclick="myFunction($_POST['searchname'])">Search</button>
<h3> </h3>
<?php
$array = (array) $supermarkets;
function myFunction($sname){
if (isset($sname) && $sname!='') {
$row = Yii::app()->db->createCommand(array(
'select' => '*',
'from' => 'supermarkets',
'where' => array('like', 'Name','%'.$sname.'')
))->queryRow();
$array = (array) $row;
}
echo $array;
$this->render('index',array('supermarkets' => $array));
}
function build_table($array){
// start table
$html = '<table class="altrowstable" id="alternatecolor">';
// header row
$html .= '<tr>';
foreach($array[0] as $key=>$value){
$html .= '<th>' . $key . '</th>';
}
$html .= '</tr>';
// data rows
foreach( $array as $key=>$value){
$html .= '<tr>';
foreach($value as $key2=>$value2){
$html .= '<td>' . $value2 . '</td>';
}
$html .= '</tr>';
}
// finish table and return it
$html .= '</table>';
return $html;
}
echo build_table($array);
?>
<?= LinkPager::widget(['pagination' => $pagination]) ?>
Even in the debug it doesn't pass through myFunction. Any suggestions please?

You should follow proper Yii syntax, ie define your function inside controller and call that function by creating button on index.php or other view file like:
Button on view file:
<?= Html::a('Search', ['search-function', 'Name' => $this->$sname], ['class' => 'btn btn-success']) ?>
And in your controller:
//As you define your function
public function actionSearchFunction($sname){
if (isset($sname) && $sname!='') {
$row = Yii::app()->db->createCommand(array(
'select' => '*',
'from' => 'supermarkets',
'where' => array('like', 'Name','%'.$sname.'')
))->queryAll();
$array = (array) $row;

I will explain you step by step. First, Note that everything inside <?php ?> tag will be generate at the server BEFORE rendering of the view. So, you can't execute php code on the client. If you need to execute some server code from client, You need to use Ajax(asynchronous JavaScript and XML). I recommend you to learn ajax, because this is very useful in web applications. OK, let's solve your problem. First step is to define an event for button click. You have myFunction already and I change it to this:
<button onclick="myFunction();">Search</button>
And I change your input to this:
<input type="text" value ="" name="searchname", id="searchname">
Now, I write myFunction() body in the <script></script> tag:
<script>
function myFunction()
{
$.ajax({
url: '<?php echo Yii::app()->baseUrl . '/supermarkets/sample' ?>',
type: 'post',
data: {searchname: $("#searchname").val()},
success: function (data) {
alert(data);
}
});
}
</script>
Now, you need to define an action in your controller for ajax request. I supposed you have SupermarketsController. Try to write actionSample() in it like this:
public function actionSample()
{
$array = (array) $supermarkets;
$sname = $_POST['searchname'];
...
echo "ok";
}
You can access the search input value in that function and all of your php code must be there. at the last line of that action, you must echo something(data or message). Everything you put after echo, you can get it as data parameter of success event of ajax request. In my example, you will see "ok" alert in your browser. I hope my explanation can help you to learn ajax. Note you need to include jquery library for using ajax. Good luck friend :)

Related

Values not passed from ctp file to controller in CakePHP

I have tried several solution posted in this forum and others as well but it has not helped so far. So I am posting my question finally. BTW, I am using CakePHP 3.6.
I am trying to pass a variable ($product->id) via submit button in view.ctp to my controller action "addit" but I just get "Undefined variable: id " (I have tried addit($id) and addit() either of case I have the same result.)
view.ctp
<p>
<?php echo $this->Form->create('NULL',['url'=>['controller'=>'products','action'=>'addit']]);?>
<?php echo $this->Form->input('id', ['type' => 'hidden', 'value' => $product->id]); ?>
<?php echo $this->Form->button('Add to cart now');?>
<?php echo $this->Form->end();?>
</p>
Controller:Products
public function addit() {
$this->autoRender = false;
if ($this->request->is('post')) {
// $this->Products->addProduct($this->request->data['Cart']['product_id']);
echo "".$this->Products->get($id);//for test
} else {
echo "".$this->Products->get($id);//for test
}
}
According to Cakephp 3.6
All POST data can be accessed using
Cake\Http\ServerRequest::getData(). Any form data that contains a data
prefix will have that data prefix removed. For example:
// An input with a name attribute equal to 'MyModel[title]' is accessible at
$title = $this->request->getData('MyModel.title');
You can get value of $id variable like this:
$id = $this->request->getData('id');
Further Reading: Request Body Data
Is this what you want to do?
$id = $this->request->getData('id');
debug($this->Products->get($id)); //for test

Kill the execution of controller after $this->load->view, Codeigniter

Hi I am using codeigniter for site and i am calling a function in a controller through a form in my php page the function call is:
Gear.php:
foreach ($gearArray as $key => $value) {
echo '<tr><td><img id="leftimg" src="'.base_url().''.$value["Product_Image_URL"].'"></td>';
echo '<td>'.$value["Description"].'';
echo '<form method="post" id="addtocart" action="'.site_url('GearController/addorUpdate').'">';
echo '<input type="hidden" name="desc1" value="'.$value["Name"].'">';
echo '<input type="hidden" name="cost1" value="'.$value["Price"].'">';
echo '<input type="submit" value="Add To Cart">';
echo '</form></td>';
}
echo '</table>';
?>
From this the method inside the GearController is called through
action="'.site_url('GearController/addorUpdate').'"
inside the function which is an add to cart function, i am checking whether the item is already in the cart or not and then updating it,once updated i am trying to redirect to a page using:
GearController.php:
public function addorUpdate(){
$this->load->helper('form');
$this->load->library('form_validation');
$this->load->model('CartModel','cart');
$boolean = FALSE;
$Description = $this->input->post('desc1');
$data['cartArray'] = $this->cart->return_cart();
foreach ($data['cartArray'] as $value) {
if($Description==$value['Description']){
$boolean = TRUE;
}
}
if($boolean==TRUE){
$this->updateCart($Description);
}
}
public function updateCart($Description){
$updatearray = array(
'Quantity'=>'Quantity+1',
'Price' => 'Price * Quantity',
);
$this->load->model('CartModel','cart');
$update_order = $this->cart->update_cart($updatearray,$Description);
$data['cartArray'] = $this->cart->return_cart();
$this->load->helper('url');
$this->load->view('cart',$data);
}
The problem here is that everything works fine, the page gets redirected but within seconds it displays a blank screen. I tried return, die and exit. None of it helps. It seems like the controller is executing the code under the $this->load->view. I am telling this because i previously had a function under the
if($boolean==TRUE){
$this->updateCart($Description);
}
That particular code was executed after the redirect. Could someone please help?
This sound like you might have what is call a BOM character at the start of your view file. This character is usually invisible. Make sure that there are not (apparently) black characters at the beginning.
You can also test that updateCart($Description) is running by temporarily putting this code as the first line of the function echo "This is updateCart; Then comment out all the other code in that function. If you see that text on the screen you know the function runs.
This doesn't answer your question but it's bugging me so...
Instead of this mess
foreach ($data['cartArray'] as $value) {
if($Description==$value['Description']){
$boolean = TRUE;
}
}
if($boolean==TRUE){
$this->updateCart($Description);
}
You could simply do this
if(in_array( $Description, array_column($data['cartArray'],'Description'))){
$this->updateCart($Description);
}
You can test it with this code (mockup)
$Description = 'foo';
$data = ['cartArray' => [
['Description' => 'foo'],
['Description' => 'bar'],
]
];
if(in_array( $Description, array_column($data['cartArray'],'Description'))){
echo "found";
}
Outputs
found
Test it here
https://3v4l.org/W5oB5
I think in_array is pretty self evident but here is array_column which is highly useful and often overlooked.

ZF2 Render Custom Class on Form Validation Error

How can I wrap a fieldset tag around my form rows, and how can I add a has-danger class to the fieldset when an element fail to validate?
I think I need to create a viewhelper, check if a specific formelement has a validation message and wrap the row with a fieldset, but I'm not sure if that's the right approach or how to do it.
The output I want on validation error:
<fieldset class="has-danger"><label for="username">Username</label>
<input type="text" name="username" id="username" class="form-control
input-error" value="f"><ul><li>Needs to be 5-20 characters long</li>
</ul></fieldset>
register.phtml:
<?php
$form = $this->registerForm;
$form->prepare();
echo $this->form()->openTag($form);
echo $this->formHidden($form->get('secret'));
echo $this->formRow($form->get('username'));
echo $this->formRow($form->get('password'));
echo $this->formRow($form->get('email'));
echo $this->formRow($form->get('confirm-email'));
echo $this->formSubmit($form->get('submit'));
echo $this->form()->closeTag($form);
Ok, you should use the formLabel(), formElement() and formElementErrors() view helpers instead of formRow().
To my ZF2 knowledge, the formRow() view helper doesn't let you have control on the HTML output easily. It displays the complete input HTML (label + input + errors) in one line of code.
To simply achieve your goal, your phtml structure for one input has to be as follow :
// NAME_OF_YOUR_FILE.phtml
<?php
$userNameInput = $form->get('username');
$userNameInputErrors = $this->formElementErrors($userNameInput);
?>
<fieldset class="<?= $userNameInputErrors ? 'has-danger' : '' ?>" >
<?= $this->formLabel($userNameInput) ?>
<?= $this->formElement($userNameInput) ?>
<?= $userNameInputErrors ?>
</fieldset>
This is a hard work to do this for each fields in form, so I suggest you to put this logic in a view helper.
// MyFormRow.php
<?php
namespace Your\Namespace;
use Zend\View\Helper\AbstractHelper;
class MyFormRow extends AbstractHelper
{
protected $formLabelViewHelper;
protected $formElementViewHelper;
protected $formElementErrorsViewHelper;
public function __construct($formLabelViewHelper, $formElementViewHelper, $formElementErrorsViewHelper)
{
$this->formLabelViewHelper = $formLabelViewHelper;
$this->formElementViewHelper = $formElementViewHelper;
$this->formElementErrorsViewHelper = $formElementErrorsViewHelper;
}
public function __invoke($formElement)
{
$html = '';
$errors = $this->formElementErrorsViewHelper->__invoke($formElement);
$html .= '<fieldset class=" . ($errors ? 'has-danger' : '') . ">';
$html .= $this->formLabelViewHelper->__invoke($formElement);
$html .= $this->formElementViewHelper->__invoke($formElement);
$html .= $errors;
$html .= '</fieldset>';
return $html;
}
}
?>
Declare it in your Module.php.
// In your Module.php
<?php
...
public function getViewHelperConfig()
{
return [
'factories' => [
'myFormRow' => function (HelperPluginManager $helperPluginManager) {
$formLabelViewHelper = $helperPluginManager->get('formLabel');
$formElementViewHelper = $helperPluginManager->get('formElement');
$formElementErrorsViewHelper = $helperPluginManager->get('formElementErrors');
return new MyFormRow($formLabelViewHelper, $formElementViewHelper, $formElementErrorsViewHelper);
},
],
];
}
?>
And now in your phtml file, simply :
// NAME_OF_YOUR_FILE.phtml
...
<?= echo $this->myFormRow($form->get('username')) ?>
...

Two submit buttons, one form (Yii)

I have two CHtml::submitButton() in my form, namely "Accept" and "Reject". Each of the buttons has a specific ID ... When any of the two are pressed, i would like to trigger an action in my controller. Below are the code snippets.
=========================================================
View
<?php
echo CHtml::beginForm('mycontrollerName/AcceptUserRegistration','get');
?>
<?php echo CHtml::submitButton('Accept', array('id' => 'accept')); ?>
<? echo ' '; ?>
<?php echo CHtml::submitButton('Reject', array('id' => 'reject')); ?>
<?php echo CHtml::endForm(); ?>
========================================================
Controller
public function actionAcceptUserRegistration() {
$value = $_GET['id'];
if($value == "accept"){
//will do something here
}
if($value == "reject"){
//will do something here.
}
}
======================================================================
When i implement it this way. the get value in the controller side is empty. What I'm I doing wrong? Or is there any other way around this?
You forgot to give the submit button a name (unless your framework does some magic which we cannot know about - you should really post the generated HTML code!).
If you do so, the value in $_GET['buttonname'] will be its value (not its id), i.e. Accept or Reject. This becomes pretty messy as soon as you get into i18n, so you might want to use different names for the buttons and then check isset($_GET['buttonname1']) and isset($_GET['buttonname2'])
Here is a code example for what you are trying to achive:
VIEW:
<?php
echo CHtml::beginForm('mycontrollerName/AcceptUserRegistration','get');
?>
<?php echo CHtml::submitButton('Accept', array('id' => 'accept', 'name' => 'accept')); ?>
<? echo ' '; ?>
<?php echo CHtml::submitButton('Reject', array('id' => 'reject', 'name' => 'reject')); ?>
<?php echo CHtml::endForm(); ?>
Note: I added the name parameter. As name is not displayed to the user, you can use accept instead of Accept.
CONTROLLER:
public function actionAcceptUserRegistration() {
if(isset($_GET['accept'])) {
//accepted
} else if(isset($_GET['reject'])) {
//rejected
}
//I recommend using POST method instead of GET for posting the form.
}

How to Validation Zend Form opening tag : Zend Form

How to Validation Zend Form ? (opening tag)
Example :
Form :
class MyForm extends Zend_Form {
function init() {
$this->addElement('select','my_select',array(
'label'=>'My select :',
'required'=>true,
'multioptions'=>array(''=>'-select please-','1'=>'value1','2'=>'value2')
'validators'=>array(
array('NotEmpty', true, array('messages' => 'This field is required'))),
));
} }
Controller :
$form = new MyForm();
if ($this->_request->isPost()) {
$form_name=$this->getRequest()->getParams();
if($form->isValid($form_name)){
echo "==success==";
}
else{
echo "==no success==";
}
}
$this->view->form = $form;
View :
// Render the form opening tag
echo $this->form->renderForm(false);
echo '<table>';
echo '<tr>';
echo '<th>'
// Render the label
echo $this->form->my_select->renderLabel();
echo '</th>
echo '<td>';
// Render the select
echo $this->form->my_select->renderViewHelper();
echo $this->form->my_select->renderErrors();
echo '</td>';
echo '</tr>';
echo '</table>';
echo '</form>';
i want to show message validation at view
This code is complete in answer 18/02/2011
You can render errors on a specific element with:
echo $this->form->my_select->renderErrors();
If you want to render the errors for all the form in one place :
$form->addDecorator('FormErrors');
echo $form->renderFormErrors();
I'm not really sure what you mean here but here's my best guess...
If you want to render the set of validation errors for the form and its elements in one place, try adding the FormErrors decorator to the form. See Zend_Form_Decorator_FormErrors
As for validation, simply add validators to the elements as normal.
to have validation errors you first need to add validators to your form element ,
$formElement = new Zend_Form_Element_Text('username');
$formElement->addValidator(new Zend_Validate_Alnum());
to get validation error messages do
$arrayOfErrors = $this->view->form->getMessages();

Categories