Custom forms for editing elements. Editing data in PHP Php editing data


We made a small application that used a single table. The application created a model, a controller, and several views to view and add categories to a database table. In this lesson we will continue working on the application and build functionality for checking, as well as for editing and deleting data from the category table.

Data validation in CakePHP is done in the model. Adding it is very simple. Since our table only has one field to check, we only need to check for the presence of a value as we enter. Let's change the code in the file /app/models/category.php :

Class Category extends AppModel ( var $name = "Category"; var $validate = array("name" => array("rule" => "notEmpty")); )

Array $validate tells CakePHP how to validate your data when calling a method save(). In our example, we indicate that the field name must have a value (that is, not be empty). CakePHP's validation engine has several built-in rules (validating credit card numbers, email addresses, etc.) and allows you to add your own validation rules. We will look at it in more detail when expanding our application to a job board.

Data validation is an important part of any application, as it helps determine the consistency of the data in the model and the logic of the application.

Now we have a validation rule. Try adding a category with an empty name field. Since we used the method input() form builder to create our elements, then an error message will appear automatically.

You can write your own error message. Try using the following code in your model file:

Class Category extends AppModel ( var $name = "Category"; var $validate = array("name" => array("rule" => "notEmpty", "message" => "The category must have a name!")) ; )

Let's add functionality for editing and deleting categories.

Let's do the removal first. Open the file and add the following function immediately after the function add():

Function delete($id) ( $this->Category->delete($id); $this->Session->setFlash("Category with id: ".$id." has been deleted."); $this->redirect (array("action"=>"index")); )

Since this function only removes the category and redirects the application logic to the action index controller, then we don't need to create a view. However, we need to change our view index to add a link to delete a category. Open the file /app/view/categories/index.ctp and change it so that it looks like this:

Categories

link("Add category",array("controller" => "categories", "action" => "add")); ?>
ID Name Actions
link($category["Category"]["name"], array("controller" => "categories", "action" => "view", $category["Category"]["id"])); ?> link("Delete", array("action" => "delete", $category["Category"]["id"]), null, "Are you sure?")?>

Now try deleting the category. CakePHP automatically generates a Javascript dialog with a question "Are you sure?" .

Now let's add a function for editing a category to our controller. Copy the following code to a file /app/controllers/categories_controller.php :

Function edit($id = null) ( $this->Category->id = $id; if (empty($this->data)) ( $this->data = $this->Category->read(); ) else ( if ($this->Category->save($this->data)) ( $this->Session->setFlash("Your category has been changed."); $this->redirect(array("action" => "index")); ) ) )

This function first checks to see if any form data has been submitted. If nothing was passed in, it finds the category and passes it to the view. If any data has been transferred, it tries to save it using the model.

For this functionality we need a view. Create a file /app/views/categories/edit.ctp and copy the code into it:

Editing a category

create(" Category ", array("action" => "edit")); echo $form->input("name"); echo $form->input("id", array("type"=>"hidden")); echo $form->end("Save"); ?>

This view displays a form for editing (with fields filled in).

One thing to note is that CakePHP assumes you are editing the model if the ‘ field is present id’ in the data array. If the 'id' field is missing (look at the view add), CakePHP assumes that you are inserting new data when the method is called save().

Now you can update the view index a link to edit a specific category, that is, a file /app/views/categories/index.ctp should look like this:

link("Add category",array("controller" => "categories", "action" => "add")); ?>

ID Name Actions
link($category["Category"]["name"], array("controller" => "categories", "action" => "view", $category["Category"]["id"])); ?> link("Delete", array("action" => "delete", $category["Category"]["id"]), null, "Are you sure?")?>link("Edit", array("action"=>"edit", $category["Category"]["id"]));?>

Now our little CakePHP application is complete!

Let's now look at routes in CakePHP. For some, CakePHP's default routing will suit their needs just fine. Developers who are looking to build an easy to use application interface and make it crawler friendly will be pleased with the way CakePHP action URLs are generated. But for training purposes we will change the routing.

By default, CakePHP responds to requests to the root address of your site (for example, http://www.example.com) using a page controller PagesController which displays a view called “ home" We'll change the route to our category controller by creating a rule accordingly.

CakePHP routing is in the file /app/config/routes.php . You can comment out or delete the line that defines the default route. It looks like this:

Router::connect ("/", array("controller"=>"pages", "action"=>"display", "home"));

Now let's add the line below:

Router::connect("/", array("controller"=>"categories", "action"=>"index"));

This way the user requesting '/' will be directed to the action index() our category controller. Now we can access our application through the root address (for example, http://localhost/cake).

In the next tutorial, we will start understanding the Bake CakePHP application generator.

The form for adding/changing elements of information blocks is one of the most frequently used, and in online stores or information publications this form is definitely the most popular in the administrative section. And despite the fact that the appearance and fields of the form change depending on the settings of the information block, and you can also customize the appearance of the form for editing elements using standard system tools, for specific tasks, sometimes this is not enough.

In this case, one or two (depending on the task) additional files should be created in /bitrix/php_interface/include/:

Then, in the information block settings, set the paths to these files:

File with element editing form

Let's create, for example, a file in the /bitrix/php_interface/include/ folder iblock_element_edit_my.php, then copy the code from the file /bitrix/modules/iblock/admin/iblock_element_edit.php into it from the line:

to the line:

///////////////////////// //END of the custom form ///////////////// /////////

Important! Don't forget to include the necessary namespaces in your file (see the first lines of the file /bitrix/modules/iblock/admin/iblock_element_edit.php).

Now you can start editing the file, i.e. to change the appearance of the information block element editing form to suit your own needs. (Before the procedure, you must cancel the form settings, if any were previously made.)

  • You can delete information block fields that you do not need. To display form fields, constructs of the following type are used:BeginCustomField("ACTIVE_TO", GetMessage("IBLOCK_FIELD_ACTIVE_PERIOD_TO"), $arIBlock["FIELDS"]["ACTIVE_TO"]["IS_REQUIRED"] === "Y"); ?> GetCustomLabelHTML()?>:EndCustomField("ACTIVE_TO", "
  • To display the properties of information block elements in the form, use the function _ShowPropertyField(): BeginCustomField("PROPERTY_".$prop_fields["ID"], $prop_fields["NAME"], $prop_fields["IS_REQUIRED"]==="Y"); ?> <? $tabControl->EndCustomField("PROPERTY_".$prop_fields["ID"], $hidden); ?>

When using a custom form, the button disappears on the element edit page Tune, which allows you to sort and customize the display of element form fields.

To avoid adding a field sorting mechanism to iblock_element_edit_my.php And without abandoning the standard function, you need to add the following code to the file:

GetCurPage()."?mode=settings".($link<>""? "&".$link:""); $aMenu = array("TEXT"=>GetMessage("IBEL_E_SETTINGS"), "TITLE"=>GetMessage("IBEL_E_SETTINGS_TITLE"), "LINK"=>"javascript:".$tabControl->GetName().".ShowSettings ("".urlencode($link)."")", "ICON"=>"btn_settings",); $context = new CAdminContextMenu($aMenu); $context->Show(); ) ?>

Important!

The file responsible for processing the element's fields before saving it

To change the saved fields, you need to modify the fields of the same name in the $_POST and $_FILES arrays, the values ​​of all properties must be modified in the $PROP array.

Let's create, for example, a file in /bitrix/php_interface/include/ iblock_element_edit_before_save.php.

To check that the detailed text of an element has been entered, use the following condition:

If (strlen($_POST["DETAIL_TEXT"])<=0) $error = new _CIBlockError(2, "DESCRIPTION_REQUIRED", "Введите текст статьи");

Object constructor _CIBlockError takes three parameters: error severity, a custom identifier, and error text. If on the editing page you define the $error variable with the value of this object, then the changes made will not be saved. To ensure that the values ​​coming from the form are not lost, after initializing the $error variable, also initialize the $bVarsFromForm=true variable. The $bVarsFromForm variable specifies that the values ​​in the fields should be shown as those that came from the form.

To automatically create a small image based on a large one, we will use the function BXIBlockAfterSave. If you define it before saving the element, it will be automatically called after the element is successfully saved. Let's define it at the beginning of the file /bitrix/php_interface/include/iblock_element_edit_before_save.php:

Fetch()) && $ar["DETAIL_PICTURE"]>< $height_orig)) $width = ($height / $height_orig) * $width_orig; else $height = ($width / $width_orig) * $height_orig; $image_p = imagecreatetruecolor($width, $height); $image = imagecreatefromjpeg($img_path); imagecopyresized($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig); $new_img_path = tempnam("/tmp", "FOO").".jpg"; imagejpeg($image_p, $new_img_path); $be = new CIBlockElement(); $be->Update($arFields["ID"], Array("PREVIEW_PICTURE" => CFile::MakeFileArray($new_img_path)), false); @unlink($new_img_path); ) ) ?>

Note: in the above script, a small one will be created based on a large image and this image will be inserted into the field for the small image. The example only works with images in the format JPG.

Here is the complete code for the page /bitrix/php_interface/include/iblock_element_edit_before_save.php:

0 && $view!="Y" && (!$error) && empty($dontsave) && strlen($_POST["DETAIL_TEXT"])<=0) $error = new _CIBlockError(2, "DESCRIPTION_REQUIRED", "Введите текст статьи"); function BXIBlockAfterSave($arFields) { $dbr = CIBlockElement::GetByID($arFields["ID"]); if(($ar = $dbr->Fetch()) && $ar["DETAIL_PICTURE"]>0) ( $img_path = $_SERVER["DOCUMENT_ROOT"].CFile::GetPath($ar["DETAIL_PICTURE"]); $width = 200; $height = 200 ; list($width_orig, $height_orig) = getimagesize($img_path); if($width && ($width_orig< $height_orig)) $width = ($height / $height_orig) * $width_orig; else $height = ($width / $width_orig) * $height_orig; $image_p = imagecreatetruecolor($width, $height); $image = imagecreatefromjpeg($img_path); imagecopyresized($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig); $new_img_path = tempnam("/tmp", "FOO").".jpg"; imagejpeg($image_p, $new_img_path); $be = new CIBlockElement(); $be->Update($arFields["ID"], Array("PREVIEW_PICTURE" => CFile::MakeFileArray($new_img_path)), false); @unlink($new_img_path); ) ) ?>

Important! Don't forget to specify the path to this file in the infoblock settings.


Sometimes it is necessary to make changes of a completely different nature, for example, an input form and changing several pictures at the same time, in this case you just need to create your own new page and add it to the administrative menu.

Dear site visitors who ask questions like “How to attach your shopping cart to the site?” and so on. I don’t make ready-made solutions, I describe the implementation logic, for each individual site you will need to add certain things in any case, so if you really need to screw or attach something, I provide paid and free services for consulting and website development. Write to the feedback form at the top of the page, I will answer everyone.


Editing a MySQL cell (prerequisites for creating your own CMS, UPDATE statement)

In this article I will give an example of how to make an editor for site content, i.e. editing information contained in the MySQL database. So, there is the following task: edit a record in a database table. Editing will take place from a regular HTML form. The first thing you need to do is select the required values ​​from the table. You can read how to do this. For example, let's take the table of products from the article about the online store cart. The logic of the script is as follows:

  1. We check whether the “Edit” button was clicked.
  2. If not, we display the form with the fields filled in
  3. If yes, change the contents of the desired cell.

Let's start with the form, it's easier this way. Create the update.php page. The structure of the product table is as follows: 1. id (smallint) 2. product name name(text field varchar(255)) 3. product price (float).
Select a value from the database:



?>



”/>




The form for editing is ready. The next step is to set a condition that will determine whether the user has clicked on the edit button, or whether he just wants to edit the data.
The condition is extremely simple. Pay attention to the hidden field called edit, it is this that tells the script that the data needs to be edited:

if (!isset($_POST[‘edit’]) (
$q=mysql_query("SELECT * FROM products WHERE id='$id'");
$product=mysql_fetch_assoc($q);
?>



”/>




}
else(
//Edit the data:
$q=mysql_query("UPDATE products SET name='".$_POST['name']."', price='".$_POST['price']."' WHERE id='".$_POST[' id'].”'”);
if (!q) (
echo “The SQL query failed”;
}
}
?>

Please note that the form handler and the form itself are on the same update.php page. Thus, now we can edit data in the MySQL database, and then modify the form to suit your data structure.
Note: Please note that you need to pass the id value by which the product is selected to the update.php page; usually it can be passed using the GET method by adding the id value, i.e. the link to the editing page will look like this: update.php?id=…

Last update: 11/1/2015

Editing existing data will be a little more difficult than retrieving and adding data from the database. First of all, because here we need to combine, firstly, receiving edited data, and then updating the database with new values.

The SQL statement "UPDATE" is used to update:

$query ="UPDATE products SET name="Samsung ACE II", company="Samsung" WHERE id="1"";

After the word SET there is a list of column names and new values ​​for them. At the end of the query line, a selector is specified using a WHERE clause. In this case, all rows with id="1" are set to name="Samsung ACE II" and company="Samsung"

Now let's create a new file edit.php, which will contain the editing logic. And add the following content to it:

Data updated"; ) // if the request is GET if(isset($_GET["id"])) ( $id = htmlentities(mysqli_real_escape_string($link, $_GET["id"])); // creating a query string $query = "SELECT * FROM tovars WHERE id = "$id""; // execute the query $result = mysqli_query($link, $query) or die("Error " . mysqli_error($link)); //if the query contains more than zero rows if($result && mysqli_num_rows($result)>0) ( $row = mysqli_fetch_row($result); // get the first row $name = $row; $company = $row; echo "

Change model

Enter model:

Manufacturer:

"; mysqli_free_result($result); ) ) // close the connection mysqli_close($link); ?>

Structurally, the entire code is divided into two parts: processing a POST request and processing a GET request. Processing a POST request is similar to adding data, only in this case the UPDATE expression is used: "UPDATE goods SET name="$name", company="$company" WHERE id="$id""

When processing a GET request, we get the id of the record and from it we get the entire record using the expression "SELECT * FROM tovars WHERE id = "$id"" . If more than zero lines are received, then we display the contents of the line in the form for editing.

Now, to edit the first entry, we need to access the script in the browser at http://localhost:8080/edit.php?id=1.

We continue the series of lessons on working with MySql databases. In this lesson we will learn how to edit information in a MySql database directly from a web page.

You may need such features when you allow the user of your resource to fill out their profile and also edit it. This knowledge will also be useful if you are writing an administrative section for a site and want to be able to edit records without going into the database.

In previous lessons, we created a MySql database, populated it, and created code to display information from the database, as well as to add new records to the database directly from the web page.

In this tutorial I will continue to use the existing file structure. All files for this lesson are in the source code for this lesson.

So let's get started!

Editing a record in the MySql database from a web page.

What do we need to do?

1. We create a button that will request all records from the database.

2. Create a file in which all the records in the database will be displayed in a list (in order to select the one that we want to edit).

3. When you select a specific record, a file handler is activated, which takes from the database all the information on the record we need.

4. The selected information is inserted into the fields of the edit form that we will create.

5. After editing, using a specific SQL query, the information is sent for updating to the MySql database.

1. The first thing we will do is create a file “select_change.php” and place it in the same directory as all our main files (that is, the main directory).

Before we start working with it, let's open the files: “search_user.html”, “info_form.html”, “select_user.php”, “all_users.php” and add a link to this file so that it is accessible from all files our application (this is for convenience, so as not to write its address in the address bar every time when we test our web pages).

Add the following line to each file before the closing tag body.

Edit Database Entry

2. Now let’s open the “select_change.php” file itself. We will only display the first and last name from the database to select the user whose information we want to edit.

To do this, we will first create a database query that will tell us to select all records from the database, and then display the first and last names of each person in a list.

We will display data as radio buttons. We do this so that we can select a user (and only one).

We will request only 3 parameters from the database: id, first_name, last_name. The last two will be displayed on the screen so that we can decide what information from the database we will edit. The id parameter will be invisible (it will be the value of the attribute value), but it is necessary so that the program can identify the selected element in the database (surnames and first names can be repeated, and id is always individual).

Please also pay attention to the way the information in this file is displayed. You may see symbols like %s.

The principle here is this: the html code is displayed in double quotes in the “printf” function, instead of a certain variable (for example, such as “$row[‘first_name’]”) we put anchors - %s. And after the double quotes are closed, we list these variables corresponding to the supplied anchors. This is convenient when working with the “printf” function, but you should pay attention to the order of the anchors and enumerated variables, since they will be substituted in exactly the order in which you enumerate them.

All this is enclosed in a form tag with action="edit.php". We will create the edit.php file in the next step.

So, the code for our “select_change.php” file will look like this:

Selecting a user to edit.

%s %s

", $row["id"], $row["first_name"], $row["last_name"]); ) while($row = mysql_fetch_array($result)) ?>
Add user

Return to search

And if you load the page in the browser, you will see something like this:

3. Create a file “edit.php” and place it there in the main directory.

This file is the handler file of our previous file. It will display a form and automatically fill it with information from the MySql database of the record we have selected.

In addition, in this form you can change one or more parameters (for example, first name, last name, etc.).

First, the program must understand what kind of recording you require from it. And for this a parameter must be passed id. Name for input in the last file we gave - “user”, in the same place we have it stored in the attribute value necessary id. Therefore, you can get it by requesting it using “$_REQUESR[‘user’]”. And then put the result into a variable "$id".

Secondly, we need to create a query that will display from our database table all information about the record with the specified identifier.

Thirdly, you need to execute this request and display each parameter in the field provided for it (in the attributes value).

Here is the code for all of the above:

We make changes











",$row["id"], $row["first_name"], $row["last_name"], $row["email"], $row["facebook"]); ?> Add user

Return to search



Please note that our form action='scripts/update.php'. We will create this file in the next step.

Also note that the id parameter is also passed, but we won’t see it because it is assigned type=’hidden’. You need to transfer it, but it is better not to give the opportunity to change it in order to prevent mistakes.

And here is the result we have achieved so far:

4. Well, there's only a little left!

You need to create a file update.php and put it in the scripts folder.

What will this file do?

It will receive all entered values ​​from the previous file and put each one into a variable.

Then he will generate a query to the database, in which he will ask to update the record taking into account the transmitted identifier, substituting the corresponding variable in the appropriate field.

Afterwards, he will send a request for execution and display the result to us in the form of a text message (either everything went well, or an error occurred).

Here is the code for this file:

Untitled Document The entry has been successfully updated!

"; ?> Add user

Return to search

Return to selecting entries to edit

And here is the result of this script:

So, at the moment (if you have completed all 4 lessons in this series) you have an application with which you can add new records to the database, display them in a list, or search and display them by the desired first and last name, as well as edit existing records.

Agree, not a little. And all this without going into the database itself. Everything comes from web pages.

In the next lesson I will tell you how to delete selected records from the database.

If you have not yet subscribed to blog updates, be sure to subscribe so as not to miss new lessons.

I also look forward to your feedback and comments.

Good luck, and see you in the next lesson!







2024 gtavrl.ru.