How to add a new ZF2' Zend\Form\Element within jQuery ajax - zend-form

I want to add a new ZF2' Zend\Form\Element within jQuery ajax. But while I use the Zend Form , I don't know how to make it. This is the add.phtml file.
<script type="text/javascript">
$(document).ready(function(){
$(".pid").change(function(){
var id = $('.pid').val();
var $_this = $(this);
$.ajax({
type:"POST",
url:"<?php echo $this->url('Element/default',array('action'=>'change'));?>",
data:"pid="+id,
dataType:'json',
async:false,
success:function(data){
if(data.response){
//here I want to add a new select component after select conponent "pid" using like "$this->formRow($form->get('mid'))" or else .
}
}
});
});
});
</script>
the following is the remaining part of the html.
<?php
$title = 'add';
$this->headTitle($title);
?>
<h1><?php echo $this->escapeHtml($title); ?></h1>
<?php
$form = $this->form;
$form->setAttribute('action', $this->url(
'Element/default',
array(
'action' => 'add'
)
));
$form->prepare();
echo $this->form()->openTag($form);
echo $this->formRow($form->get('pid'));
echo $this->formRow($form->get('name'));
echo $this->formRow($form->get('desc'));
echo $this->formSubmit($form->get('submit'));
echo $this->form()->closeTag();
How do I add a new zend form element within jquery ajax ? Thanks.

You have script to receive data using ajax and view/html should be received by this script. You need controller/action to rendering data and return as response.
use Zend\View\Model\JsonModel;
//some controller
public function changeAction(){ // your requested action
//1. get partial helper to rendering html;
$partial = $this->getServiceLocator()->get('ViewHelperManager')->get('partial');
$form = new Form();// your form
//2. render html
$html = $partial('path/to/your/file/phtml',['form'=>$form]);
//3. return data as JSON because in your ajax configuration dataType: 'json'
return new JsonModel([
'html' => $html,
]);
}
in your js success function should be:
success:function(data){
if(data.html){
$_this.find('blockToAppend').append(data.html);
}
}

Related

Make an ajax request from a Prestashop module

I am making a module and I need to make an ajax request, with JSON response if possible, how can i do this ?
I don't understand really well the structure of Prestashop 1.7 on this.
Thanks !
This is pretty simple, you just have to make the controller with Prestashop's standards then link it to your frontend Javascript.
Name a php file like this : ./modules/modulename/controllers/front/ajax.php
Then put inside :
<?php
// Edit name and class according to your files, keep camelcase for class name.
require_once _PS_MODULE_DIR_.'modulename/modulename.php';
class ModuleNameAjaxModuleFrontController extends ModuleFrontController
{
public function initContent()
{
$module = new ModuleName;
// You may should do some security work here, like checking an hash from your module
if (Tools::isSubmit('action')) {
// Usefull vars derivated from getContext
$context = Context::getContext();
$cart = $context->cart;
$cookie = $context->cookie;
$customer = $context->customer;
$id_lang = $cookie->id_lang;
// Default response with translation from the module
$response = array('status' => false, "message" => $module->l('Nothing here.'));
switch (Tools::getValue('action')) {
case 'action_name':
// Edit default response and do some work here
$response = array('status' => true, "message" => $module->l('It works !'));
break;
default:
break;
}
}
// Classic json response
$json = Tools::jsonEncode($response);
echo $json;
die;
// For displaying like any other use this method to assign and display your template placed in modules/modulename/views/template/front/...
// Just put some vars in your template
// $this->context->smarty->assign(array('var1'=>'value1'));
// $this->setTemplate('template.tpl');
// For sending a template in ajax use this method
// $this->context->smarty->fetch('template.tpl');
}
}
?>
In your Module Hooks, you need to bring access to the route in JS, so we basicaly make a variable :
// In your module PHP
public function hookFooter($params)
{
// Create a link with the good path
$link = new Link;
$parameters = array("action" => "action_name");
$ajax_link = $link->getModuleLink('modulename','controller', $parameters);
Media::addJsDef(array(
"ajax_link" => $ajax_link
));
}
On the frontend side, you just call it like this in a JS file (with jQuery here) :
// ajax_link has been set in hookfooter, this is the best way to do it
$(document).ready(function(){
$.getJSON(ajax_link, {parameter1 : "value"}, function(data) {
if(typeof data.status !== "undefined") {
// Use your new datas here
console.log(data);
}
});
});
And voila, you have your ajax ready to use controller

Set options for the dropdown based on radio button select

I have a form in which contains a dropdown field.The options for the dropdown is based on the radio button selection.
Radio Button
<?php
$list=array("1"=>"Assign to Department","2"=>"Assign to user");
echo $form->field($model, 'option')->radioList($list,
[
'template' => '{input}{label}', // put the label behind
]);
?>
Script
<script>
$('input[type=radio]').click(function(){
var Flag=this.value;
if(Flag=='1') {
'<?php $items= ArrayHelper::map($company->Users, 'id', 'fullname');?>';
} else if(Flag=='2') {
'<?php $items= ArrayHelper::map(Department::find()->all(), 'dep_id', 'name'); ?>';
}
alert(Flag);
});
</script>
Drodown
<?php
echo $form->field($model, 'assignee')
->dropDownList(
$items, // Flat array ('id'=>'label')
['prompt'=>''] // options
)->label('');
?>
Expected response is the change of option values according to the drop down selection.But it is not changing even though the flag value is different for radio buttons and changes on click.
Any ideas?
I have tried this for a sample and it works -
<?php
$items1 = range(0, 5); //PHP Array 1
$items2 = range(5, 10); //PHP Array 2
?>
<script>
var arr1 = <?php echo json_encode($items1); ?>; //Javascript Array 1
var arr2 = <?php echo json_encode($items2); ?>; //Javascript Array 2
$(document).ready(function() {
$('input[type=radio]').click(function(){
var Flag = this.value;
setDropdown(Flag);
});
});
function setDropdown(Flag) {
var elem = $('#Skill_order_no'); //Your dropdown element name.
if(Flag == '1') {
elem.empty();
$.each(arr1, function(index, value) {
elem.append($('<option>').text(value).attr('value', value));
});
} else if(Flag == '2') {
elem.empty();
$.each(arr2, function(index, value) {
elem.append($('<option>').text(value).attr('value', value));
});
}
}
</script>

how to get one of the input textfield value through ajaxbutton

how do i get the user's input value and submit it to ajax then to controller? Right now, in my controller it says that id is an undefined index in $_POST['id']
This input textfield is actually within another form, kind of like a form inside a form.
<?php echo $form->textField($model,'email',array('id'=>'email')); ?>
<?php echo $form->error($model,'email'); ?>
<?php echo CHtml::ajaxButton ( 'Request Code',
CHtml::normalizeUrl(array('site/requestResetCode', 'render'=>true),
array (
'type' => 'POST',
//'data'=> array('id'=> 'js:$("#ResetPasswordForm_email").val()'),
'data'=> array('id'=> 'js:$("#email").val()'),
'success'=>'function(data){
if(data.status == "sent")
bootbox.alert("Code is sent. Please check your email.");
else (data.status == "failed")
bootbox.alert("Request Failure");
}',
'error'=> 'function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}',
)
))
?>
controller:
public function actionRequestResetCode()
{
$id = $_POST['id'];
//stuff..
your POST array is empty because value is not being sent. You need to make a javascript function like
<script type="text/javascript">
function getVal()
{
var value= $("#myEmail").attr('value');
alert(value);
return value;
}
</script>
check if the alert shows correct value then remove this alert statement. If it does not show the value then there is a problem with the id of your textfield.
If you get it working then use it like
'data'=> array('id'=> 'js:getVal()'),

How to Redirects with a Drop Down?

I have parent page and there are two child view _sectionhead.php and _classteacher.php i need to renderPartial to those child view when user select from dropdwon how can do this
this is my create from
IF there is any other way i like to know it.i need quick help
In view:
<?php Yii::app()->clientScript->registerScript('some-name', "
$('select').on('change', function (event) {
var url = $(event.currentTarget).val();
if (url != 0)
$.get(url, function (data) {
$('#result').html(data);
});
});", CClientScript::POS_READY) ?>
<?php echo
CHtml::dropDownList("param", "select here", [
'Select here',
$this->createUrl('/testing/action1') => "Add class teacher",
$this->createUrl('/testing/action2') => "Add class techer"
]) ?>
<div id="result"></div>
Assuming you are doing in HTML ,Add below in HTML code
<option onClick="fnCallPage('classteacher')">class teacher</option>
<option onClick="fnCallPage('Section')">Section</option>
Add below in Javascript tag :
function fnCallPage(param){
//Javascript code for sending
}
Based on #Fraz solution:
HTML:
<option onClick="fnCallPage('_classteacher')">class teacher</option>
<option onClick="fnCallPage('_sectionhead')">Section</option>
<div id="divContainerPartial"></div> <!-- View rendered container -->
Javascript:
function fnCallPage(param){
$.ajax({
url: '<?php echo Yii::app()->createUrl('yourModel/renderPageByAjax');?>/' + param,
type: 'GET',
success: function(html){
$('#divContainerPartial').html(html);
},
error: function(data){
alert('Error loading a '+param+' view.');
}
});
}
Controller:
/**
* #param $view String : View name to render.
*/
public function actionRenderPageByAjax($view)
{
$params = array(); // Variables to view.
$this->renderPartial('//myFolderView/'.$view, array(
'params' => $params,
), false, true);
}

Layout redirect in zend Framework 2

Is it possible to redirect to a route in Layout.phtml in ZF2. I want to redirect to login page if the user is not logged in from layout.phtml
So far i have tried:
<?php $auth = new AuthenticationService();
if ($auth->hasIdentity()) {?>
<li class="active"><a href="<?php echo $this->url('home') ?>">
<?php echo $this->translate('Home') ?></a></li>
<li class="active"><?php echo $this->translate('Logout') ?></li>
<?php
}
else
{
$this->_forward('login/process');
} ?>
its giving me error "get was unable to fetch or create an instance for _forward"
BOOTSTRAP CODE:
public function onBootstrap(MvcEvent $e)
{
$e->getApplication()->getServiceManager()->get('translator');
$eventManager = $e->getApplication()->getEventManager();
$moduleRouteListener = new ModuleRouteListener();
$moduleRouteListener->attach($eventManager);
$eventManager = $e->getApplication()->getEventManager();
//nothing's available for non logged user, so redirect him to login page
$eventManager->attach("dispatch", function($e) {
$match = $e->getRouteMatch();
$list = $this->whitelist;
// Route is whitelisted
$name = $match->getMatchedRouteName();
if (in_array($name, $list)) {
return;
}
$sm = $e->getApplication()->getServiceManager();
$controller = $e->getTarget();
$auth = $sm->get('AuthService');
if (!$auth->hasIdentity() && $e->getRouteMatch()->getMatchedRouteName() !== 'login/process') {
$application = $e->getTarget();
$e->stopPropagation();
$response = $e->getResponse();
$response->setStatusCode(302);
$response->getHeaders()->addHeaderLine('Location', $e->getRouter()->assemble(array(), array('name' => 'login/process')));
//returning response will cause zf2 to stop further dispatch loop
return $response;
}
}, 100);
}
This is not something that you wanna be doing inside your layout.phtml. Typically you want to hook in to an event that happens before the rendering. In ZF2, the earliest event to hook into that kind of stuff, where it makes sense to hook into, would be the route event. A good diagram of the process that's used in the Authorization-Module BjyAuthorize explains it quite well:
If you don't want to use the Module, you can minify what's happening there, too, like this:
//class Module
public function onBootstrap(MvcEvent $mvcEvent)
{
$eventManager = $mvcEvent->getApplication()->getEventManager();
$eventManager->attach(MvcEvent::EVENT_ROUTE, array($this, 'onRoute'), -1000);
}
public function onRoute(MvcEvent $event)
{
$serviceLocator = $mvcEvent->getApplication()->getServiceLocator();
// From this point onwards you have access to the ServiceLocator and can check
// for an authenticated user and if the user is not logged in, you return a
// Response object with the appropriate ResponseCode redirected and that's it :)
}