give two function in one button in Yii framework - javascript

I have a question about Yii framework, i have problem with submit button, i want to given two fungsi save and update in one submit button, can anyone tell me how to set that function on form ?
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
</div>
i change 'Save' with 'Update' it's still have error Primary key added, how i can create two function update and save in one push button ?
public function actionCreate()
{
$model=new TblUasUts;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['TblUasUts']))
{
$model->attributes=$_POST['TblUasUts'];
if($model->save())
$this->redirect(array('view','id'=>$model->nim_mhs));
}
if(isset($_POST['TblUasUts'])
{
$model->attributes=$_POST['TblUasUts'];
if($model->update())
$this->redirect(array('view','id'=>$model->nim_mhs));
}
$this->render('update',array(
'model'=>$model,
));
}

In your form, you can use something like :
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Update'); ?>
</div>
As far as processing different actions on the backend code, there are a few options, for example, you could :-
Direct your form to different URLs
Set a (hidden) field (for example ID) and parse for that.
Use the default action from the activeForm, which directs back to the invoking action, for example actionCreate(), or actionUpdate()
In light of your updates, please extend your controller as per my initial suggestion to have another action actionUpdate()
The main difference between the actionCreate(), or actionUpdate() actions is that the Create action create a new (empty) TblUasUts object, while the Update action populates the TblUasUts object from the database.
public function actionCreate()
{
$model=new TblUasUts;
...
... Do things with $model ...
...
$model->save();
}
public function actionUpdate
{
// The id of the existing entry is passed in the url. for example
// ...http:// .... /update/id/10
//
$model = TblUasUts::model()->findByPK($_GET['id']);
...
... Do things with $model ...
...
$model->save();
}

Related

alpine component fails to execute on livewire update

I have an alpine.js component with livewire data save. https://github.com/TerrePorter/CustomCountrySelectBox.git
I am trying to load two and eventually three of these in sequence on the page. First, the country then when that is selected, I update the state/region, and finally when that is updated I update the city.
The problem is when I update the state/region the alpine.js code does not execute when livewire refreshed that part of the page.
I also tried to make it work all on one page, a select box that updates the next select box, but it would always fail to load the second array.
Here is the relevant part of the template
<div class="p-6">
<lable>Please select your location: </lable>
#if ($country == '')
#component('components.country-select-box', ['countryJson' => $countryJson])#endcomponent
#endif
#if ($stateJson != '')
#component('components.state-select-box', ['stateJson' => $stateJson])#endcomponent
#endif
</div>
Here is part of the livewire code where I update the state's JSON file.
public function updatedCountry() {
$this->stateJson = $this->getStateJson();
}
public function getStateJson() {
$r = Countries::where('short_name', '=', $this->country)->with('states')->first();
$ret = [];
foreach ($r->states as $index => $item) {
$ret[] = ['title' => $item->state_name, 'value' => $item->id];
}
return json_encode($ret);
}
And finally as mentioned before this is the select box dropdown I am using, https://github.com/TerrePorter/CustomCountrySelectBox.git

How to run a script when a user authenticates Laravel?

I would like to know how to run a function when a user authenticates,
This is my function for log
public function redirectPath()
{
if (Auth::user()->hasRole('admin')){
$bitacora = TblBitacora::create([
'accion' => 'Inicio de SesiĆ³n Admin Exitoso',
'user_id' => Auth::id(),
'ip' => \Request::ip(),
]);
return '/';
}
}
I would like to run this script
#if(Auth::user()->??????????????????????????????????????????
<script>
$(function() {
$('#mostrarmodal').modal('show');
});
</script>
#endif
Laravel has Authentication Directives
The #auth and #guest directives may be used to quickly determine if
the current user is authenticated or is a guest:
#auth
// The user is authenticated...
#endauth
#guest
// The user is not authenticated...
#endguest
More information available at https://laravel.com/docs/5.8/blade
Also I wouldn't recommend to log in redirectPath method in your controller. You can use events, an similar to what you want to achieve is provided as an example on Laravel docs. https://laravel.com/docs/5.7/events#event-subscribers
First Question Answer :
You can check is user login in your blade file and add javascript or something like this in your view file :
#if(\Auth::check())
<script>
$(function() {
$('#mostrarmodal').modal('show');
});
</script>
#endif
If Authenticate user is an Admin
#if (auth()->check())
#if (auth()->user()->Admin())
// Put your js files here
#else
// this is for others role
#endif
#endif
Second Question Answer :
If you want to run a function if user is authenticate then you can do it like that :
public function check() {
if(Auth::check()){
$this->secondFunc(); // This will run if user is authenticate.
}
else{
return redirect('auth/login');
}
}
public function secondFunc() {
echo "This is second function";
}
You can use JS localStorage to help you to do it:
#if(\Auth::check())
<script>
if (localStorage.getItem('already_connected') !== '1') {
$('#mostrarmodal').modal('show');
localStorage.setItem('already_connected', 1);
}
</script>
#endif
Now, if you refresh the page, unless you clear localStorage data, it will not show
run this function again.
Hope it helps.

How to invoke my post method when I'm changing dropdown list in ASP.NET MVC

I'm very new to MVC and Javascript so please be patient with me, I'm working on small application and I came to part when I need to select something from dropdown list and based on that selection I need to redirect user to another View, I also need to determine somehow where I should redirect user, so that is reason why I tried to pass parameter also ( database ID to my post method) but unfortunatelly this is not working, in section below I will post my code:
Method which is sending data to my DropDownList :
public ActionResult ShowArticleGroup()
{
List<ArticleGroup> articlesGroups = GroupsController.GetAllGroups();
ViewBag.articlesGroups = articlesGroups;
return View(articlesGroups);
}
[HttpPost]
public ActionResult ShowArticleGroup(string id)
{
//Here I wanted to take ID of selected Group and because there will be allways 3 Groups I can do if else and Redirect by ID
if(id =="00000000-0000-0000-0000-000000000002")
{
return RedirectToAction("Create","Article");
}
return RedirectToAction("Create", "Article");
}
And my VIEW - there is only one control on the view : just one dropdown, and based on selection I should be redirected to another view, and I wanted here to take ID of selected group and by that I wanted to redirect user to appropiate view:
#model IEnumerable<Model.ArticleGroup>
#{
ViewBag.Title = "Add new article";
}
<h3 style="text-align:center">Choose article group</h3>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true)
<div class="form-group" style="text-align:center">
#Html.DropDownList("Group", new SelectList(ViewBag.articlesGroups, "GroupID", "GroupTitle.Name"), null, new { onchange = "document.location.href = '/Articles/ShowArticleGroup/' + this.options[this.selectedIndex].value;" })
</div>
</div>
}
First of all, usage of location.href on DropDownList seems wrong here:
#Html.DropDownList("Group", new SelectList(ViewBag.articlesGroups, "GroupID", "GroupTitle.Name"), null,
new { onchange = "document.location.href = '/Articles/ShowArticleGroup/' + this.options[this.selectedIndex].value;" })
AFAIK, location.href used for redirect to another page using HTTP GET, hence it will try to call first ShowArticleGroup action method without parameter, and the URL parameter simply ignored since given URL parameter only exist in POST.
To submit the form with DropDownList, you need to handle change event triggering POST into controller action method:
jQuery
<script type="text/javascript">
$(document).ready(function() {
$("#Group").change(function() {
var groupId = $("#Group").val();
$.post('#Url.Action("ShowArticleGroup", "ControllerName")', { id: groupId }, function (response, status) {
// response handling (optional)
});
});
});
</script>
DropDownList
#Html.DropDownList("Group", new SelectList(ViewBag.articlesGroups, "GroupID", "GroupTitle.Name"), null)
I recommend you using strongly-typed DropDownListFor with binding to a viewmodel approach if you want to pass viewmodel contents during form submit.
NB: $.post is shorthand version of $.ajax which uses POST submit method as default.
Related issues:
Autopost back in mvc drop down list
MVC 4 postback on Dropdownlist change

Add Dynamic JS Code on Magento Product Page

On my magento product page I need to add a dynamic JavaScript array base on display upselling products on the product page. The goal is to change the images of the upselling products when the user change the color of the main product.
To achieve my goal I need a custom JavaScript array on every product page that give me information about crossselling product and the associated product image.
What is the best way to do this?
I try this
add a observer event in my config.xml
<controller_action_layout_load_before>
<observers>
<crossselling_product_view>
<type>singleton</type>
<class>XXXXXXXX_Crossselling_Model_Observer</class>
<method>productview</method>
</crossselling_product_view>
</observers>
</controller_action_layout_load_before>
add observer to add specific JS Code
<?php
class XXXXXXXX_Crossselling_Model_Observer {
public function productview(Varien_Event_Observer $observer) {
$product = Mage::registry('current_product');
//only on product page
if (!($product instanceof Mage_Catalog_Model_Product)) {
return;
}
$controller = $observer->getAction();
$layout = $controller->getLayout();
$block = $layout->createBlock('core/text');
$block->setText(
'<script type="text/javascript">
function main_pulsestorm_hellojavascript()
{
alert("Foo");
}
main_pulsestorm_hellojavascript();
</script>'
);
$layout->getBlock('head')->append($block);
}
}
My error:
Fatal error: Call to a member function append() on a non-object
What is my problem and is it the right way to add dynamic js code?
I would probably approach this from a different angle. Since you are only interested in interacting with data and output for the upsell block, you could change the behavior of just that block by observing its output and appending your extra JavaScript. For the purposes of brevity this answer assumes that you understand the basics of Magento extensions.
Observe the core_block_abstract_to_html_after event:
etc/config.xml
<core_block_abstract_to_html_after>
<observers>
<addCustomUpsellFormat>
<class>XXXXXXXX_Crossselling_Model_Observer</class>
<method>addCustomUpsellFormat</method>
</addCustomUpsellFormat>
</observers>
</core_block_abstract_to_html_after>
Act upon instances of Mage_Catalog_Block_Product_List_Upsell by appending the output of a new block that will read their data:
Model/Observer.php
public function addCustomUpsellFormat(Varien_Event_Observer $observer)
{
/* #var Mage_Core_Block_Abstract $block */
$block = $observer->getBlock();
if ($block instanceof Mage_Catalog_Block_Product_List_Upsell) {
/* #var Varien_Object $transport */
$transport = $observer->getTransport();
// Receive the standard output for the block.
$output = $transport->getHtml();
/* #var Mage_Core_Model_Layout $layout */
$layout = $block->getLayout();
$json = $layout->createBlock('core/template')
->setTemplate('catalog/product/list/upsell_json.phtml')
->setItems($block->getItems())
->toHtml();
// Append new JSON data to block output.
$transport->setHtml($output . $json);
}
return $this;
}
Create a template that interprets the upsell data and outputs it in your desired way, in my example above I created a template that could do something like this (my example creates a new template, so it should go into the base theme):
app/design/frontend/base/default/template/catalog/product/list/upsell_json.phtml
<?php
$_json = array(); // Add data in here to convert to JSON for output.
$_items = $this->getItems();
/* #var Mage_Catalog_Model_Product $_product */
foreach ($_items as $_product) {
$_json[$_product->getId()] = array(
'image' => (string)Mage::helper('catalog/image')->init($_product, 'image')
);
}
?>
<script type="text/javascript">var upsellData = <?php echo json_encode($_json) ?>;</script>
Use
$controller = $observer->getEvent()->getAction();
instead of
$controller = $observer->getAction();

kendo ui widget doesn't work in partial view after post-back

I load a partial view into kendo-ui window widget via jquery ajax , and no problem ,
public ActionResult Create()
{
return PartialView("_Create");
}
public ActionResult Create(CreateObjectViewModel viewModel)
{
if(ModelState.IsValid)
{
//Persist to database ...
return Json(new {success=true});
}
return PartialView("_Create",viewModel);
}
All kendo ui widgets works fine , after submitting the form , client-side validation works fine too .
But if there is a server side validation error , I will return modelstate to the partial view and the view shows the errors .
In this case all my widget loose their functionality and do not work ,
here is how i submit the form in partial view :
#using(Html.BeginForm())
{
#* all kendo ui widget and form element *#
<input type="submit" id="insert" onclick(submitForm(this.id)" value="insert" />
}
<script type="text/javascript>
$(documet).ready(function(){
rebindvalidation();
}
function rebindValidation(){
var form =$('form');
form.removeData('validator');
form.removeData('unobtrusiveValidation');
$.validator.unobtrusive.parse(form);
}
function submitForm(e){
$('form').submit(function(){
$.ajax({
url:this.action,
type:this.method,
data:$(this).serialize(),
success:function(result){
if(result.success){
$("#window").data('kendoWindow').close()
}else{
$('form').html(result);
rebindValidation();
}
}
});
</script>
When I say it loose their functionality , Imagin the the multiselect widget behave just like a normal textbox , while it work at first load till not submitted to the controller:
#(Html.Kendo().MultiselectFor(p=>p.PartyIds)
.Name("PartyIds").DataTextField("Title").DataValueField("Id")
.Filter(FilterType.Contains)
.DataSource(s=>s.read(r=>r.Action("SearchAllPerson","Party"))
.Data("getPartyIdsData")
s.ServerFiltering(true))
I'm wondering how could I fix this problem.
I found my mistake , In partial view after postback , I set the result to the form element , while It's correct to set to the window .
By another word instead of
else{
$('form').html(result);
rebindValidation();
}
would be correct to write like this :
else{
$('#window').html(result);
rebindValidation();
}

Categories