Kode Program Menu Utama Android

  Lampiran 1

  activity_login.xml

  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/LinearLayout1" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".LoginActivity" > <TextView android:id="@+id/login_text" android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center" android:text="@string/log_in" android:textSize="20sp" /> <EditText android:id="@+id/usernm" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:gravity="center" android:hint="@string/str_username" /> <EditText android:id="@+id/passwd" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:gravity="center" android:hint="@string/str_password" android:inputType="textPassword" /> <CheckBox android:id="@+id/chk_remember" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/remember" /> <Button android:id="@+id/btn_login" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/login" /> <TextView android:id="@+id/txt_error" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="" />

  </LinearLayout>

  Lampiran 2

  Kode Program Menu Utama Android

  package com.ami.warungmbakami; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.actionbarsherlock.app.SherlockActivity; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; import com.ami.warungmbakami.resource.JSONParser; import com.ami.warungmbakami.resource.UserFunctions; import com.ami.warungmbakami.utils.DatabaseHandler; import android.os.Bundle; import android.os.StrictMode; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.view.ContextMenu; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; public class MainActivity extends SherlockActivity implements OnItemClickListener{ private ListView list; private SharedPreferences pref; private Editor editor; private String host; private String url; // JSON Node names private final String TAG_DETAIL = "detail"; private final String TAG_NAME = "nama_meja"; private final String TAG_SELECTED = "selected_tag"; private String TIPE_PEMESANAN; private DatabaseHandler db;

  UserFunctions userFunctions; JSONArray detail, selectedTag = null;

  @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); userFunctions = new

  UserFunctions(getApplicationContext()); db = userFunctions.getDbHandler(); this.host = "http://"+db.getHost(); this.url = host + "/warungmbakami/index.php?r="; StrictMode.ThreadPolicy policy = new

  StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); pref = getApplicationContext().getSharedPreferences("mbakami",

  0); // 0 - for private mode editor = pref.edit(); if(!userFunctions.isUserLoggedIn()){

  // user is not logged in show login screen Intent login = new Intent(getApplicationContext(), LoginActivity.class); login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(login); // Closing dashboard screen finish();

  } else { setContentView(R.layout.activity_main); list = (ListView)findViewById(R.id.list_main); String[] items = getResources().getStringArray(R.array.menu_utama); list.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_single_choice, items)); list.setChoiceMode(ListView.CHOICE_MODE_SINGLE); list.setOnItemClickListener(this); registerForContextMenu(list);

  } }

  @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { String newURL = url+"meja/daftarmeja&param="+TIPE_PEMESANAN;

  JSONParser parser = new JSONParser(newURL); JSONObject json = parser.getJSONfromURL(); detail = json.optJSONArray(TAG_DETAIL); if(detail != null) { for(int i = 0; i < detail.length(); i++){ try {

  JSONObject c = detail.getJSONObject(i); // Storing each json item in variable String name = c.getString(TAG_NAME); menu.add(name);

  } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace();

  } }

  } }

  @Override public boolean onContextItemSelected(android.view.MenuItem item) { long orderID = -1; String namaMeja = item.toString(); if(TIPE_PEMESANAN.equals("baru")){ orderID = db.createOrderData(namaMeja); editor.putLong("orderID", orderID);

  Intent menuList = new Intent(getApplicationContext(), ListAllMenuActivity.class); menuList.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(menuList); } else if(TIPE_PEMESANAN.equals("update")){

  String newURL = url+"penjualan/deviceupdate&meja="+namaMeja; JSONParser parser = new JSONParser(newURL); JSONObject json = parser.getJSONfromURL(); try { selectedTag = json.getJSONArray(TAG_SELECTED); if(selectedTag != null) { for(int i = 0; i < selectedTag.length(); i++){

  JSONObject c = selectedTag.getJSONObject(i); String name = c.getString("name"); int amount = c.getInt("amount"); editor.putBoolean(name, true); editor.putString("namaMeja", namaMeja); editor.putInt("amount_"+name, amount);

  } }

  Intent menuList = new Intent(getApplicationContext(), ListAllMenuActivity.class); menuList.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(menuList);

  } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace();

  } } else if(TIPE_PEMESANAN.equals("detail")){ editor.putString("namaMeja", namaMeja);

  Intent detail = new Intent(getApplicationContext(), DetailPejualanActivity.class); detail.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(detail);

  } editor.putString("tipe", TIPE_PEMESANAN); editor.commit(); return true; }

  @Override public boolean onCreateOptionsMenu(Menu menu) { getSupportMenuInflater().inflate(R.menu.main, menu); menu.add("Save") .setIcon(R.drawable.abs__ic_cab_done_holo_light) .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM); menu.add("Logout") .setIcon(R.drawable.ic_tab_logout_unselected) .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM); return true;

  } @Override public boolean onOptionsItemSelected(MenuItem item) {

  //This uses the imported MenuItem from ActionBarSherlock String clickedId = item.getTitle().toString(); if(clickedId.equals("Save")){

  Toast.makeText(this.getApplicationContext(), "Clicked "+clickedId, Toast.LENGTH_SHORT).show(); } else if(clickedId.equals("Logout")){ userFunctions.logoutUser(); editor.clear(); editor.commit(); Intent login = new Intent(getApplicationContext(), LoginActivity.class); login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(login); finish(); } else if(item.getTitle().toString().equals("Settings")){ Intent settings = new Intent(getApplicationContext(), SettingsActivity.class); // Close all views before launching Dashboard settings.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(settings); } return true; }

  @Override public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {

  // TODO Auto-generated method stub if(id == 0){ this.TIPE_PEMESANAN = "baru";

  } else if(id == 1) { this.TIPE_PEMESANAN = "update"; } else if(id == 2){ this.TIPE_PEMESANAN = "detail"; } view.showContextMenu();

  } } Lampiran 3

  activity_makanan.xml

  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/LinearLayout1" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MakananListActivity" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:padding="15dip" android:text="@string/menu_makanan" android:textSize="18sp" /> <ListView android:id="@+id/list_makanan" android:layout_width="fill_parent" android:layout_height="0dip" android:layout_weight="0.71" android:divider="#b5b5b5" android:dividerHeight="1dp" android:entries="@array/data_makanan" android:listSelector="@drawable/list_selector" /> </LinearLayout>

  makanan_row.xml

  <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/makanan_layout" android:layout_width="fill_parent" android:layout_height="match_parent" android:background="@drawable/list_selector" android:orientation="horizontal" android:padding="5dip" > <LinearLayout android:id="@+id/mkn_linear" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:background="@drawable/gradient_bg" android:orientation="vertical" android:padding="3dip" > <ImageView android:id="@+id/image_makanan" android:layout_width="50dip" android:layout_height="50dip" android:maxHeight="50dp" android:maxWidth="50dp" android:src="@drawable/makanan_normal" /> </LinearLayout> <TextView android:id="@+id/nm_makanan" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignTop="@+id/mkn_linear" android:layout_marginLeft="55dp" android:layout_marginTop="10dp" android:layout_toRightOf="@+id/mkn_linear" android:text="Nama Makanan" android:textSize="15sp" /> <TextView android:id="@+id/harga" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/nm_makanan" android:layout_below="@+id/nm_makanan" android:text="Harga" /> <CheckBox android:id="@+id/chk_makanan" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_marginRight="10dp" android:layout_alignParentTop="true" /> </RelativeLayout>

  ListMenuAdapter.java

  package com.ami.warungmbakami.resource; import java.util.ArrayList; import java.util.HashMap; import com.ami.warungmbakami.DessertListActivity; import com.ami.warungmbakami.MakananListActivity; import com.ami.warungmbakami.MinumanListActivity; import com.ami.warungmbakami.R; import com.ami.warungmbakami.utils.Utils; import android.app.Activity; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.Toast; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.ImageView; import android.widget.TextView; public class ListMenuAdapter extends BaseAdapter { private String TYPE; //makanan, minuman, dessert private Activity activity; private ArrayList<HashMap<String, String>> data; private static LayoutInflater inflater=null; public ImageLoader imageLoader; private SharedPreferences pref; private Editor editor; //private DatabaseHandler db; private Dialog dialog; private TextView txtNamaMenu; private EditText inputJumlah; private Button btnOK; private CheckBox chk; private TextView nama; private TextView harga; private ImageView thumb_image; public ListMenuAdapter(String TYPE, Activity a, ArrayList<HashMap<String, String>> d){ activity = a; data = d; inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SER

  VICE); imageLoader=new ImageLoader(activity.getApplicationContext()); pref = activity.getApplicationContext().getSharedPreferences("mbakami", 0); // 0 - for private mode editor = pref.edit(); this.TYPE = TYPE; //db = new DatabaseHandler(activity); } public ListMenuAdapter(String TYPE, Fragment f, ArrayList<HashMap<String, String>> d){ activity = f.getActivity(); data = d; inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SER

  VICE); imageLoader=new ImageLoader(activity.getApplicationContext()); pref = activity.getApplicationContext().getSharedPreferences("mbakami", 0);

  // 0 - for private mode editor = pref.edit(); //db = new DatabaseHandler(activity); this.TYPE = TYPE; }

  @Override public int getCount() { // TODO Auto-generated method stub return data.size();

  } @Override public Object getItem(int position) {

  // TODO Auto-generated method stub return position; } @Override public long getItemId(int position) {

  // TODO Auto-generated method stub return position; } @Override public View getView(int position, View convertView, ViewGroup parent) {

  // TODO Auto-generated method stub View vi=convertView; if(convertView==null){ if(TYPE.equals("makanan")){ vi = inflater.inflate(R.layout.makanan_row, null); } else if(TYPE.equals("minuman")){ vi = inflater.inflate(R.layout.minuman_row, null); } else { vi = inflater.inflate(R.layout.dessert_row, null); }

  } vi.setClickable(true); /*TextView nama = null; TextView harga = null; ImageView thumb_image = null; CheckBox chk = null;*/ if(TYPE.equals("makanan")){ nama = (TextView)vi.findViewById(R.id.nm_makanan); // nama makanan harga = (TextView)vi.findViewById(R.id.harga); // harga makanan thumb_image=(ImageView)vi.findViewById(R.id.image_makanan); // thumb image chk = (CheckBox)vi.findViewById(R.id.chk_makanan);

  } else if(TYPE.equals("minuman")){ nama = (TextView)vi.findViewById(R.id.nm_minuman); // nama minuman harga = (TextView)vi.findViewById(R.id.harga_minuman); // harga minuman thumb_image=(ImageView)vi.findViewById(R.id.image_minuman); // thumb image chk = (CheckBox)vi.findViewById(R.id.chk_minuman); } else { nama = (TextView)vi.findViewById(R.id.nm_dessert); // nama dessert harga = (TextView)vi.findViewById(R.id.harga_dessert); // harga dessert thumb_image=(ImageView)vi.findViewById(R.id.image_dessert); // thumb image chk = (CheckBox)vi.findViewById(R.id.chk_dessert); } HashMap<String, String> list = new HashMap<String, String>(); list = data.get(position); // Setting all values in listview if(TYPE.equals("makanan")){ nama.setText(list.get(MakananListActivity.TAG_NAME)); harga.setText(list.get(MakananListActivity.TAG_PRICE)); imageLoader.DisplayImage(list.get(MakananListActivity.TAG_IMAGE), thumb_image); chk.setTag(list.get(MakananListActivity.TAG_NAME).toString().toLowerC ase().replace(" ", "_")); vi.setTag(list.get(MakananListActivity.TAG_NAME).toString().toLowerCa se().replace(" ", "_")); } else if(TYPE.equals("minuman")){ nama.setText(list.get(MinumanListActivity.TAG_NAME)); harga.setText(list.get(MinumanListActivity.TAG_PRICE)); imageLoader.DisplayImage(list.get(MinumanListActivity.TAG_IMAGE), thumb_image); chk.setTag(list.get(MinumanListActivity.TAG_NAME).toString().toLowerC ase().replace(" ", "_")); vi.setTag(list.get(MakananListActivity.TAG_NAME).toString().toLowerCa se().replace(" ", "_")); } else { nama.setText(list.get(DessertListActivity.TAG_NAME)); harga.setText(list.get(DessertListActivity.TAG_PRICE)); imageLoader.DisplayImage(list.get(DessertListActivity.TAG_IMAGE), thumb_image); chk.setTag(list.get(DessertListActivity.TAG_NAME).toString().toLowerC ase().replace(" ", "_")); vi.setTag(list.get(MakananListActivity.TAG_NAME).toString().toLowerCa se().replace(" ", "_")); } if(pref!=null){

boolean checked = pref.getBoolean(chk.getTag().toString(), false); if(checked){ chk.setChecked(checked); if(pref.getString("tipe", "").equals("update")){ chk.setEnabled(false); }

  } } chk.setOnCheckedChangeListener(new OnCheckedChangeListener(){ @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // TODO Auto-generated method stub chkActionPerformed(buttonView, isChecked); } }); vi.setOnClickListener(new OnClickListener() {

  @Override public void onClick(View v) { // TODO Auto-generated method stub viewActionPerformed(v);

  } }); return vi;

  } protected void showDialog(Context context, String namaMenu){ dialog = new Dialog(context); dialog.setContentView(R.layout.jumlah_pesanan_dialog); dialog.setTitle("Jumlah pemesanan"); txtNamaMenu =

  (TextView)dialog.findViewById(R.id.txt_nama_menu); txtNamaMenu.setText(namaMenu); inputJumlah =

  (EditText)dialog.findViewById(R.id.txt_jumlah); String key = namaMenu.toString().toLowerCase().replace("

  ", "_"); String k = "amount_"+key; int j = pref.getInt(k, -1); if(j > 0){ inputJumlah.setText(j+""); } btnOK = (Button)dialog.findViewById(R.id.btn_ok); btnOK.setOnClickListener(new OnClickListener() {

  @Override public void onClick(View v) { btnOKActionPerformed(v);

  }

  }); dialog.setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) {

  // TODO Auto-generated method stub if(chk.isChecked() && chk.isEnabled()){ chk.setChecked(false); }

  } }); dialog.show();

  } private void chkActionPerformed(CompoundButton buttonView, boolean isChecked){ if(isChecked){

  String title = Utils.toTitleCase(buttonView.getTag().toString().replace("_", " ")); showDialog(activity, title); } else {

  Toast.makeText(activity, "Deselected: "+buttonView.getTag(), Toast.LENGTH_SHORT).show();

  String key = buttonView.getTag().toString().toLowerCase().replace(" ", "_"); editor.putBoolean(key, isChecked); editor.commit();

  } } private void viewActionPerformed(View v){ if(TYPE.equals("makanan")){ chk = (CheckBox)v.findViewById(R.id.chk_makanan); } else if(TYPE.equals("minuman")){ chk = (CheckBox)v.findViewById(R.id.chk_minuman); } else { chk = (CheckBox)v.findViewById(R.id.chk_dessert); } String title =

  Utils.toTitleCase(chk.getTag().toString().toString().replace("_", " ")); if(chk.getTag().equals(v.getTag())){ if(!chk.isChecked()){ chk.setChecked(true); } else { showDialog(activity, title); }

  } } private void btnOKActionPerformed(View v){ int jumlah =

  Integer.valueOf(inputJumlah.getText().toString()); String key = txtNamaMenu.getText().toString().toLowerCase().replace(" ", "_");

  String k = "amount_"+key; editor.putInt(k, jumlah); editor.putBoolean(key, true); editor.commit(); dialog.dismiss();

  } }

  JSONParser.java

  package com.ami.warungmbakami.resource; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONException; import org.json.JSONObject; import android.util.Log; public class JSONParser { private InputStream is = null; private JSONObject jObj = null; private String json = ""; private String url; // constructor public JSONParser(String url) { this.url = url; } public JSONObject getJSONfromURL(){ // Making HTTP request try { // defaultHttpClient

  HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(); request.setURI(new URI(url)); HttpResponse response = client.execute(request); is = response.getEntity().getContent();

  } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (URISyntaxException e) {

  // TODO Auto-generated catch block e.printStackTrace();

  } try { BufferedReader reader = new BufferedReader(new InputStreamReader( is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } this.is.close(); this.json = sb.toString(); } catch (Exception e) { Log.e("Buffer Error", "Error converting result " + e.toString()); } // try parse the string to a JSON object try { this.jObj = new JSONObject(this.json);

  } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data WOOOI " + e.getMessage()); } // return JSON String return this.jObj; } public JSONObject getJSONFromUrl(List<NameValuePair> params) { // Making HTTP request try { // defaultHttpClient DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); httpPost.setEntity(new UrlEncodedFormEntity(params)); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { BufferedReader reader = new BufferedReader(new InputStreamReader( is, "iso-8859-1"), 8);

  StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "n"); } is.close(); json = sb.toString(); Log.e("JSON", json); } catch (Exception e) { Log.e("Buffer Error", "Error converting result " + e.toString()); } // try parse the string to a JSON object try { jObj = new JSONObject(json); } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data " + e.toString()); } // return JSON String return jObj; } }

  Lampiran 4

  MenuController.php

  <?php class MenuController extends Controller {

  /**

  • @var string the default layout for the views. Defaults to '//layouts/column2', meaning
  • using two-column layout. See 'protected/views/layouts/column2.php'.
  • / public $layout='//layouts/column2'; /**
  • @return array action filters
  • / public function filters() { return array(

  'accessControl', // perform access control for CRUD operations 'postOnly + delete', // we only allow deletion via

  POST request );

  } /** * Specifies the access control rules.

  • This method is used by the 'accessControl' filter.
  • @return array access control rules
  • / public function accessRules() { return array( array('allow', // allow all users to perform

  'index' and 'view' actions 'actions'=>array('index','view','daftarmenu'),

  'users'=>array('*'), ), array('allow', // allow authenticated user to perform 'create' and 'update' actions

  'actions'=>array('create','update'), 'users'=>array('@'),

  ), array('allow', // allow admin user to perform 'admin' and 'delete' actions

  'actions'=>array('admin','delete'), 'users'=>array('admin'),

  ), array('deny', // deny all users 'users'=>array('*'),

  ), );

  } /**

  • Displays a particular model.
  • @param integer $id the ID of the model to be displayed
  • / public function actionView($id) {

  $this->render('view',array( 'model'=>$this->loadModel($id),

  )); } /** * Creates a new model.

  • If creation is successful, the browser will be redirected to the 'view' page.
  • / public function actionCreate() {

  $model=new Menu; // Uncomment the following line if AJAX validation is needed // $this->performAjaxValidation($model); if(isset($_POST['Menu'])) {

  //$nama=$_POST['Menu']['nama']; $uploadedFile=CUploadedFile::getInstance($model,

  'gambar'); $fileName = $uploadedFile->name;

  //$fileName = $nama.".".$uploadedFile- >extensionName; // random number + file name

  $model->attributes=$_POST['Menu']; $model->gambar = $fileName; if($model->save()){

  $uploadedFile->saveAs(Yii::app()- >basePath.'/../images/'.$fileName);

  $this->redirect(array('view','id'=>$model- >id_menu));

  } } $this->render('create',array(

  'model'=>$model, ));

  } /** * Updates a particular model.

  • If update is successful, the browser will be redirected to the 'view' page.
  • @param integer $id the ID of the model to be updated
  • / public function actionUpdate($id) {

  $model=$this->loadModel($id); // Uncomment the following line if AJAX validation is needed // $this->performAjaxValidation($model); if(isset($_POST['Menu'])) {

  $model->attributes=$_POST['Menu']; //$nama=$_POST['Menu']['nama']; $uploadedFile=CUploadedFile::getInstance($model, 'gambar'); //$fileName = $nama.".".$uploadedFile- >extensionName; // random number + file name $fileName = $uploadedFile->name; $model->gambar = $fileName; if($model->save()){ $uploadedFile->saveAs(Yii::app()- >basePath.'/../images/'.$fileName);

  $this->redirect(array('view','id'=>$model- >id_menu)); }

  } $this->render('update',array(

  'model'=>$model, ));

  } /** * Deletes a particular model.

  • If deletion is successful, the browser will be redirected to the 'admin' page.
  • @param integer $id the ID of the model to be deleted
  • / public function actionDelete($id) {

  $this->loadModel($id)->delete(); // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser if(!isset($_GET['ajax']))

  $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));

  } /** * Lists all models.

  • / public function actionIndex() {

  $dataProvider=new CActiveDataProvider('Menu'); $this->render('index',array(

  'dataProvider'=>$dataProvider, ));

  } /** * Manages all models.

  • / public function actionAdmin() {

  $model=new Menu('search');

  $model->unsetAttributes(); // clear any default values if(isset($_GET['Menu'])) $model->attributes=$_GET['Menu'];

  $this->render('admin',array( 'model'=>$model,

  )); } public function actionDaftarmenu($id = 1){

  $model = Menu::model()->findAll("id_jenis_menu = $id"); foreach($model as $value){ $json['detail'][] = array( 'nama_makanan' => $value->nama, 'harga_makanan' => $value->harga, 'gambar_makanan' => Yii::app()- >baseUrl.'/images/'.$value->gambar ); } echo json_encode($json); }

  /**

  • Returns the data model based on the primary key given in the GET variable.
  • If the data model is not found, an HTTP exception will be raised.
  • @param integer $id the ID of the model to be loaded
  • @return Menu the loaded model
  • @throws CHttpException
  • / public function loadModel($id) {

  $model=Menu::model()->findByPk($id); if($model===null) throw new CHttpException(404,'The requested page does not exist.'); return $model;

  } /** * Performs the AJAX validation.

  • @param Menu $model the model to be validated
  • / protected function performAjaxValidation($model) { if(isset($_POST['ajax']) && $_POST['ajax']==='menu-form') { echo CActiveForm::validate($model); Yii::app()->end();

  } }

  }

  PenjualanController.php <?php class PenjualanController extends Controller {

  /**

  • @var string the default layout for the views. Defaults to '//layouts/column2', meaning
  • using two-column layout. See 'protected/views/layouts/column2.php'.
  • / public $layout='//layouts/column2'; /**
  • @return array action filters
  • / public function filters() { return array(

  'accessControl', // perform access control for CRUD operations 'postOnly + delete', // we only allow deletion via

  POST request );

  } /** * Specifies the access control rules.

  • This method is used by the 'accessControl' filter.
  • @return array access control rules
  • / public function accessRules() { return array( array('allow', // allow all users to perform

  'index' and 'view' actions 'actions'=>array('index','view','devicecreate','deviceupdate',' devicegetdetails'),

  'users'=>array('*'), ), array('allow', // allow authenticated user to perform 'create' and 'update' actions

  'actions'=>array('create', 'update'), 'users'=>array('@'),

  ), array('allow', // allow admin user to perform 'admin' and 'delete' actions

  'actions'=>array('admin','delete', 'details'),

  'users'=>array('admin'), ), array('deny', // deny all users

  'users'=>array('*'), ),

  ); } /**

  • Displays a particular model.
  • @param integer $id the ID of the model to be displayed
  • / public function actionView($id) {

  $this->render('view',array( 'model'=>$this->loadModel($id),

  )); } public function actionDetails($id=""){ if(isset($_POST['bayar'])){ $penjualanModel = Penjualan::model()- >findByPk($_POST['idPenjualan']); $penjualanModel->is_paid = 1; $penjualanModel->save(); $mejaModel = Meja::model()- >findByPk($_POST['idMeja']); $mejaModel->is_empty = 1; $mejaModel->save(); $this- >redirect(array('details','id'=>$_POST['idPenjualan'])); } else { if(empty($id)){ $dataProvider=new CActiveDataProvider('Penjualan'); $this->render('details',array( 'dataProvider'=>$dataProvider, )); } else { $criteria = new CDbCriteria; $criteria->select = 'nama, jumlah, harga, harga*jumlah as total_harga, meja, tanggal, is_paid, j.id_meja'; $criteria->alias = 'p'; $criteria->join = 'LEFT JOIN tbl_penjualan_menu pm ON pm.id_penjualan = p.id_penjualan LEFT JOIN tbl_menu m ON m.id_menu = pm.id_menu LEFT JOIN tbl_meja j ON j.id_meja = p.id_meja'; $criteria->condition = "p.id_penjualan = $id"; $penjualanModel = Penjualan::model()- >findAll($criteria); $meja = $penjualanModel[0]->meja; $tanggal = $penjualanModel[0]->tanggal; $statusBayar = $penjualanModel[0]->is_paid ? "Sudah bayar" : "Belum bayar"; $this->render('detailpenjualan', array('dataPenjualan' => $penjualanModel, 'namaMeja' => $meja, 'tanggal' => $tanggal, 'statusBayar' => $statusBayar, 'id' => $id)); } } }

  /**

  • Creates a new model.
  • If creation is successful, the browser will be redirected to the 'view' page.
  • / public function actionCreate() {

  $model=new Penjualan; // Uncomment the following line if AJAX validation is needed // $this->performAjaxValidation($model); if(isset($_POST['Penjualan'])) {

  $model->attributes=$_POST['Penjualan']; if($model->save()) $this->redirect(array('view','id'=>$model-

  >id_penjualan)); } $this->render('create',array(

  'model'=>$model, ));

  } /** * Creates a new model.

  • If creation is successful, the browser will be redirected to the 'view' page.
  • / public function actionDevicecreate() { if (isset($_POST['tag']) && $_POST['tag'] != '') { if($_POST['tag'] == "pesan_baru"){ $data = $_POST['details']; $param = json_decode($data); //$transaction = Yii::app()->db- >beginTransaction();

  //try{ $namaMeja = $param->meja; $meja_is_empty = $param- >meja_is_empty; $tanggal = date("Y-m-d h:i:s"); $mejaModel = Meja::model()- >find("meja = '$namaMeja'"); $mejaModel->is_empty = $meja_is_empty; $mejaModel->save(); //if(!$mejaModel->save()){ // throw new Exception("saving status meja"); //} $idMeja = $mejaModel->id_meja;

  $penjualanModel = new Penjualan; $penjualanModel->id_meja = $idMeja; $penjualanModel->tanggal = $tanggal; $penjualanModel->save(); //if(!$penjualanModel->save()){ // throw new Exception("saving penjualan"); //} foreach($param->items as $item){ $penjualanMenuModel = new PenjualanMenu; $penjualanMenuModel- >id_penjualan = $penjualanModel->id_penjualan; $idmenu = Menu::model()- >find("nama = '".$item->menu_name."'")->id_menu; $penjualanMenuModel->id_menu = $idmenu; $penjualanMenuModel->jumlah = $item->amount; $penjualanMenuModel->save(); $stokModel = Stok::model()- >find("id_menu = $idmenu"); $oldJumlah = $stokModel- >jumlah; $newJumlah = $oldJumlah - $item->amount; $stokModel->jumlah = $newJumlah; $stokModel->save(); //if(!$penjualanMenuModel- >save() && !$stokModel->save()){ // throw new Exception("saving penjualan menu"); ///} } //$transaction->commit(); $response["success"] = 1; //} catch (Exception $e){ // $transaction->rollback(); // $response["error"] = 1; // $response["error_msg"] = "Error when $e"; // } else if($_POST['tag'] == "update_pesanan"){ $data = $_POST['details']; $param = json_decode($data); //$transaction = Yii::app()->db- >beginTransaction(); //try{ $namaMeja = $_POST['namaMeja']; $idMeja = Meja::model()->find("meja = '".$namaMeja."'")->id_meja; $idpenjualan = Penjualan::model()-

  >find("id_meja = ".$idMeja." and is_paid = 0")->id_penjualan; foreach($param->items as $item){ $idMenu = Menu::model()- >find("nama = '".$item->menu_name."'")->id_menu; $penjualanMenuModel = PenjualanMenu::model()->find("id_penjualan = '$idpenjualan' and id_menu = '$idMenu'"); if(count($penjualanMenuModel->id) <= 0){ $penjualanMenuModel = new PenjualanMenu(); $penjualanMenuModel->id_menu = $idMenu; $penjualanMenuModel- >id_penjualan = $idpenjualan; } $penjualanMenuModel->jumlah = $item->amount; $penjualanMenuModel->save(); $stokModel = Stok::model()- >find("id_menu = $idMenu"); $oldJumlah = $stokModel->jumlah; $newJumlah = $oldJumlah - $item- >amount; $stokModel->jumlah = $newJumlah; $stokModel->save(); //if(!$penjualanMenuModel- >save()){ // throw new Exception("updating penjualan menu"); //} } //$transaction->commit(); $response["success"] = 1; //} catch(Exception $e){ // $transaction->rollback(); // $response["error"] = 1; // $response["error_msg"] = "Error when $e"; //} } else { $response["error"] = 1; $response["error_msg"] = "Invalid request"; } } else { $response["error"] = 1; $response["error_msg"] = "Access Denied"; } echo json_encode($response);

  } private function selectedMeja($meja){ $criteria = new CDbCriteria;

  $criteria->select = 'm.id_menu, nama, jumlah, harga'; $criteria->alias = 'm'; $criteria->join = 'left join tbl_penjualan_menu pm on pm.id_menu = m.id_menu left join tbl_penjualan p on p.id_penjualan = pm.id_penjualan left join tbl_meja j on j.id_meja = p.id_meja'; $criteria->condition = 'is_paid = 0 and is_empty = 0 and j.meja = "'.$meja.'"'; $menuModel = Menu::model()->findAll($criteria); return $menuModel; } public function actionDevicegetdetails($meja){ $model = $this->selectedMeja($meja); $x = 0; foreach($model as $value){ $hargaTotal = $value->harga * $value->jumlah; $data['details'][] = array( 'name' => $value->nama/*str_replace(" ", "_", strtolower($value->nama))*/, 'amount' => $value->jumlah, 'tag_key' => str_replace(" ", "_", strtolower($value->nama)), 'harga_satuan' => $value->harga, 'harga_total' => $hargaTotal, ); $x += $hargaTotal; } $data['meja'] = $meja; $data['total'] = $x; echo json_encode($data); } public function actionDeviceupdate($meja){ $model = $this->selectedMeja($meja); foreach($model as $value){ $data['selected_tag'][] = array( 'name' => str_replace(" ", "_", strtolower($value->nama)), 'amount' => $value->jumlah, 'id_menu' => $value->id_menu, ); } echo json_encode($data); }

  /** * Updates a particular model.

  • If update is successful, the browser will be redirected to the 'view' page.
  • @param integer $id the ID of the model to be updated
  • / public function actionUpdate($id) {

  $model=$this->loadModel($id); // Uncomment the following line if AJAX validation is needed // $this->performAjaxValidation($model); if(isset($_POST['Penjualan'])) {

  $model->attributes=$_POST['Penjualan']; if($model->save()) $this->redirect(array('view','id'=>$model-

  >id_penjualan)); } $this->render('update',array(

  'model'=>$model, ));

  } /** * Deletes a particular model.

  • If deletion is successful, the browser will be redirected to the 'admin' page.
  • @param integer $id the ID of the model to be deleted
  • / public function actionDelete($id) {

  $this->loadModel($id)->delete(); // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser if(!isset($_GET['ajax']))

  $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));

  } /** * Lists all models.

  • / public function actionIndex() {

  $dataProvider=new CActiveDataProvider('Penjualan'); $this->render('index',array(

  'dataProvider'=>$dataProvider, ));

  } /** * Manages all models.

  • / public function actionAdmin() {

  $model=new Penjualan('search'); $model->unsetAttributes(); // clear any default values if(isset($_GET['Penjualan']))

  $model->attributes=$_GET['Penjualan'];

  $this->render('admin',array( 'model'=>$model,

  )); } /**

  • Returns the data model based on the primary key given in the GET variable.
  • If the data model is not found, an HTTP exception will be raised.
  • @param integer $id the ID of the model to be loaded
  • @return Penjualan the loaded model
  • @throws CHttpException
  • / public function loadModel($id) {

  $model=Penjualan::model()->findByPk($id); if($model===null) throw new CHttpException(404,'The requested page does not exist.'); return $model;

  } /** * Performs the AJAX validation.

  • @param Penjualan $model the model to be validated
  • / protected function performAjaxValidation($model) { if(isset($_POST['ajax']) && $_POST['ajax']==='penjualan- form')

  { echo CActiveForm::validate($model); Yii::app()->end();

  } }

  }

Dokumen yang terkait

Pengaruh Ketidakpuasan Konsumen Dan Kebutuhan Mencari Variasi Terhadap Keputusan Perpindahan Merek Dari Smartphone Blackberry Pada Mahasiswa Program Studi Manajemen Fakultas Ekonomi Dan Bisnis Universitas Sumatera Utara

0 1 11

BAB II TINJAUAN PUSTAKA 2.1 Merek 2.1.1 Pengertian Merek - Pengaruh Ketidakpuasan Konsumen Dan Kebutuhan Mencari Variasi Terhadap Keputusan Perpindahan Merek Dari Smartphone Blackberry Pada Mahasiswa Program Studi Manajemen Fakultas Ekonomi Dan Bisnis Uni

0 0 15

BAB I LATAR BELAKANG 1.1 Latar Belakang - Pengaruh Ketidakpuasan Konsumen Dan Kebutuhan Mencari Variasi Terhadap Keputusan Perpindahan Merek Dari Smartphone Blackberry Pada Mahasiswa Program Studi Manajemen Fakultas Ekonomi Dan Bisnis Universitas Sumatera

0 0 9

Pengaruh Ketidakpuasan Konsumen Dan Kebutuhan Mencari Variasi Terhadap Keputusan Perpindahan Merek Dari Smartphone Blackberry Pada Mahasiswa Program Studi Manajemen Fakultas Ekonomi Dan Bisnis Universitas Sumatera Utara

0 0 10

2. Form Sub Menu - Implementasi Algoritma Shannon-Fano Pada Kompresi Audio

0 1 10

Pengaruh Program CSR Terhadap Kepuasan Kerja Pada PT Toba Pulp Lestari kabupaten Toba Samosir Sumatera Utara

0 0 10

Form Utama menggunakan MDIFORM

0 0 25

BAB II PT TASPEN (PERSERO) KANTOR CABANG UTAMA MEDAN A. Sejarah Singkat - Pengendalian Internal Gaji dan Upah pada PT. Taspen (Persero) Kantor Cabang Utama Medan

0 4 16

LISTING PROGRAM Kode Program Form Main (Menu Utama) :

0 2 25

LISTING PROGRAM Form Menu Utama

0 0 11