working on it ...

Filters

Explore Public Snippets

Sort by

Found 5,233 snippets matching: controller

    public by ColbyDavis  160582  0  3  0

    Mojolicious::Controller using CGI::Expand

    Mojolicious::Controller using CGI::Expand: Perl: Mojolicious
    use Mojo::Base 'Mojolicious';
    use CGI::Expand;
    
    sub startup
    {
       my $self = shift;
       $self->hook(before_dispatch => sub {
            my $c = shift;
            my $hash = CGI::Expand->expand_hash($c->req->params->to_hash);
            $c->param($_ => $hash->{$_}) for keys %$hash;
        });
    }
    
    

    public by JKCPR  8760  1  5  1

    AngularJS 'Ctrl as vm' pattern

    Within controller use 'var varname' if it is only needed internally, anything which needs to be bound to the ViewModel uses 'vm.varname' because in 'Controller as vm' pattern you forego using $scope to bind to the ViewModel and instead use the vm.object instead. Sometimes $scope is necessary but less so using this pattern....vm is readable and conv
    // AngularJS 'Controller As vm' pattern
    <script>
    (function(){
      "use strict";
    
      var app = angular.module('app')
        .controller('Customers', [function() {
          var vm = this; //this is implicitly bound to controller's scope
      
          vm.title = 'Customers';
          vm.customers = [
            {name: 'Haley'}, {name: 'Ella'}, {name: 'Landon'}, {name: 'John'}
            ];
        }])
        .controller('Shells', [function() {
          var vm = this; //this need not be named identically as in HTML
      
          vm.title = 'Shells';
          vm.shells = [
            {name: 'Main Shells'}, {name:'Half Shells'},{name: 'Quarter Shells'}
          ];
        }]);
    })();
    </script>
    
    <div ng-controller="Shell as shellVm">
      <h1>{{  shellVm.title }}</h1>
      <article ng-controller="Customers as customersVm">
        <h2> {{ customersVm.title }} in </h2>
        <ul ng-repeat="c in customersVm.customers">
          <li>{{ c.name }}</li>
        </ul>
      </article>
    </div>

    public by sTiLL-iLL @ SniPitz-KND  5139  4  9  42

    Vanilla KemPlates... MVC in stiches....

    real kwik model view controller example made with 100% vanilla JS
    
    ///  MY "SIGNALS" EVENT SYSTEM ////////////////
    
    //   this solution Uses my signals.js module
    
    ////////  styles  ///////////
    
    
    body {
    	font-family: Calibri;
    	width: 220px;
    }
    
    .container {
        border: 1px solid black;
        padding: 10px;
        width: 232px;
        margin: 50px auto 50px 350px;
    	border-radius: 7px;
    	background: lightgray;
    }
    
    fieldset {
    	width: 205px;
    	margin: 0 auto 3px 3px;
    	margin-right: auto;
    	margin-bottom: 6px;
    	padding: 10px;
    }
    
    h1 {
    	margin-left: 55px;
    	margin-right: auto;
    }
    
    span {
    	margin: 3px;
    }
    
    input {
    	margin-top: 2px;
    	margin-bottom: 8px;
    	width: 168px;
    	padding-left: 3px;
    }
    
    ul {
    	padding-left: 20px;
    	list-style: none;
    	color: navy;
    	overflow-x: hidden;
    }
    
    li {
    	max-width: 180px
    }
    
    
    
    /////////  Model(s)   ////////////////////////
    
    // this is the user model object
    
    var user1 = {
        name1: "Richard",
        name2: "Longwood",
        occupation: "Software Engineer",
        age: "40",
        title: 'Skillz Yo!',
        subTitle: "add a skill...",
        showSkills: true,
        skills: []
    };
    
    
    
    function UserModel (usr) {
        this.user = usr;
        this.get = function(k) {
            if (k) {
                var u = this.user;
                return u[k];
            } 
            else {
                var u = this.user;
                return u;
            }
        };
    };
    
    
    
    var User = new UserModel (user1);
    User.prototype = Signals;
    User.constructor = User;
    
    User.on = function(v, cbk) {
        this.prototype.receive(v, function(d) {
            cbk.call(this.user, d);
        });
    };
    User.emit = function(v) {
        this.prototype.signal("change", v);
    };
    User.off = function(v) {
        this.prototype.dropReceivers(v);
    };
    User.set = function(k, v) {
        if (v && v !== this.user[k]) {
            if (k == "skills") {
                this.user[k].push(v);
            } else {
                this.user[k] = v;
            }
            this.prototype.signal("change", this.user);
        }
    };
    
    
    
    // array for template strings, 
    // our template engine, and an array of target Ids.
    
    var kList = [], 
        TPE = new TPEngine(), 
        Nodz = ["t1", "t2", "t3", "t4", "t5", "t6"];
    
    
    
    // this template string is pretty bulky, 
    // so Ill keep it stashed as a string, 
    // then inject it into its target when its time.
    
    var template6 = '~>{ if(User.get("showSkills")) { :}' + 
            '~>{ for(var index in User.get("skills")) { :}' + 
            '<li><a href="#"> ~>{ User.get("skills")[index] :}' + 
            '</a></li> ~>{ } :}' + '~>{ } else { :}' + 
            '<li>none</li>' + '~>{ } :}';
    
    
    
    // this array holds the template strings.
    // the innerText is where I extract them from the mark-up
    // notice how #5 is already defined
    
    var Templates = [
        template1 = t1.innerText, 
        template2 = t2.innerText, 
        template3 = t3.innerText, 
        template4 = t4.innerText,
        template5 = t5.innerText, 
        template6
    ];
    
    
    // Now I iterate over the list of nodes and templates,
    // pull each one out per the array position and plug
    // them into the kompiler along with the property of the node that 
    // the content is assigned to, then komile into a "kPlate" template.
    // each one of these kPlates is then put into another array: "kList"
    
    Nodz.forEach(function(tmpltNd) {
        var seed = Templates.shift();
        kPlt = TPE.Template(tmpltNd, "innerHTML", seed);
        kList.push(kPlt);
    });
    
    
    
    // Here, we set up the 2-way bindings
    
    var bb = document.getElementById("btn"), 
        tgl = document.getElementById("tgl"),
        updateDom = function (d) {
            kList.forEach(function(itm) {
                TPE.BindSet(itm, d);
            });
        },
        updateModel = function (d) {
            User.set("skills", tgl.value);
            tgl.value = "";
        };
    
    
    // When the button is pressed, this handler
    // in the controller hears it, grabs the new value
    // and updates the model.
    
    bb.addEventListener("click", updateModel);
    
    
    // When the model's value is changed, it fires a change event.
    // The handler here in the controller hears it,
    // grabs the new value, and then updates the dom
     
    User.on("change", updateDom);
    
    
    // This part basicly is what runs on window ready.
    // Now that everything is all set up..
    // we iterate over the array of kPlates that we stored earlier,
    // calling BindSet on each one. This renders the mark-up
    // to the dom at lightening speed, and there ya go!
    
    kList.forEach(function(itm) {
        TPE.BindSet(itm, User);
    });
    
    
    
    
    
    
    //////////// Template kompiler (controller)  //////////////////////////////////////
    
    this.TPEngine = function() {
        var kompiler = function(templateString, model) {
            var rgx = /~>{([^:]+)?:}/g, 
            rgex = /(^( )?(if|for|else|switch|case|break|{|}))(.*)?/g, 
            segment = 'var r=[];\n', position = 0, 
            kompile = function(chunk, ixjs) {
                ixjs ? (segment += chunk.match(rgex) ? chunk + '\n' : 'r.push(' + chunk + ');\n') : 
                (segment += chunk != '' ? 'r.push("' + chunk.replace(/"/g, '\\"') + '");\n' : '');
                return kompile;
            };
            while (match = rgx.exec(templateString)) {
                kompile(templateString.slice(position, match.index))(match[1], true);
                position = (match.index + match[0].length);
            }
            ;
            kompile(templateString.substr(position, templateString.length - position));
            segment += 'return r.join("");';
            return new Function(segment.replace(/[\r\t\n]/g, '')).apply(model);
        }, 
        template = function(elementID, prop, templateString) {
            var c = {
                tStr: templateString,
                tProp: prop,
                tVal: document.getElementById(elementID)
            };
            return c;
        }, 
        applyBind = function(temp, model) {
            if (temp.tVal.id && temp.tStr && model) {
                template = temp;
                var el = document.getElementById(template.tVal.id);
                el[template.tProp] = kompiler(template.tStr, model);
                template.tVal = el;
            }
        };
        return {
            Template: template,
            BindSet: applyBind
        };
    };
    
    
    ///////// VIEW  //////////////////////////
    
    <!DOCTYPE html>
    <html>
    <head>
    	<title>MY MVC</title>
    </head>
      	<meta charset="utf-8" />
    	<link rel="stylesheet" href="css/stylz.css" />
    	<script src="js/signals.js"></script>
    	<script src="js/myTPlates.js"></script>
    <body>
    	<div class="container">
    		<h1 id="t1">
    			~>{ User.get("title") :} 
    		</h1>
    		<fieldset>
    			<legend id="t2">
    				~>{ User.get("subTitle") :}
    			</legend>
    			<input id="tgl" type="text" placeholder="skills"></input>
            	<button id="btn">+</button>
    			<hr><b>
    			  Name:
    			  <span id="t3">
    					~>{ User.get("name1") +" "+ User.get("name2") :}
    			  </span>
    			  </br>
    			  Age: 
    			  <span id="t4">
    					~>{ User.get("age") :}
    			 </span>
    			 </br>
    			  Dept: 
    			  <span id="t5">
    					~>{ User.get("occupation") :}
    			 </span>
    			 <hr>
    			  Skills List: 
    			 <ul id="t6">
    					~>{ User.get("skills") :}
    			 </ul></b>	
    			<hr>
    		</fieldset>
    	</div>
    </body>
    <script src="js/script1.js"></script>
    </html>
    
    
                                                                                                                

    public by addicttux  11296  1  5  0

    Controller Template

    Template para el controller con CRUD
    # Controla el CRUD
    #
    # Por convencionalismo se omiten los métodos +index+, +new+, +update+. Ver nota sobre convencionalismos en +application_controller.rb+
    #
    # El método +update+ es un alias de +create+ debido a *DRYtizar* el código
    #
    # Se aplican 7 métodos +before_action+ como consecuencia de *DRYtizar* el código, los cuales son *privados*
    class NombreDeLaTablaEnSingularsController < ApplicationController
    
      before_action :authenticate_user!
      before_action :set_nombre_de_la_tabla_en_singular, only: [:edit, :update, :destroy, :confirmar_borrar]
      before_action :new_nombre_de_la_tabla_en_singular, only: [:new, :create]
      before_action :crear_breadcrum, only: [:index,:new,:edit]
      before_action :asginar_captura, only: [:create,:update]
      before_action :asgina_current_user, only: [ :update, :destroy ]
      before_action :genera_listado, only: :index
    
      # Evitamos que en producción se vea un 404, redirigiendo culaquier petición a una página inexistente al index
      unless Rails.env.development?
        rescue_from ActionView::MissingTemplate do
          redirect_to nombre_de_la_tabla_en_singulars_path, status: 303
        end
      end
    
      # Lo guarda en la base de datos.
      #
      # @note Hacemos uso del método del mismo nombre definido en <tt>application_controller.rb</tt>
      def create
        super  @nombre_de_la_tabla_en_singular
      end
    
      alias_method :update, :create
    
      # Lo elimina de la base de datos
      #
      # @note Hacemos uso del método del mismo nombre definido en <tt>application_controller.rb</tt>
      def destroy
        super @nombre_de_la_tabla_en_singular
      end
    
      # Genera el reporte en PDF
      #
      # @note Hacemos uso del método del mismo nombre definido en <tt>application_controller.rb</tt>
      def listado_pdf
        super NombreDeLaTablaEnSingularPdf.new( NombreDeLaTablaEnSingular.all.order(:campo_ordenado), view_context )
      end
    
      private
    
      # Este método se utiliza para asignar cada valor capturado a su contraparte en la instancia de la base de datos.
      # <b>Hacemos esto para evitar un ataque de inyección de SQL</b>
      def asginar_captura
        @nombre_de_la_tabla_en_singular.campo_ordenado = params[:nombre_de_la_tabla_en_singular][:campo_ordenado]
        @nombre_de_la_tabla_en_singular.campo_segundo  = params[:nombre_de_la_tabla_en_singular][:campo_segundo]
        @nombre_de_la_tabla_en_singular.solo_root_ns   = params[:nombre_de_la_tabla_en_singular][:solo_root_ns]
      end
    
      # Genera el breadcrum, pasamos la ruta a +index+
      #
      # @note Hacemos uso del método del mismo nombre definido en <tt>application_controller.rb</tt>
      def crear_breadcrum
        super nombre_de_la_tabla_en_singulars_path
      end
    
      # Crea una nueva instancia del objeto
      def new_nombre_de_la_tabla_en_singular
        @nombre_de_la_tabla_en_singular = NombreDeLaTablaEnSingular.new
      end
    
      # Obtiene los datos desde la base de datos
      def set_nombre_de_la_tabla_en_singular
        @nombre_de_la_tabla_en_singular = NombreDeLaTablaEnSingular.find(params[:id])
      end
    
      # Genera el listado. Este método es llamado tanto de forma directa como en el filtro +before_action+
      def genera_listado
        @nombre_de_la_tabla_en_singulars = initialize_grid NombreDeLaTablaEnSingular,
                                              order: 'nombre_de_la_tabla_en_singulars.campo_ordenado',
                                              order_direction: 'desc',
                                              per_page: 10
      end
    
      # Asigna el usuario actual a una variable de instancia a fin de pasen los tests
      def asgina_current_user
        @nombre_de_la_tabla_en_singular.usuario_actual = current_user
      end
    
    end            

    public by shebin512  5121  1  8  1

    Magento get current controller ,current module , current action and route name

    Magento get current controller ,current module , current action and route name
    <?php
    
    /*
     *Magento get current controller ,current module , current action and route name
     */
    
    //1 . controller name
    Mage::app()->getRequest()->getControllerName();// will return controller name
    
    //2. action name
    Mage::app()->getRequest()->getActionName();//will return action name
    
    //3. module name
    Mage::app()->getRequest()->getModuleName();// will return module name
    
    //4. routes name
    Mage::app()->getRequest()->getRouteName();//will return routes name            

    public by wassim  3171  0  4  0

    IOS root view controller exception

    Application windows are expected to have a root view controller at the end of application launch
    Application windows are expected to have a root view controller at the end of application launch 
    //you have to add this code to your appdelegate didfinishlaunching
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor clearColor];
    [self.window makeKeyAndVisible];
    ViewController *cont = [[ViewController alloc]init];
    [self.window setRootViewController:cont];ed.

    public by nsssim  1894  7  5  0

    calling a controller from another controller in codeigniter - no hmvc- Nassim baci

    calling a controller from another controller in codeigniter - no hmvc- we ll need Request library http://requests.ryanmccue.info/
    $this->load->library('PHPRequests');
    $this->load->helper("url");
    $response_url = base_url()."controller/method";
    $response_str = Requests::get($response_url);
    echo($response_str->body);
    $json_data = json_decode($response_str->body);

    public by vivi7  2581  0  4  0

    Back navigation controller code

    navigationController?.popViewControllerAnimated(true)

    public by passh  2092  1  6  0

    Obtain GET or POST values from CONTROLLER

    class loginController extends Controller
    {
        function loginAction(Request $Request, String $user)
        {
            
           dump(        $Request->query->get('fooget')      ); 
           dump(        $Request->get('barpost')        );
           dump(        $Request                            );
           
            die ();
                    
        }
    }            

    public by cyberrspiritt  1701  0  6  0

    Codeigniter Sample Controller

    Simple codeigniter controller initialization
    <?php
    defined('BASEPATH') OR exit('No direct script access allowed');
    
    class Controllername extends CI_Controller {
    
        function __construct(){
             parent::__constrcut();
        }
    
    	public function index()
    	{
    		
    	}
    
    }
    
    /* End of file controllername.php */
    /* Location: ./application/controllers/controllername.php */
    • Public Snippets
    • Channels Snippets